diff options
author | Jesús <heckyel@hyperbola.info> | 2022-02-28 07:51:38 +0800 |
---|---|---|
committer | Jesús <heckyel@hyperbola.info> | 2022-02-28 07:51:38 +0800 |
commit | 1079d1cee4a1389a6b697ae7e08a1c6835adcd52 (patch) | |
tree | 23937d314af363b5c60ed06a02ba8a997350792e | |
parent | 958aea082131b4e8bda224d0bba36e56df400a18 (diff) | |
download | mediagoblin-1079d1cee4a1389a6b697ae7e08a1c6835adcd52.tar.lz mediagoblin-1079d1cee4a1389a6b697ae7e08a1c6835adcd52.tar.xz mediagoblin-1079d1cee4a1389a6b697ae7e08a1c6835adcd52.zip |
Add plyr as player default and remove NodeJS, npm and videojs
43 files changed, 36066 insertions, 259 deletions
diff --git a/.bowerrc b/.bowerrc deleted file mode 100644 index 8c122aa3..00000000 --- a/.bowerrc +++ /dev/null @@ -1,3 +0,0 @@ -{"directory": "extlib/", - "analytics": false -}
\ No newline at end of file diff --git a/.builds/debian-10-sqlite.yml b/.builds/debian-10-sqlite.yml index 95e31901..18751610 100644 --- a/.builds/debian-10-sqlite.yml +++ b/.builds/debian-10-sqlite.yml @@ -2,8 +2,6 @@ image: debian/buster packages: # Install bootstrap and configure dependencies. - automake - - nodejs - - npm - python3-dev - virtualenv diff --git a/.builds/debian-11-sqlite.yml b/.builds/debian-11-sqlite.yml index 1ff1dd22..5a0d493a 100644 --- a/.builds/debian-11-sqlite.yml +++ b/.builds/debian-11-sqlite.yml @@ -2,8 +2,6 @@ image: debian/bullseye packages: # Install bootstrap and configure dependencies. - automake - - nodejs - - npm - python3-dev - virtualenv @@ -71,4 +69,3 @@ tasks: # Build the documentation. cd docs && make html - diff --git a/.builds/fedora-33-sqlite.yml b/.builds/fedora-33-sqlite.yml index 82fd5d9c..577fb972 100644 --- a/.builds/fedora-33-sqlite.yml +++ b/.builds/fedora-33-sqlite.yml @@ -4,11 +4,9 @@ packages: - automake # - gcc # - make - - nodejs - - npm - python3-devel - virtualenv - + # Install make and runtime dependencies. # - findutils - python3-lxml @@ -34,7 +32,7 @@ packages: - python3-gobject - python3-gstreamer1 - gstreamer1-plugin-openh264 - + # # Install raw image dependencies. # - libexiv2-dev # - libboost-python-dev @@ -47,7 +45,7 @@ packages: # Install OpenID dependencies. - python3-openid - + tasks: - core: | cd mediagoblin diff --git a/.builds/ubuntu-20.04.yml b/.builds/ubuntu-20.04.yml index be9a8fb9..9fbd53dd 100644 --- a/.builds/ubuntu-20.04.yml +++ b/.builds/ubuntu-20.04.yml @@ -2,8 +2,6 @@ image: ubuntu/20.04 packages: # Install bootstrap and configure dependencies. - automake - - nodejs - - npm - python3-dev - virtualenv @@ -69,4 +67,3 @@ tasks: # Build the documentation. cd docs && make html - diff --git a/.dockerignore b/.dockerignore index 31b0f398..3d1bd603 100644 --- a/.dockerignore +++ b/.dockerignore @@ -5,7 +5,6 @@ bin lib lib64 -node_modules user_dev .tox dist @@ -29,7 +29,6 @@ /.eggs/ /env /mediagoblin.ini -/node_modules/ /pip-selfcheck.json # pyconfigure/automake generated files @@ -62,8 +61,6 @@ venv* # extlib things /extlib/jquery/ /extlib/leaflet/ -/extlib/video.js/ -/extlib/videojs-resolution-switcher # Mac files .DS_Store diff --git a/.gitmodules b/.gitmodules index e4f5247d..51b3b4ba 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,15 @@ +[submodule "extlib/jquery"] + path = extlib/jquery + url = https://github.com/jquery/jquery +[submodule "extlib/leaflet"] + path = extlib/leaflet + url = https://github.com/Leaflet/Leaflet [submodule "extlib/pdf.js"] path = extlib/pdf.js url = https://github.com/mozilla/pdf.js.git -[submodule "extlib/skeleton"] - path = extlib/skeleton - url = https://github.com/dhg/Skeleton.git [submodule "extlib/sandyseventiesspeedboat"] path = extlib/sandyseventiesspeedboat url = https://github.com/jpope777/sandyseventiesspeedboat-mg.git +[submodule "extlib/skeleton"] + path = extlib/skeleton + url = https://github.com/dhg/Skeleton.git diff --git a/Dockerfile-debian-11-sqlite b/Dockerfile-debian-11-sqlite index 50133fd0..ae482259 100644 --- a/Dockerfile-debian-11-sqlite +++ b/Dockerfile-debian-11-sqlite @@ -59,8 +59,6 @@ FROM debian:bullseye RUN apt-get update && apt-get install -y \ automake \ git \ -nodejs \ -npm \ python3-dev \ virtualenv diff --git a/Dockerfile-fedora-33-sqlite b/Dockerfile-fedora-33-sqlite index 8569b6d7..60c4cca3 100644 --- a/Dockerfile-fedora-33-sqlite +++ b/Dockerfile-fedora-33-sqlite @@ -15,8 +15,6 @@ automake \ gcc \ git-core \ make \ -nodejs \ -npm \ python3-devel \ virtualenv diff --git a/MANIFEST.in b/MANIFEST.in index afa295cb..309f8737 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -23,5 +23,4 @@ include COPYING AUTHORS include lazyserver.sh lazystarter.sh lazycelery.sh runtests.sh include configure.ac configure install-sh include Makefile.in -include bower.json include mediagoblin/static/metadata/rdfa11.jsonld diff --git a/Makefile.in b/Makefile.in index 7b21241f..713f26d6 100644 --- a/Makefile.in +++ b/Makefile.in @@ -9,11 +9,11 @@ # without any warranty. # List whatever files you want to include in your source distribution here. -# You can include whole directories but note that *everything* under that +# You can include whole directories but note that *everything* under that # directory will be included DISTFILES = PKG-INFO Makefile.in configure setup.py install-sh -DESTDIR = +DESTDIR = VPATH = @srcdir@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ @@ -46,7 +46,7 @@ pkgdatadir = $(datadir)/@PACKAGE_NAME@ pkgincludedir = $(includedir)/@PACKAGE_NAME@ PYTHONPATH = $(pythondir)$(PATH_SEPARATOR)$(DESTDIR)$(pythondir) -EXTLIB_INSTALLS = extlib/jquery extlib/video.js extlib/leaflet +EXTLIB_INSTALLS = extlib/jquery extlib/leaflet # pkgpythondir = @pkgpythondir@ # pkgpyexecdir = @pkgpyexecdir@ @@ -75,14 +75,14 @@ else maybe_venved = maybe_venved_python = $(PYTHON) # No need for commands to build virtualenv as a dependency! -maybe_venv_dep = +maybe_venv_dep = # Nor to clean up! -maybe_venv_clean = +maybe_venv_clean = endif .PHONY: all install uninstall distclean info install-html html \ install-pdf pdf install-dvi dvi install-ps ps clean dist check \ -installdirs i18n virtualenv docs extlib +installdirs i18n virtualenv docs # update postgresql @@ -95,11 +95,6 @@ else cd docs && make html endif -# In the future we may provide more options than just npm/bower here -# eg, we may support guix updating. -extlib: - ./devtools/update_extlib.sh - develop: $(maybe_venv_dep) i18n mediagoblin.ini # NEVER clobber a user's mediagoblin.ini once they've defined it @@ -131,16 +126,16 @@ clean-virtualenv: rm -rf ./include/ endif -# setup.py doesn't (yet) support an uninstall command, so until it does, you +# setup.py doesn't (yet) support an uninstall command, so until it does, you # must manually remove everything that was installed here. The following example -# should remove a basic package installed via setup.py, but please double- and +# should remove a basic package installed via setup.py, but please double- and # triple-check it so that you don't remove something you shouldn't! # Be sure to remove any extra files you install, such as binaries or documentation! -# -# uninstall: +# +# uninstall: # rm -rvf $(pkgpythondir) # rm -v $(pythondir)/$(PACKAGE_DISTNAME)-*.egg-info -# +# # We don't know what this does yet. # Originally: @@ -163,7 +158,6 @@ distclean: $(maybe_venv_clean) rm -rvf $(srcdir)/autom4te.cache rm -vf $(srcdir)/aclocal.m4 rm -rf $(EXTLIB_INSTALLS) - rm -rf node_modules rm -vf $(srcdir)/Makefile check: diff --git a/bower.json b/bower.json deleted file mode 100644 index 4e2756d2..00000000 --- a/bower.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "mediagoblin-extlib", - "description": "External libraries used by GNU MediaGoblin", - "author": "MediaGoblin team <devel@mediagoblin.org>", - "private": true, - "ignore": [ - "**/.*", - "node_modules", - "bower_components", - "extlib/", - "test", - "tests" - ], - "dependencies": { - "jquery": "~2.1.3", - "video.js": "~5.20.1", - "videojs-resolution-switcher": "~0.4.2", - "leaflet": "~0.7.3" - } -} diff --git a/devtools/update_extlib.sh b/devtools/update_extlib.sh deleted file mode 100755 index bc39a3cf..00000000 --- a/devtools/update_extlib.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/sh - -# GNU MediaGoblin -- federated, autonomous media hosting -# Copyright (C) 2015 GNU MediaGoblin Contributors. See AUTHORS. -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see <http://www.gnu.org/licenses/>. - - -set -e - -# Make sure we have npm available - -if ! which npm > /dev/null 2>&1; then - echo "Can't find npm, no way to install extlib :("; - exit 1; -fi - -# Install bower if need be -if which bower > /dev/null 2>&1; then - BOWER=`which bower`; -elif [ -f ./node_modules/.bin/bower ]; then - BOWER="./node_modules/.bin/bower"; -else - echo "Bower not found, installing via npm!"; - npm install bower; - BOWER="./node_modules/.bin/bower"; -fi - -# Do package/file installs -$BOWER install diff --git a/docs/source/siteadmin/deploying.rst b/docs/source/siteadmin/deploying.rst index 54906cfb..01e5c477 100644 --- a/docs/source/siteadmin/deploying.rst +++ b/docs/source/siteadmin/deploying.rst @@ -42,10 +42,10 @@ alternative deployment options. Throughout the documentation we use the ``sudo`` command to indicate that an instruction requires elevated user privileges to run. You can issue these commands as the ``root`` user if you prefer. - + If you need help configuring ``sudo``, see the `Debian wiki <https://wiki.debian.org/sudo/>`_ or the - `Fedora Project wiki <https://fedoraproject.org/wiki/Configuring_Sudo/>`_. + `Fedora Project wiki <https://fedoraproject.org/wiki/Configuring_Sudo/>`_. Prepare System @@ -63,7 +63,6 @@ MediaGoblin has the following core dependencies: - `Python Imaging Library <http://www.pythonware.com/products/pil/>`_ (PIL or Pillow) - `virtualenv <http://www.virtualenv.org/>`_ -- `Node.js <https://nodejs.org>`_ These instructions have been tested on Debian 11 and Fedora 33. These instructions should approximately translate to recent Debian @@ -76,11 +75,11 @@ Issue the following commands: # Debian 11 sudo apt update - sudo apt install automake git nodejs npm python3-dev \ + sudo apt install automake git python3-dev \ python3-gst-1.0 python3-lxml python3-pil virtualenv # Fedora 33 - sudo dnf install automake gcc git-core make nodejs npm \ + sudo dnf install automake gcc git-core make \ libffi-devel python3-devel python3-lxml python3-pillow \ virtualenv @@ -169,7 +168,7 @@ MediaGoblin does not require special permissions or elevated access to run. As such, the preferred way to run MediaGoblin is to create a dedicated, unprivileged system user for the sole purpose of running MediaGoblin. Running MediaGoblin processes under an unprivileged system user -helps to keep it more secure. +helps to keep it more secure. The following command will create a system account with a username of ``mediagoblin``. @@ -191,10 +190,10 @@ read the media files that users upload (images, videos, etc.) Many operating systems will automatically create a group ``mediagoblin`` to go with the new user ``mediagoblin``, but just to be sure:: - + sudo groupadd --force mediagoblin sudo usermod --append --groups mediagoblin mediagoblin - + No password will be assigned to this account, and you will not be able to log in as this user. To switch to this account, enter:: @@ -209,7 +208,7 @@ Create a MediaGoblin Directory ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You should create a working directory for MediaGoblin. This document -assumes your local git repository will be located at +assumes your local git repository will be located at ``/srv/mediagoblin.example.org/mediagoblin/``. Substitute your preferred local deployment path as needed. @@ -489,7 +488,7 @@ created:: sudo find /opt/mediagoblin.example.org/mediagoblin/bin -type f -exec chmod 750 {} \; .. note:: - + If you see an Nginx placeholder page, you may need to remove the Nginx default configuration, or explictly set a ``server_name`` directive in the Nginx config. diff --git a/extlib/jquery b/extlib/jquery new file mode 160000 +Subproject 683ceb8ff067ac53a7cb464ba1ec3f88e353e3f diff --git a/extlib/leaflet b/extlib/leaflet new file mode 160000 +Subproject 8a5fdfc6e3db2807b8f0dd617474e4ab2949142 diff --git a/extlib/plyr/blank.webm b/extlib/plyr/blank.webm Binary files differnew file mode 100644 index 00000000..6ec17ef3 --- /dev/null +++ b/extlib/plyr/blank.webm diff --git a/extlib/plyr/build-instructions.md b/extlib/plyr/build-instructions.md new file mode 100644 index 00000000..4323281d --- /dev/null +++ b/extlib/plyr/build-instructions.md @@ -0,0 +1,23 @@ +# Build steps for Plyr (3.6.8) + +Tested on Hyperbola GNU with Linux-libre. + +First install npm (node package manager). + +Clone the repo to a location of your choosing: +``` +git clone https://git.sr.ht/~heckyel/plyr +cd plyr +``` + +Install Plyr's dependencies: +``` +npm install +``` + +Build with npm: +``` +npm run build +``` + +plyr.js and other files will be in the `dist` directory. diff --git a/extlib/plyr/plyr.css b/extlib/plyr/plyr.css new file mode 100644 index 00000000..17dab36f --- /dev/null +++ b/extlib/plyr/plyr.css @@ -0,0 +1 @@ +@charset "UTF-8";@keyframes plyr-progress{to{background-position:25px 0;background-position:var(--plyr-progress-loading-size,25px) 0}}@keyframes plyr-popup{0%{opacity:.5;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes plyr-fade-in{0%{opacity:0}to{opacity:1}}.plyr{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;align-items:center;direction:ltr;display:flex;flex-direction:column;font-family:inherit;font-family:var(--plyr-font-family,inherit);font-variant-numeric:tabular-nums;font-weight:400;font-weight:var(--plyr-font-weight-regular,400);line-height:1.7;line-height:var(--plyr-line-height,1.7);max-width:100%;min-width:200px;position:relative;text-shadow:none;transition:box-shadow .3s ease;z-index:0}.plyr audio,.plyr iframe,.plyr video{display:block;height:100%;width:100%}.plyr button{font:inherit;line-height:inherit;width:auto}.plyr:focus{outline:0}.plyr--full-ui{box-sizing:border-box}.plyr--full-ui *,.plyr--full-ui :after,.plyr--full-ui :before{box-sizing:inherit}.plyr--full-ui a,.plyr--full-ui button,.plyr--full-ui input,.plyr--full-ui label{touch-action:manipulation}.plyr__badge{background:#4a5464;background:var(--plyr-badge-background,#4a5464);border-radius:2px;border-radius:var(--plyr-badge-border-radius,2px);color:#fff;color:var(--plyr-badge-text-color,#fff);font-size:9px;font-size:var(--plyr-font-size-badge,9px);line-height:1;padding:3px 4px}.plyr--full-ui ::-webkit-media-text-track-container{display:none}.plyr__captions{animation:plyr-fade-in .3s ease;bottom:0;display:none;font-size:13px;font-size:var(--plyr-font-size-small,13px);left:0;padding:10px;padding:var(--plyr-control-spacing,10px);position:absolute;text-align:center;transition:transform .4s ease-in-out;width:100%}.plyr__captions span:empty{display:none}@media (min-width:480px){.plyr__captions{font-size:15px;font-size:var(--plyr-font-size-base,15px);padding:20px;padding:calc(var(--plyr-control-spacing, 10px)*2)}}@media (min-width:768px){.plyr__captions{font-size:18px;font-size:var(--plyr-font-size-large,18px)}}.plyr--captions-active .plyr__captions{display:block}.plyr:not(.plyr--hide-controls) .plyr__controls:not(:empty)~.plyr__captions{transform:translateY(-40px);transform:translateY(calc(var(--plyr-control-spacing, 10px)*-4))}.plyr__caption{background:rgba(0,0,0,.8);background:var(--plyr-captions-background,rgba(0,0,0,.8));border-radius:2px;-webkit-box-decoration-break:clone;box-decoration-break:clone;color:#fff;color:var(--plyr-captions-text-color,#fff);line-height:185%;padding:.2em .5em;white-space:pre-wrap}.plyr__caption div{display:inline}.plyr__control{background:transparent;border:0;border-radius:3px;border-radius:var(--plyr-control-radius,3px);color:inherit;cursor:pointer;flex-shrink:0;overflow:visible;padding:7px;padding:calc(var(--plyr-control-spacing, 10px)*.7);position:relative;transition:all .3s ease}.plyr__control svg{fill:currentColor;display:block;height:18px;height:var(--plyr-control-icon-size,18px);pointer-events:none;width:18px;width:var(--plyr-control-icon-size,18px)}.plyr__control:focus{outline:0}.plyr__control.plyr__tab-focus{outline:3px dotted #00b3ff;outline:var(--plyr-tab-focus-color,var(--plyr-color-main,var(--plyr-color-main,#00b3ff))) dotted 3px;outline-offset:2px}a.plyr__control{text-decoration:none}.plyr__control.plyr__control--pressed .icon--not-pressed,.plyr__control.plyr__control--pressed .label--not-pressed,.plyr__control:not(.plyr__control--pressed) .icon--pressed,.plyr__control:not(.plyr__control--pressed) .label--pressed,a.plyr__control:after,a.plyr__control:before{display:none}.plyr--full-ui ::-webkit-media-controls{display:none}.plyr__controls{align-items:center;display:flex;justify-content:flex-end;text-align:center}.plyr__controls .plyr__progress__container{flex:1;min-width:0}.plyr__controls .plyr__controls__item{margin-left:2.5px;margin-left:calc(var(--plyr-control-spacing, 10px)/4)}.plyr__controls .plyr__controls__item:first-child{margin-left:0;margin-right:auto}.plyr__controls .plyr__controls__item.plyr__progress__container{padding-left:2.5px;padding-left:calc(var(--plyr-control-spacing, 10px)/4)}.plyr__controls .plyr__controls__item.plyr__time{padding:0 5px;padding:0 calc(var(--plyr-control-spacing, 10px)/2)}.plyr__controls .plyr__controls__item.plyr__progress__container:first-child,.plyr__controls .plyr__controls__item.plyr__time+.plyr__time,.plyr__controls .plyr__controls__item.plyr__time:first-child{padding-left:0}.plyr [data-plyr=airplay],.plyr [data-plyr=captions],.plyr [data-plyr=fullscreen],.plyr [data-plyr=pip],.plyr__controls:empty{display:none}.plyr--airplay-supported [data-plyr=airplay],.plyr--captions-enabled [data-plyr=captions],.plyr--fullscreen-enabled [data-plyr=fullscreen],.plyr--pip-supported [data-plyr=pip]{display:inline-block}.plyr__menu{display:flex;position:relative}.plyr__menu .plyr__control svg{transition:transform .3s ease}.plyr__menu .plyr__control[aria-expanded=true] svg{transform:rotate(90deg)}.plyr__menu .plyr__control[aria-expanded=true] .plyr__tooltip{display:none}.plyr__menu__container{animation:plyr-popup .2s ease;background:hsla(0,0%,100%,.9);background:var(--plyr-menu-background,hsla(0,0%,100%,.9));border-radius:4px;bottom:100%;box-shadow:0 1px 2px rgba(0,0,0,.15);box-shadow:var(--plyr-menu-shadow,0 1px 2px rgba(0,0,0,.15));color:#4a5464;color:var(--plyr-menu-color,#4a5464);font-size:15px;font-size:var(--plyr-font-size-base,15px);margin-bottom:10px;position:absolute;right:-3px;text-align:left;white-space:nowrap;z-index:3}.plyr__menu__container>div{overflow:hidden;transition:height .35s cubic-bezier(.4,0,.2,1),width .35s cubic-bezier(.4,0,.2,1)}.plyr__menu__container:after{border:4px solid transparent;border-top-color:hsla(0,0%,100%,.9);border:var(--plyr-menu-arrow-size,4px) solid transparent;border-top-color:var(--plyr-menu-background,hsla(0,0%,100%,.9));content:"";height:0;position:absolute;right:14px;right:calc(var(--plyr-control-icon-size, 18px)/2 + var(--plyr-control-spacing, 10px)*.7 - var(--plyr-menu-arrow-size, 4px)/2);top:100%;width:0}.plyr__menu__container [role=menu]{max-height:320px;overflow-y:auto;padding:7px;padding:calc(var(--plyr-control-spacing, 10px)*.7)}.plyr__menu__container [role=menuitem],.plyr__menu__container [role=menuitemradio]{margin-top:2px}.plyr__menu__container [role=menuitem]:first-child,.plyr__menu__container [role=menuitemradio]:first-child{margin-top:0}.plyr__menu__container .plyr__control{align-items:center;color:#4a5464;color:var(--plyr-menu-color,#4a5464);display:flex;font-size:13px;font-size:var(--plyr-font-size-menu,var(--plyr-font-size-small,13px));padding:4.66667px 10.5px;padding:calc(var(--plyr-control-spacing, 10px)*.7/1.5) calc(var(--plyr-control-spacing, 10px)*.7*1.5);-webkit-user-select:none;user-select:none;width:100%}.plyr__menu__container .plyr__control>span{align-items:inherit;display:flex;width:100%}.plyr__menu__container .plyr__control:after{border:4px solid transparent;border:var(--plyr-menu-item-arrow-size,4px) solid transparent;content:"";position:absolute;top:50%;transform:translateY(-50%)}.plyr__menu__container .plyr__control--forward{padding-right:28px;padding-right:calc(var(--plyr-control-spacing, 10px)*.7*4)}.plyr__menu__container .plyr__control--forward:after{border-left-color:#728197;border-left-color:var(--plyr-menu-arrow-color,#728197);right:6.5px;right:calc(var(--plyr-control-spacing, 10px)*.7*1.5 - var(--plyr-menu-item-arrow-size, 4px))}.plyr__menu__container .plyr__control--forward.plyr__tab-focus:after,.plyr__menu__container .plyr__control--forward:hover:after{border-left-color:currentColor}.plyr__menu__container .plyr__control--back{font-weight:400;font-weight:var(--plyr-font-weight-regular,400);margin:7px;margin:calc(var(--plyr-control-spacing, 10px)*.7);margin-bottom:3.5px;margin-bottom:calc(var(--plyr-control-spacing, 10px)*.7/2);padding-left:28px;padding-left:calc(var(--plyr-control-spacing, 10px)*.7*4);position:relative;width:calc(100% - 14px);width:calc(100% - var(--plyr-control-spacing, 10px)*.7*2)}.plyr__menu__container .plyr__control--back:after{border-right-color:#728197;border-right-color:var(--plyr-menu-arrow-color,#728197);left:6.5px;left:calc(var(--plyr-control-spacing, 10px)*.7*1.5 - var(--plyr-menu-item-arrow-size, 4px))}.plyr__menu__container .plyr__control--back:before{background:#dcdfe5;background:var(--plyr-menu-back-border-color,#dcdfe5);box-shadow:0 1px 0 #fff;box-shadow:0 1px 0 var(--plyr-menu-back-border-shadow-color,#fff);content:"";height:1px;left:0;margin-top:3.5px;margin-top:calc(var(--plyr-control-spacing, 10px)*.7/2);overflow:hidden;position:absolute;right:0;top:100%}.plyr__menu__container .plyr__control--back.plyr__tab-focus:after,.plyr__menu__container .plyr__control--back:hover:after{border-right-color:currentColor}.plyr__menu__container .plyr__control[role=menuitemradio]{padding-left:7px;padding-left:calc(var(--plyr-control-spacing, 10px)*.7)}.plyr__menu__container .plyr__control[role=menuitemradio]:after,.plyr__menu__container .plyr__control[role=menuitemradio]:before{border-radius:100%}.plyr__menu__container .plyr__control[role=menuitemradio]:before{background:rgba(0,0,0,.1);content:"";display:block;flex-shrink:0;height:16px;margin-right:10px;margin-right:var(--plyr-control-spacing,10px);transition:all .3s ease;width:16px}.plyr__menu__container .plyr__control[role=menuitemradio]:after{background:#fff;border:0;height:6px;left:12px;opacity:0;top:50%;transform:translateY(-50%) scale(0);transition:transform .3s ease,opacity .3s ease;width:6px}.plyr__menu__container .plyr__control[role=menuitemradio][aria-checked=true]:before{background:#00b3ff;background:var(--plyr-control-toggle-checked-background,var(--plyr-color-main,var(--plyr-color-main,#00b3ff)))}.plyr__menu__container .plyr__control[role=menuitemradio][aria-checked=true]:after{opacity:1;transform:translateY(-50%) scale(1)}.plyr__menu__container .plyr__control[role=menuitemradio].plyr__tab-focus:before,.plyr__menu__container .plyr__control[role=menuitemradio]:hover:before{background:rgba(35,40,47,.1)}.plyr__menu__container .plyr__menu__value{align-items:center;display:flex;margin-left:auto;margin-right:calc(-7px - -2);margin-right:calc(var(--plyr-control-spacing, 10px)*.7*-1 - -2);overflow:hidden;padding-left:24.5px;padding-left:calc(var(--plyr-control-spacing, 10px)*.7*3.5);pointer-events:none}.plyr--full-ui input[type=range]{-webkit-appearance:none;appearance:none;background:transparent;border:0;border-radius:26px;border-radius:calc(var(--plyr-range-thumb-height, 13px)*2);color:#00b3ff;color:var(--plyr-range-fill-background,var(--plyr-color-main,var(--plyr-color-main,#00b3ff)));display:block;height:19px;height:calc(var(--plyr-range-thumb-active-shadow-width, 3px)*2 + var(--plyr-range-thumb-height, 13px));margin:0;min-width:0;padding:0;transition:box-shadow .3s ease;width:100%}.plyr--full-ui input[type=range]::-webkit-slider-runnable-track{background:transparent;background-image:linear-gradient(90deg,currentColor 0,transparent 0);background-image:linear-gradient(to right,currentColor var(--value,0),transparent var(--value,0));border:0;border-radius:2.5px;border-radius:calc(var(--plyr-range-track-height, 5px)/2);height:5px;height:var(--plyr-range-track-height,5px);-webkit-transition:box-shadow .3s ease;transition:box-shadow .3s ease;-webkit-user-select:none;user-select:none}.plyr--full-ui input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;background:#fff;background:var(--plyr-range-thumb-background,#fff);border:0;border-radius:100%;box-shadow:0 1px 1px 0 0 0 1px rgba(35,40,47,.15) rgba(35,40,47,.2);box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px rgba(35,40,47,.15),0 0 0 1px rgba(35,40,47,.2));height:13px;height:var(--plyr-range-thumb-height,13px);margin-top:-4px;margin-top:calc(var(--plyr-range-thumb-height, 13px)/2*-1 - var(--plyr-range-track-height, 5px)/2*-1);position:relative;-webkit-transition:all .2s ease;transition:all .2s ease;width:13px;width:var(--plyr-range-thumb-height,13px)}.plyr--full-ui input[type=range]::-moz-range-track{background:transparent;border:0;border-radius:2.5px;border-radius:calc(var(--plyr-range-track-height, 5px)/2);height:5px;height:var(--plyr-range-track-height,5px);-moz-transition:box-shadow .3s ease;transition:box-shadow .3s ease;user-select:none}.plyr--full-ui input[type=range]::-moz-range-thumb{background:#fff;background:var(--plyr-range-thumb-background,#fff);border:0;border-radius:100%;box-shadow:0 1px 1px 0 0 0 1px rgba(35,40,47,.15) rgba(35,40,47,.2);box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px rgba(35,40,47,.15),0 0 0 1px rgba(35,40,47,.2));height:13px;height:var(--plyr-range-thumb-height,13px);position:relative;-moz-transition:all .2s ease;transition:all .2s ease;width:13px;width:var(--plyr-range-thumb-height,13px)}.plyr--full-ui input[type=range]::-moz-range-progress{background:currentColor;border-radius:2.5px;border-radius:calc(var(--plyr-range-track-height, 5px)/2);height:5px;height:var(--plyr-range-track-height,5px)}.plyr--full-ui input[type=range]::-ms-track{color:transparent}.plyr--full-ui input[type=range]::-ms-fill-upper,.plyr--full-ui input[type=range]::-ms-track{background:transparent;border:0;border-radius:2.5px;border-radius:calc(var(--plyr-range-track-height, 5px)/2);height:5px;height:var(--plyr-range-track-height,5px);-ms-transition:box-shadow .3s ease;transition:box-shadow .3s ease;user-select:none}.plyr--full-ui input[type=range]::-ms-fill-lower{background:transparent;background:currentColor;border:0;border-radius:2.5px;border-radius:calc(var(--plyr-range-track-height, 5px)/2);height:5px;height:var(--plyr-range-track-height,5px);-ms-transition:box-shadow .3s ease;transition:box-shadow .3s ease;user-select:none}.plyr--full-ui input[type=range]::-ms-thumb{background:#fff;background:var(--plyr-range-thumb-background,#fff);border:0;border-radius:100%;box-shadow:0 1px 1px 0 0 0 1px rgba(35,40,47,.15) rgba(35,40,47,.2);box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px rgba(35,40,47,.15),0 0 0 1px rgba(35,40,47,.2));height:13px;height:var(--plyr-range-thumb-height,13px);margin-top:0;position:relative;-ms-transition:all .2s ease;transition:all .2s ease;width:13px;width:var(--plyr-range-thumb-height,13px)}.plyr--full-ui input[type=range]::-ms-tooltip{display:none}.plyr--full-ui input[type=range]::-moz-focus-outer{border:0}.plyr--full-ui input[type=range]:focus{outline:0}.plyr--full-ui input[type=range].plyr__tab-focus::-webkit-slider-runnable-track{outline:3px dotted #00b3ff;outline:var(--plyr-tab-focus-color,var(--plyr-color-main,var(--plyr-color-main,#00b3ff))) dotted 3px;outline-offset:2px}.plyr--full-ui input[type=range].plyr__tab-focus::-moz-range-track{outline:3px dotted #00b3ff;outline:var(--plyr-tab-focus-color,var(--plyr-color-main,var(--plyr-color-main,#00b3ff))) dotted 3px;outline-offset:2px}.plyr--full-ui input[type=range].plyr__tab-focus::-ms-track{outline:3px dotted #00b3ff;outline:var(--plyr-tab-focus-color,var(--plyr-color-main,var(--plyr-color-main,#00b3ff))) dotted 3px;outline-offset:2px}.plyr__poster{background-color:#000;background-color:var(--plyr-video-background,var(--plyr-video-background,#000));background-position:50% 50%;background-repeat:no-repeat;background-size:contain;height:100%;left:0;opacity:0;position:absolute;top:0;transition:opacity .2s ease;width:100%;z-index:1}.plyr--stopped.plyr__poster-enabled .plyr__poster{opacity:1}.plyr--youtube.plyr--paused.plyr__poster-enabled:not(.plyr--stopped) .plyr__poster{display:none}.plyr__time{font-size:13px;font-size:var(--plyr-font-size-time,var(--plyr-font-size-small,13px))}.plyr__time+.plyr__time:before{content:"⁄";margin-right:10px;margin-right:var(--plyr-control-spacing,10px)}@media (max-width:767px){.plyr__time+.plyr__time{display:none}}.plyr__tooltip{background:hsla(0,0%,100%,.9);background:var(--plyr-tooltip-background,hsla(0,0%,100%,.9));border-radius:3px;border-radius:var(--plyr-tooltip-radius,3px);bottom:100%;box-shadow:0 1px 2px rgba(0,0,0,.15);box-shadow:var(--plyr-tooltip-shadow,0 1px 2px rgba(0,0,0,.15));color:#4a5464;color:var(--plyr-tooltip-color,#4a5464);font-size:13px;font-size:var(--plyr-font-size-small,13px);font-weight:400;font-weight:var(--plyr-font-weight-regular,400);left:50%;line-height:1.3;margin-bottom:10px;margin-bottom:calc(var(--plyr-control-spacing, 10px)/2*2);opacity:0;padding:5px 7.5px;padding:calc(var(--plyr-control-spacing, 10px)/2) calc(var(--plyr-control-spacing, 10px)/2*1.5);pointer-events:none;position:absolute;transform:translate(-50%,10px) scale(.8);transform-origin:50% 100%;transition:transform .2s ease .1s,opacity .2s ease .1s;white-space:nowrap;z-index:2}.plyr__tooltip:before{border-left:4px solid transparent;border-left:var(--plyr-tooltip-arrow-size,4px) solid transparent;border-right:4px solid transparent;border-right:var(--plyr-tooltip-arrow-size,4px) solid transparent;border-top:4px solid hsla(0,0%,100%,.9);border-top:var(--plyr-tooltip-arrow-size,4px) solid var(--plyr-tooltip-background,hsla(0,0%,100%,.9));bottom:-4px;bottom:calc(var(--plyr-tooltip-arrow-size, 4px)*-1);content:"";height:0;left:50%;position:absolute;transform:translateX(-50%);width:0;z-index:2}.plyr .plyr__control.plyr__tab-focus .plyr__tooltip,.plyr .plyr__control:hover .plyr__tooltip,.plyr__tooltip--visible{opacity:1;transform:translate(-50%) scale(1)}.plyr .plyr__control:hover .plyr__tooltip{z-index:3}.plyr__controls>.plyr__control:first-child+.plyr__control .plyr__tooltip,.plyr__controls>.plyr__control:first-child .plyr__tooltip{left:0;transform:translateY(10px) scale(.8);transform-origin:0 100%}.plyr__controls>.plyr__control:first-child+.plyr__control .plyr__tooltip:before,.plyr__controls>.plyr__control:first-child .plyr__tooltip:before{left:16px;left:calc(var(--plyr-control-icon-size, 18px)/2 + var(--plyr-control-spacing, 10px)*.7)}.plyr__controls>.plyr__control:last-child .plyr__tooltip{left:auto;right:0;transform:translateY(10px) scale(.8);transform-origin:100% 100%}.plyr__controls>.plyr__control:last-child .plyr__tooltip:before{left:auto;right:16px;right:calc(var(--plyr-control-icon-size, 18px)/2 + var(--plyr-control-spacing, 10px)*.7);transform:translateX(50%)}.plyr__controls>.plyr__control:first-child+.plyr__control.plyr__tab-focus .plyr__tooltip,.plyr__controls>.plyr__control:first-child+.plyr__control .plyr__tooltip--visible,.plyr__controls>.plyr__control:first-child+.plyr__control:hover .plyr__tooltip,.plyr__controls>.plyr__control:first-child.plyr__tab-focus .plyr__tooltip,.plyr__controls>.plyr__control:first-child .plyr__tooltip--visible,.plyr__controls>.plyr__control:first-child:hover .plyr__tooltip,.plyr__controls>.plyr__control:last-child.plyr__tab-focus .plyr__tooltip,.plyr__controls>.plyr__control:last-child .plyr__tooltip--visible,.plyr__controls>.plyr__control:last-child:hover .plyr__tooltip{transform:translate(0) scale(1)}.plyr__progress{left:6.5px;left:calc(var(--plyr-range-thumb-height, 13px)*.5);margin-right:13px;margin-right:var(--plyr-range-thumb-height,13px);position:relative}.plyr__progress__buffer,.plyr__progress input[type=range]{margin-left:-6.5px;margin-left:calc(var(--plyr-range-thumb-height, 13px)*-.5);margin-right:-6.5px;margin-right:calc(var(--plyr-range-thumb-height, 13px)*-.5);width:calc(100% + 13px);width:calc(100% + var(--plyr-range-thumb-height, 13px))}.plyr__progress input[type=range]{position:relative;z-index:2}.plyr__progress .plyr__tooltip{font-size:13px;font-size:var(--plyr-font-size-time,var(--plyr-font-size-small,13px));left:0}.plyr__progress__buffer{-webkit-appearance:none;background:transparent;border:0;border-radius:100px;height:5px;height:var(--plyr-range-track-height,5px);left:0;margin-top:-2.5px;margin-top:calc(var(--plyr-range-track-height, 5px)/2*-1);padding:0;position:absolute;top:50%}.plyr__progress__buffer::-webkit-progress-bar{background:transparent}.plyr__progress__buffer::-webkit-progress-value{background:currentColor;border-radius:100px;min-width:5px;min-width:var(--plyr-range-track-height,5px);-webkit-transition:width .2s ease;transition:width .2s ease}.plyr__progress__buffer::-moz-progress-bar{background:currentColor;border-radius:100px;min-width:5px;min-width:var(--plyr-range-track-height,5px);-moz-transition:width .2s ease;transition:width .2s ease}.plyr__progress__buffer::-ms-fill{border-radius:100px;-ms-transition:width .2s ease;transition:width .2s ease}.plyr--loading .plyr__progress__buffer{animation:plyr-progress 1s linear infinite;background-image:linear-gradient(-45deg,rgba(35,40,47,.6) 25%,transparent 0,transparent 50%,rgba(35,40,47,.6) 0,rgba(35,40,47,.6) 75%,transparent 0,transparent);background-image:linear-gradient(-45deg,var(--plyr-progress-loading-background,rgba(35,40,47,.6)) 25%,transparent 25%,transparent 50%,var(--plyr-progress-loading-background,rgba(35,40,47,.6)) 50%,var(--plyr-progress-loading-background,rgba(35,40,47,.6)) 75%,transparent 75%,transparent);background-repeat:repeat-x;background-size:25px 25px;background-size:var(--plyr-progress-loading-size,25px) var(--plyr-progress-loading-size,25px);color:transparent}.plyr--video.plyr--loading .plyr__progress__buffer{background-color:hsla(0,0%,100%,.25);background-color:var(--plyr-video-progress-buffered-background,hsla(0,0%,100%,.25))}.plyr--audio.plyr--loading .plyr__progress__buffer{background-color:rgba(193,200,209,.6);background-color:var(--plyr-audio-progress-buffered-background,rgba(193,200,209,.6))}.plyr__volume{align-items:center;display:flex;max-width:110px;min-width:80px;position:relative;width:20%}.plyr__volume input[type=range]{margin-left:5px;margin-left:calc(var(--plyr-control-spacing, 10px)/2);margin-right:5px;margin-right:calc(var(--plyr-control-spacing, 10px)/2);position:relative;z-index:2}.plyr--is-ios .plyr__volume{min-width:0;width:auto}.plyr--audio{display:block}.plyr--audio .plyr__controls{background:#fff;background:var(--plyr-audio-controls-background,#fff);border-radius:inherit;color:#4a5464;color:var(--plyr-audio-control-color,#4a5464);padding:10px;padding:var(--plyr-control-spacing,10px)}.plyr--audio .plyr__control.plyr__tab-focus,.plyr--audio .plyr__control:hover,.plyr--audio .plyr__control[aria-expanded=true]{background:#00b3ff;background:var(--plyr-audio-control-background-hover,var(--plyr-color-main,var(--plyr-color-main,#00b3ff)));color:#fff;color:var(--plyr-audio-control-color-hover,#fff)}.plyr--full-ui.plyr--audio input[type=range]::-webkit-slider-runnable-track{background-color:rgba(193,200,209,.6);background-color:var(--plyr-audio-range-track-background,var(--plyr-audio-progress-buffered-background,rgba(193,200,209,.6)))}.plyr--full-ui.plyr--audio input[type=range]::-moz-range-track{background-color:rgba(193,200,209,.6);background-color:var(--plyr-audio-range-track-background,var(--plyr-audio-progress-buffered-background,rgba(193,200,209,.6)))}.plyr--full-ui.plyr--audio input[type=range]::-ms-track{background-color:rgba(193,200,209,.6);background-color:var(--plyr-audio-range-track-background,var(--plyr-audio-progress-buffered-background,rgba(193,200,209,.6)))}.plyr--full-ui.plyr--audio input[type=range]:active::-webkit-slider-thumb{box-shadow:0 1px 1px 0 0 0 1px rgba(35,40,47,.15) rgba(35,40,47,.2),0 0 0 3px rgba(35,40,47,.1);box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px rgba(35,40,47,.15),0 0 0 1px rgba(35,40,47,.2)),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,rgba(35,40,47,.1))}.plyr--full-ui.plyr--audio input[type=range]:active::-moz-range-thumb{box-shadow:0 1px 1px 0 0 0 1px rgba(35,40,47,.15) rgba(35,40,47,.2),0 0 0 3px rgba(35,40,47,.1);box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px rgba(35,40,47,.15),0 0 0 1px rgba(35,40,47,.2)),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,rgba(35,40,47,.1))}.plyr--full-ui.plyr--audio input[type=range]:active::-ms-thumb{box-shadow:0 1px 1px 0 0 0 1px rgba(35,40,47,.15) rgba(35,40,47,.2),0 0 0 3px rgba(35,40,47,.1);box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px rgba(35,40,47,.15),0 0 0 1px rgba(35,40,47,.2)),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,rgba(35,40,47,.1))}.plyr--audio .plyr__progress__buffer{color:rgba(193,200,209,.6);color:var(--plyr-audio-progress-buffered-background,rgba(193,200,209,.6))}.plyr--video{background:#000;background:var(--plyr-video-background,var(--plyr-video-background,#000));overflow:hidden}.plyr--video.plyr--menu-open{overflow:visible}.plyr__video-wrapper{background:#000;background:var(--plyr-video-background,var(--plyr-video-background,#000));height:100%;margin:auto;overflow:hidden;position:relative;width:100%}.plyr__video-embed,.plyr__video-wrapper--fixed-ratio{aspect-ratio:16/9}@supports not (aspect-ratio:16/9){.plyr__video-embed,.plyr__video-wrapper--fixed-ratio{height:0;padding-bottom:56.25%;position:relative}}.plyr__video-embed iframe,.plyr__video-wrapper--fixed-ratio video{border:0;height:100%;left:0;position:absolute;top:0;width:100%}.plyr--full-ui .plyr__video-embed>.plyr__video-embed__container{padding-bottom:240%;position:relative;transform:translateY(-38.28125%)}.plyr--video .plyr__controls{background:linear-gradient(transparent,rgba(0,0,0,.75));background:var(--plyr-video-controls-background,linear-gradient(transparent,rgba(0,0,0,.75)));border-bottom-left-radius:inherit;border-bottom-right-radius:inherit;bottom:0;color:#fff;color:var(--plyr-video-control-color,#fff);left:0;padding:5px;padding:calc(var(--plyr-control-spacing, 10px)/2);padding-top:20px;padding-top:calc(var(--plyr-control-spacing, 10px)*2);position:absolute;right:0;transition:opacity .4s ease-in-out,transform .4s ease-in-out;z-index:3}@media (min-width:480px){.plyr--video .plyr__controls{padding:10px;padding:var(--plyr-control-spacing,10px);padding-top:35px;padding-top:calc(var(--plyr-control-spacing, 10px)*3.5)}}.plyr--video.plyr--hide-controls .plyr__controls{opacity:0;pointer-events:none;transform:translateY(100%)}.plyr--video .plyr__control.plyr__tab-focus,.plyr--video .plyr__control:hover,.plyr--video .plyr__control[aria-expanded=true]{background:#00b3ff;background:var(--plyr-video-control-background-hover,var(--plyr-color-main,var(--plyr-color-main,#00b3ff)));color:#fff;color:var(--plyr-video-control-color-hover,#fff)}.plyr__control--overlaid{background:#00b3ff;background:var(--plyr-video-control-background-hover,var(--plyr-color-main,var(--plyr-color-main,#00b3ff)));border:0;border-radius:100%;color:#fff;color:var(--plyr-video-control-color,#fff);display:none;left:50%;opacity:.9;padding:15px;padding:calc(var(--plyr-control-spacing, 10px)*1.5);position:absolute;top:50%;transform:translate(-50%,-50%);transition:.3s;z-index:2}.plyr__control--overlaid svg{left:2px;position:relative}.plyr__control--overlaid:focus,.plyr__control--overlaid:hover{opacity:1}.plyr--playing .plyr__control--overlaid{opacity:0;visibility:hidden}.plyr--full-ui.plyr--video .plyr__control--overlaid{display:block}.plyr--full-ui.plyr--video input[type=range]::-webkit-slider-runnable-track{background-color:hsla(0,0%,100%,.25);background-color:var(--plyr-video-range-track-background,var(--plyr-video-progress-buffered-background,hsla(0,0%,100%,.25)))}.plyr--full-ui.plyr--video input[type=range]::-moz-range-track{background-color:hsla(0,0%,100%,.25);background-color:var(--plyr-video-range-track-background,var(--plyr-video-progress-buffered-background,hsla(0,0%,100%,.25)))}.plyr--full-ui.plyr--video input[type=range]::-ms-track{background-color:hsla(0,0%,100%,.25);background-color:var(--plyr-video-range-track-background,var(--plyr-video-progress-buffered-background,hsla(0,0%,100%,.25)))}.plyr--full-ui.plyr--video input[type=range]:active::-webkit-slider-thumb{box-shadow:0 1px 1px 0 0 0 1px rgba(35,40,47,.15) rgba(35,40,47,.2),0 0 0 3px rgba(255,255,255,.5);box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px rgba(35,40,47,.15),0 0 0 1px rgba(35,40,47,.2)),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,hsla(0,0%,100%,.5))}.plyr--full-ui.plyr--video input[type=range]:active::-moz-range-thumb{box-shadow:0 1px 1px 0 0 0 1px rgba(35,40,47,.15) rgba(35,40,47,.2),0 0 0 3px rgba(255,255,255,.5);box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px rgba(35,40,47,.15),0 0 0 1px rgba(35,40,47,.2)),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,hsla(0,0%,100%,.5))}.plyr--full-ui.plyr--video input[type=range]:active::-ms-thumb{box-shadow:0 1px 1px 0 0 0 1px rgba(35,40,47,.15) rgba(35,40,47,.2),0 0 0 3px rgba(255,255,255,.5);box-shadow:var(--plyr-range-thumb-shadow,0 1px 1px rgba(35,40,47,.15),0 0 0 1px rgba(35,40,47,.2)),0 0 0 var(--plyr-range-thumb-active-shadow-width,3px) var(--plyr-audio-range-thumb-active-shadow-color,hsla(0,0%,100%,.5))}.plyr--video .plyr__progress__buffer{color:hsla(0,0%,100%,.25);color:var(--plyr-video-progress-buffered-background,hsla(0,0%,100%,.25))}.plyr:-webkit-full-screen{background:#000;border-radius:0!important;height:100%;margin:0;width:100%}.plyr:fullscreen{background:#000;border-radius:0!important;height:100%;margin:0;width:100%}.plyr:-webkit-full-screen video{height:100%}.plyr:fullscreen video{height:100%}.plyr:-webkit-full-screen .plyr__control .icon--exit-fullscreen{display:block}.plyr:fullscreen .plyr__control .icon--exit-fullscreen{display:block}.plyr:-webkit-full-screen .plyr__control .icon--exit-fullscreen+svg{display:none}.plyr:fullscreen .plyr__control .icon--exit-fullscreen+svg{display:none}.plyr:-webkit-full-screen.plyr--hide-controls{cursor:none}.plyr:fullscreen.plyr--hide-controls{cursor:none}@media (min-width:1024px){.plyr:-webkit-full-screen .plyr__captions{font-size:21px;font-size:var(--plyr-font-size-xlarge,21px)}.plyr:fullscreen .plyr__captions{font-size:21px;font-size:var(--plyr-font-size-xlarge,21px)}}.plyr--fullscreen-fallback{background:#000;border-radius:0!important;bottom:0;display:block;height:100%;left:0;margin:0;position:fixed;right:0;top:0;width:100%;z-index:10000000}.plyr--fullscreen-fallback video{height:100%}.plyr--fullscreen-fallback .plyr__control .icon--exit-fullscreen{display:block}.plyr--fullscreen-fallback .plyr__control .icon--exit-fullscreen+svg{display:none}.plyr--fullscreen-fallback.plyr--hide-controls{cursor:none}@media (min-width:1024px){.plyr--fullscreen-fallback .plyr__captions{font-size:21px;font-size:var(--plyr-font-size-xlarge,21px)}}.plyr__ads{border-radius:inherit;bottom:0;cursor:pointer;left:0;overflow:hidden;position:absolute;right:0;top:0;z-index:-1}.plyr__ads>div,.plyr__ads>div iframe{height:100%;position:absolute;width:100%}.plyr__ads:after{background:#23282f;border-radius:2px;bottom:10px;bottom:var(--plyr-control-spacing,10px);color:#fff;content:attr(data-badge-text);font-size:11px;padding:2px 6px;pointer-events:none;position:absolute;right:10px;right:var(--plyr-control-spacing,10px);z-index:3}.plyr__ads:empty:after{display:none}.plyr__cues{background:currentColor;display:block;height:5px;height:var(--plyr-range-track-height,5px);left:0;opacity:.8;position:absolute;top:50%;transform:translateY(-50%);width:3px;z-index:3}.plyr__preview-thumb{background-color:hsla(0,0%,100%,.9);background-color:var(--plyr-tooltip-background,hsla(0,0%,100%,.9));border-radius:3px;bottom:100%;box-shadow:0 1px 2px rgba(0,0,0,.15);box-shadow:var(--plyr-tooltip-shadow,0 1px 2px rgba(0,0,0,.15));margin-bottom:10px;margin-bottom:calc(var(--plyr-control-spacing, 10px)/2*2);opacity:0;padding:3px;padding:var(--plyr-tooltip-radius,3px);pointer-events:none;position:absolute;transform:translateY(10px) scale(.8);transform-origin:50% 100%;transition:transform .2s ease .1s,opacity .2s ease .1s;z-index:2}.plyr__preview-thumb--is-shown{opacity:1;transform:translate(0) scale(1)}.plyr__preview-thumb:before{border-left:4px solid transparent;border-left:var(--plyr-tooltip-arrow-size,4px) solid transparent;border-right:4px solid transparent;border-right:var(--plyr-tooltip-arrow-size,4px) solid transparent;border-top:4px solid hsla(0,0%,100%,.9);border-top:var(--plyr-tooltip-arrow-size,4px) solid var(--plyr-tooltip-background,hsla(0,0%,100%,.9));bottom:-4px;bottom:calc(var(--plyr-tooltip-arrow-size, 4px)*-1);content:"";height:0;left:50%;position:absolute;transform:translateX(-50%);width:0;z-index:2}.plyr__preview-thumb__image-container{background:#c1c8d1;border-radius:2px;border-radius:calc(var(--plyr-tooltip-radius, 3px) - 1px);overflow:hidden;position:relative;z-index:0}.plyr__preview-thumb__image-container img{height:100%;left:0;max-height:none;max-width:none;position:absolute;top:0;width:100%}.plyr__preview-thumb__time-container{bottom:6px;left:0;position:absolute;right:0;white-space:nowrap;z-index:3}.plyr__preview-thumb__time-container span{background-color:rgba(0,0,0,.55);border-radius:2px;border-radius:calc(var(--plyr-tooltip-radius, 3px) - 1px);color:#fff;font-size:13px;font-size:var(--plyr-font-size-time,var(--plyr-font-size-small,13px));padding:3px 6px}.plyr__preview-scrubbing{bottom:0;filter:blur(1px);height:100%;left:0;margin:auto;opacity:0;overflow:hidden;pointer-events:none;position:absolute;right:0;top:0;transition:opacity .3s ease;width:100%;z-index:1}.plyr__preview-scrubbing--is-shown{opacity:1}.plyr__preview-scrubbing img{height:100%;left:0;max-height:none;max-width:none;-o-object-fit:contain;object-fit:contain;position:absolute;top:0;width:100%}.plyr--no-transition{transition:none!important}.plyr__sr-only{clip:rect(1px,1px,1px,1px);border:0!important;height:1px!important;overflow:hidden;padding:0!important;position:absolute!important;width:1px!important}.plyr [hidden]{display:none!important}
\ No newline at end of file diff --git a/extlib/plyr/plyr.js b/extlib/plyr/plyr.js new file mode 100644 index 00000000..fe1b6ae9 --- /dev/null +++ b/extlib/plyr/plyr.js @@ -0,0 +1,8678 @@ +typeof navigator === "object" && (function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define('Plyr', factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Plyr = factory()); +})(this, (function () { 'use strict'; + + function _defineProperty$1(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; + } + + function _classCallCheck(e, t) { + if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function"); + } + + function _defineProperties(e, t) { + for (var n = 0; n < t.length; n++) { + var r = t[n]; + r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r); + } + } + + function _createClass(e, t, n) { + return t && _defineProperties(e.prototype, t), n && _defineProperties(e, n), e; + } + + function _defineProperty(e, t, n) { + return t in e ? Object.defineProperty(e, t, { + value: n, + enumerable: !0, + configurable: !0, + writable: !0 + }) : e[t] = n, e; + } + + function ownKeys(e, t) { + var n = Object.keys(e); + + if (Object.getOwnPropertySymbols) { + var r = Object.getOwnPropertySymbols(e); + t && (r = r.filter(function (t) { + return Object.getOwnPropertyDescriptor(e, t).enumerable; + })), n.push.apply(n, r); + } + + return n; + } + + function _objectSpread2(e) { + for (var t = 1; t < arguments.length; t++) { + var n = null != arguments[t] ? arguments[t] : {}; + t % 2 ? ownKeys(Object(n), !0).forEach(function (t) { + _defineProperty(e, t, n[t]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : ownKeys(Object(n)).forEach(function (t) { + Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)); + }); + } + + return e; + } + + var defaults$1 = { + addCSS: !0, + thumbWidth: 15, + watch: !0 + }; + + function matches$1(e, t) { + return function () { + return Array.from(document.querySelectorAll(t)).includes(this); + }.call(e, t); + } + + function trigger(e, t) { + if (e && t) { + var n = new Event(t, { + bubbles: !0 + }); + e.dispatchEvent(n); + } + } + + var getConstructor$1 = function (e) { + return null != e ? e.constructor : null; + }, + instanceOf$1 = function (e, t) { + return !!(e && t && e instanceof t); + }, + isNullOrUndefined$1 = function (e) { + return null == e; + }, + isObject$1 = function (e) { + return getConstructor$1(e) === Object; + }, + isNumber$1 = function (e) { + return getConstructor$1(e) === Number && !Number.isNaN(e); + }, + isString$1 = function (e) { + return getConstructor$1(e) === String; + }, + isBoolean$1 = function (e) { + return getConstructor$1(e) === Boolean; + }, + isFunction$1 = function (e) { + return getConstructor$1(e) === Function; + }, + isArray$1 = function (e) { + return Array.isArray(e); + }, + isNodeList$1 = function (e) { + return instanceOf$1(e, NodeList); + }, + isElement$1 = function (e) { + return instanceOf$1(e, Element); + }, + isEvent$1 = function (e) { + return instanceOf$1(e, Event); + }, + isEmpty$1 = function (e) { + return isNullOrUndefined$1(e) || (isString$1(e) || isArray$1(e) || isNodeList$1(e)) && !e.length || isObject$1(e) && !Object.keys(e).length; + }, + is$1 = { + nullOrUndefined: isNullOrUndefined$1, + object: isObject$1, + number: isNumber$1, + string: isString$1, + boolean: isBoolean$1, + function: isFunction$1, + array: isArray$1, + nodeList: isNodeList$1, + element: isElement$1, + event: isEvent$1, + empty: isEmpty$1 + }; + + function getDecimalPlaces(e) { + var t = "".concat(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); + return t ? Math.max(0, (t[1] ? t[1].length : 0) - (t[2] ? +t[2] : 0)) : 0; + } + + function round(e, t) { + if (1 > t) { + var n = getDecimalPlaces(t); + return parseFloat(e.toFixed(n)); + } + + return Math.round(e / t) * t; + } + + var RangeTouch = function () { + function e(t, n) { + _classCallCheck(this, e), is$1.element(t) ? this.element = t : is$1.string(t) && (this.element = document.querySelector(t)), is$1.element(this.element) && is$1.empty(this.element.rangeTouch) && (this.config = _objectSpread2({}, defaults$1, {}, n), this.init()); + } + + return _createClass(e, [{ + key: "init", + value: function () { + e.enabled && (this.config.addCSS && (this.element.style.userSelect = "none", this.element.style.webKitUserSelect = "none", this.element.style.touchAction = "manipulation"), this.listeners(!0), this.element.rangeTouch = this); + } + }, { + key: "destroy", + value: function () { + e.enabled && (this.config.addCSS && (this.element.style.userSelect = "", this.element.style.webKitUserSelect = "", this.element.style.touchAction = ""), this.listeners(!1), this.element.rangeTouch = null); + } + }, { + key: "listeners", + value: function (e) { + var t = this, + n = e ? "addEventListener" : "removeEventListener"; + ["touchstart", "touchmove", "touchend"].forEach(function (e) { + t.element[n](e, function (e) { + return t.set(e); + }, !1); + }); + } + }, { + key: "get", + value: function (t) { + if (!e.enabled || !is$1.event(t)) return null; + var n, + r = t.target, + i = t.changedTouches[0], + o = parseFloat(r.getAttribute("min")) || 0, + s = parseFloat(r.getAttribute("max")) || 100, + u = parseFloat(r.getAttribute("step")) || 1, + c = r.getBoundingClientRect(), + a = 100 / c.width * (this.config.thumbWidth / 2) / 100; + return 0 > (n = 100 / c.width * (i.clientX - c.left)) ? n = 0 : 100 < n && (n = 100), 50 > n ? n -= (100 - 2 * n) * a : 50 < n && (n += 2 * (n - 50) * a), o + round(n / 100 * (s - o), u); + } + }, { + key: "set", + value: function (t) { + e.enabled && is$1.event(t) && !t.target.disabled && (t.preventDefault(), t.target.value = this.get(t), trigger(t.target, "touchend" === t.type ? "change" : "input")); + } + }], [{ + key: "setup", + value: function (t) { + var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}, + r = null; + if (is$1.empty(t) || is$1.string(t) ? r = Array.from(document.querySelectorAll(is$1.string(t) ? t : 'input[type="range"]')) : is$1.element(t) ? r = [t] : is$1.nodeList(t) ? r = Array.from(t) : is$1.array(t) && (r = t.filter(is$1.element)), is$1.empty(r)) return null; + + var i = _objectSpread2({}, defaults$1, {}, n); + + if (is$1.string(t) && i.watch) { + var o = new MutationObserver(function (n) { + Array.from(n).forEach(function (n) { + Array.from(n.addedNodes).forEach(function (n) { + is$1.element(n) && matches$1(n, t) && new e(n, i); + }); + }); + }); + o.observe(document.body, { + childList: !0, + subtree: !0 + }); + } + + return r.map(function (t) { + return new e(t, n); + }); + } + }, { + key: "enabled", + get: function () { + return "ontouchstart" in document.documentElement; + } + }]), e; + }(); + + // ========================================================================== + // Type checking utils + // ========================================================================== + const getConstructor = input => input !== null && typeof input !== 'undefined' ? input.constructor : null; + + const instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor); + + const isNullOrUndefined = input => input === null || typeof input === 'undefined'; + + const isObject = input => getConstructor(input) === Object; + + const isNumber = input => getConstructor(input) === Number && !Number.isNaN(input); + + const isString = input => getConstructor(input) === String; + + const isBoolean = input => getConstructor(input) === Boolean; + + const isFunction = input => getConstructor(input) === Function; + + const isArray = input => Array.isArray(input); + + const isWeakMap = input => instanceOf(input, WeakMap); + + const isNodeList = input => instanceOf(input, NodeList); + + const isTextNode = input => getConstructor(input) === Text; + + 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) && isFunction(input.then); + + const isElement = input => input !== null && typeof input === 'object' && input.nodeType === 1 && typeof input.style === 'object' && typeof input.ownerDocument === 'object'; + + const isEmpty = input => isNullOrUndefined(input) || (isString(input) || isArray(input) || isNodeList(input)) && !input.length || isObject(input) && !Object.keys(input).length; + + const isUrl = input => { + // Accept a URL object + if (instanceOf(input, window.URL)) { + return true; + } // Must be string from here + + + if (!isString(input)) { + return false; + } // Add the protocol if required + + + let string = input; + + if (!input.startsWith('http://') || !input.startsWith('https://')) { + string = `http://${input}`; + } + + try { + return !isEmpty(new URL(string).hostname); + } catch (_) { + return false; + } + }; + + var is = { + nullOrUndefined: isNullOrUndefined, + object: isObject, + number: isNumber, + string: isString, + boolean: isBoolean, + function: isFunction, + array: isArray, + weakMap: isWeakMap, + nodeList: isNodeList, + element: isElement, + textNode: isTextNode, + event: isEvent, + keyboardEvent: isKeyboardEvent, + cue: isCue, + track: isTrack, + promise: isPromise, + url: isUrl, + empty: isEmpty + }; + + // ========================================================================== + const transitionEndEvent = (() => { + const element = document.createElement('span'); + const events = { + WebkitTransition: 'webkitTransitionEnd', + MozTransition: 'transitionend', + OTransition: 'oTransitionEnd otransitionend', + transition: 'transitionend' + }; + const type = Object.keys(events).find(event => element.style[event] !== undefined); + return is.string(type) ? events[type] : false; + })(); // Force repaint of element + + function repaint(element, delay) { + setTimeout(() => { + try { + // eslint-disable-next-line no-param-reassign + element.hidden = true; // eslint-disable-next-line no-unused-expressions + + element.offsetHeight; // eslint-disable-next-line no-param-reassign + + element.hidden = false; + } catch (_) {// Do nothing + } + }, delay); + } + + // ========================================================================== + // Browser sniffing + // Unfortunately, due to mixed support, UA sniffing is required + // ========================================================================== + const browser = { + isIE: Boolean(window.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: navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 || /(iPad|iPhone|iPod)/gi.test(navigator.platform) + }; + + // ========================================================================== + + function cloneDeep(object) { + return JSON.parse(JSON.stringify(object)); + } // Get a nested value in an object + + function getDeep(object, path) { + return path.split('.').reduce((obj, key) => obj && obj[key], object); + } // Deep extend destination object with N more objects + + function extend(target = {}, ...sources) { + if (!sources.length) { + return target; + } + + const source = sources.shift(); + + if (!is.object(source)) { + return target; + } + + Object.keys(source).forEach(key => { + if (is.object(source[key])) { + if (!Object.keys(target).includes(key)) { + Object.assign(target, { + [key]: {} + }); + } + + extend(target[key], source[key]); + } else { + Object.assign(target, { + [key]: source[key] + }); + } + }); + return extend(target, ...sources); + } + + // ========================================================================== + + function wrap(elements, wrapper) { + // Convert `elements` to an array, if necessary. + const targets = elements.length ? elements : [elements]; // Loops backwards to prevent having to clone the wrapper on the + // first element (see `child` below). + + Array.from(targets).reverse().forEach((element, index) => { + const child = index > 0 ? wrapper.cloneNode(true) : wrapper; // Cache the current parent and sibling. + + const parent = element.parentNode; + const sibling = element.nextSibling; // Wrap the element (is automatically removed from its current + // parent). + + child.appendChild(element); // If the element had a sibling, insert the wrapper before + // the sibling to maintain the HTML structure; otherwise, just + // append it to the parent. + + if (sibling) { + parent.insertBefore(child, sibling); + } else { + parent.appendChild(child); + } + }); + } // Set attributes + + function setAttributes(element, attributes) { + if (!is.element(element) || is.empty(attributes)) { + return; + } // Assume null and undefined attributes should be left out, + // Setting them would otherwise convert them to "null" and "undefined" + + + Object.entries(attributes).filter(([, value]) => !is.nullOrUndefined(value)).forEach(([key, value]) => element.setAttribute(key, value)); + } // Create a DocumentFragment + + function createElement(type, attributes, text) { + // Create a new <element> + const element = document.createElement(type); // Set all passed attributes + + if (is.object(attributes)) { + setAttributes(element, attributes); + } // Add text node + + + if (is.string(text)) { + element.innerText = text; + } // Return built element + + + return element; + } // Inaert an element after another + + function insertAfter(element, target) { + if (!is.element(element) || !is.element(target)) { + return; + } + + target.parentNode.insertBefore(element, target.nextSibling); + } // Insert a DocumentFragment + + function insertElement(type, parent, attributes, text) { + if (!is.element(parent)) { + return; + } + + parent.appendChild(createElement(type, attributes, text)); + } // Remove element(s) + + function removeElement(element) { + if (is.nodeList(element) || is.array(element)) { + Array.from(element).forEach(removeElement); + return; + } + + if (!is.element(element) || !is.element(element.parentNode)) { + return; + } + + element.parentNode.removeChild(element); + } // Remove all child elements + + function emptyElement(element) { + if (!is.element(element)) { + return; + } + + let { + length + } = element.childNodes; + + while (length > 0) { + element.removeChild(element.lastChild); + length -= 1; + } + } // Replace element + + function replaceElement(newChild, oldChild) { + if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) { + return null; + } + + oldChild.parentNode.replaceChild(newChild, oldChild); + return newChild; + } // Get an attribute object from a string selector + + function getAttributesFromSelector(sel, existingAttributes) { + // For example: + // '.test' to { class: 'test' } + // '#test' to { id: 'test' } + // '[data-test="test"]' to { 'data-test': 'test' } + if (!is.string(sel) || is.empty(sel)) { + return {}; + } + + const attributes = {}; + const existing = extend({}, existingAttributes); + sel.split(',').forEach(s => { + // Remove whitespace + const selector = s.trim(); + const className = selector.replace('.', ''); + const stripped = selector.replace(/[[\]]/g, ''); // Get the parts and value + + const parts = stripped.split('='); + const [key] = parts; + const value = parts.length > 1 ? parts[1].replace(/["']/g, '') : ''; // Get the first character + + const start = selector.charAt(0); + + switch (start) { + case '.': + // Add to existing classname + if (is.string(existing.class)) { + attributes.class = `${existing.class} ${className}`; + } else { + attributes.class = className; + } + + break; + + case '#': + // ID selector + attributes.id = selector.replace('#', ''); + break; + + case '[': + // Attribute selector + attributes[key] = value; + break; + } + }); + return extend(existing, attributes); + } // Toggle hidden + + function toggleHidden(element, hidden) { + if (!is.element(element)) { + return; + } + + let hide = hidden; + + if (!is.boolean(hide)) { + hide = !element.hidden; + } // eslint-disable-next-line no-param-reassign + + + element.hidden = hide; + } // Mirror Element.classList.toggle, with IE compatibility for "force" argument + + function toggleClass(element, className, force) { + if (is.nodeList(element)) { + return Array.from(element).map(e => toggleClass(e, className, force)); + } + + if (is.element(element)) { + let method = 'toggle'; + + if (typeof force !== 'undefined') { + method = force ? 'add' : 'remove'; + } + + element.classList[method](className); + return element.classList.contains(className); + } + + return false; + } // Has class name + + function hasClass(element, className) { + return is.element(element) && element.classList.contains(className); + } // Element matches selector + + function matches(element, selector) { + const { + prototype + } = Element; + + function match() { + return Array.from(document.querySelectorAll(selector)).includes(this); + } + + const method = prototype.matches || prototype.webkitMatchesSelector || prototype.mozMatchesSelector || prototype.msMatchesSelector || match; + return method.call(element, selector); + } // Closest ancestor element matching selector (also tests element itself) + + function closest$1(element, selector) { + const { + prototype + } = Element; // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill + + function closestElement() { + let el = this; + + do { + if (matches.matches(el, selector)) return el; + el = el.parentElement || el.parentNode; + } while (el !== null && el.nodeType === 1); + + return null; + } + + const method = prototype.closest || closestElement; + return method.call(element, selector); + } // Find all elements + + function getElements(selector) { + return this.elements.container.querySelectorAll(selector); + } // Find a single element + + function getElement(selector) { + return this.elements.container.querySelector(selector); + } // Set focus and tab focus class + + function setFocus(element = null, tabFocus = false) { + if (!is.element(element)) { + return; + } // Set regular focus + + + element.focus({ + preventScroll: true + }); // If we want to mimic keyboard focus via tab + + if (tabFocus) { + toggleClass(element, this.config.classNames.tabFocus); + } + } + + // ========================================================================== + + const defaultCodecs = { + 'audio/ogg': 'vorbis', + 'audio/wav': '1', + 'video/webm': 'vp8, vorbis', + 'video/mp4': 'avc1.42E01E, mp4a.40.2', + 'video/ogg': 'theora' + }; // Check for feature support + + const support = { + // Basic support + audio: 'canPlayType' in document.createElement('audio'), + video: 'canPlayType' in document.createElement('video'), + + // Check for support + // Basic functionality vs full UI + check(type, provider, playsinline) { + const canPlayInline = browser.isIPhone && playsinline && support.playsinline; + const api = support[type] || provider !== 'html5'; + const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline); + return { + api, + ui + }; + }, + + // Picture-in-picture support + // Safari & Chrome only currently + pip: (() => { + if (browser.isIPhone) { + return false; + } // Safari + // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls + + + if (is.function(createElement('video').webkitSetPresentationMode)) { + return true; + } // Chrome + // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture + + + if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) { + return true; + } + + return false; + })(), + // Airplay support + // Safari only currently + airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent), + // Inline playback support + // https://webkit.org/blog/6784/new-video-policies-for-ios/ + playsinline: 'playsInline' in document.createElement('video'), + + // Check for mime type support against a player instance + // Credits: http://diveintohtml5.info/everything.html + // Related: http://www.leanbackplayer.com/test/h5mt.html + 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) { + return false; + } // Add codec if required + + + if (Object.keys(defaultCodecs).includes(type)) { + type += `; codecs="${defaultCodecs[input]}"`; + } + + try { + return Boolean(type && this.media.canPlayType(type).replace(/no/, '')); + } catch (_) { + return false; + } + }, + + // Check for textTracks support + textTracks: 'textTracks' in document.createElement('video'), + // <input type="range"> Sliders + rangeInput: (() => { + const range = document.createElement('input'); + range.type = 'range'; + return range.type === 'range'; + })(), + // Touch + // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event + touch: 'ontouchstart' in document.documentElement, + // Detect transitions support + transitions: transitionEndEvent !== false, + // Reduced motion iOS & MacOS setting + // https://webkit.org/blog/7551/responsive-design-for-motion/ + reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches + }; + + // ========================================================================== + // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md + // https://www.youtube.com/watch?v=NPM6172J22g + + const supportsPassiveListeners = (() => { + // Test via a getter in the options object to see if the passive property is accessed + let supported = false; + + try { + const options = Object.defineProperty({}, 'passive', { + get() { + supported = true; + return null; + } + + }); + window.addEventListener('test', null, options); + window.removeEventListener('test', null, options); + } catch (_) {// Do nothing + } + + return supported; + })(); // Toggle event listener + + + function toggleListener(element, event, callback, toggle = false, passive = true, capture = false) { + // Bail if no element, event, or callback + if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) { + return; + } // Allow multiple events + + + const events = event.split(' '); // Build options + // Default to just the capture boolean for browsers with no passive listener support + + let options = capture; // If passive events listeners are supported + + if (supportsPassiveListeners) { + options = { + // Whether the listener can be passive (i.e. default never prevented) + passive, + // Whether the listener is a capturing listener or not + capture + }; + } // If a single node is passed, bind the event listener + + + events.forEach(type => { + if (this && this.eventListeners && toggle) { + // Cache event listener + this.eventListeners.push({ + element, + type, + callback, + options + }); + } + + element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options); + }); + } // Bind event handler + + function on(element, events = '', callback, passive = true, capture = false) { + toggleListener.call(this, element, events, callback, true, passive, capture); + } // Unbind event handler + + function off(element, events = '', callback, passive = true, capture = false) { + toggleListener.call(this, element, events, callback, false, passive, capture); + } // Bind once-only event handler + + function once(element, events = '', callback, passive = true, capture = false) { + const onceCallback = (...args) => { + off(element, events, onceCallback, passive, capture); + callback.apply(this, args); + }; + + toggleListener.call(this, element, events, onceCallback, true, passive, capture); + } // Trigger event + + function triggerEvent(element, type = '', bubbles = false, detail = {}) { + // Bail if no element + if (!is.element(element) || is.empty(type)) { + return; + } // Create and dispatch the event + + + const event = new CustomEvent(type, { + bubbles, + detail: { ...detail, + plyr: this + } + }); // Dispatch the event + + element.dispatchEvent(event); + } // Unbind all cached event listeners + + function unbindListeners() { + if (this && this.eventListeners) { + this.eventListeners.forEach(item => { + const { + element, + type, + callback, + options + } = item; + element.removeEventListener(type, callback, options); + }); + this.eventListeners = []; + } + } // Run method when / if player is ready + + function ready() { + return new Promise(resolve => this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve)).then(() => {}); + } + + /** + * Silence a Promise-like object. + * This is useful for avoiding non-harmful, but potentially confusing "uncaught + * play promise" rejection error messages. + * @param {Object} value An object that may or may not be `Promise`-like. + */ + + function silencePromise(value) { + if (is.promise(value)) { + value.then(null, () => {}); + } + } + + // ========================================================================== + + function dedupe(array) { + if (!is.array(array)) { + return array; + } + + return array.filter((item, index) => array.indexOf(item) === index); + } // Get the closest value in an array + + function closest(array, value) { + if (!is.array(array) || !array.length) { + return null; + } + + return array.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev); + } + + // ========================================================================== + + function supportsCSS(declaration) { + if (!window || !window.CSS) { + return false; + } + + return window.CSS.supports(declaration); + } // Standard/common aspect ratios + + const standardRatios = [[1, 1], [4, 3], [3, 4], [5, 4], [4, 5], [3, 2], [2, 3], [16, 10], [10, 16], [16, 9], [9, 16], [21, 9], [9, 21], [32, 9], [9, 32]].reduce((out, [x, y]) => ({ ...out, + [x / y]: [x, y] + }), {}); // Validate an aspect ratio + + function validateAspectRatio(input) { + if (!is.array(input) && (!is.string(input) || !input.includes(':'))) { + return false; + } + + const ratio = is.array(input) ? input : input.split(':'); + return ratio.map(Number).every(is.number); + } // Reduce an aspect ratio to it's lowest form + + function reduceAspectRatio(ratio) { + if (!is.array(ratio) || !ratio.every(is.number)) { + return null; + } + + const [width, height] = ratio; + + const getDivider = (w, h) => h === 0 ? w : getDivider(h, w % h); + + const divider = getDivider(width, height); + return [width / divider, height / divider]; + } // Calculate an aspect ratio + + function getAspectRatio(input) { + const parse = ratio => validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null; // Try provided ratio + + + let ratio = parse(input); // Get from config + + if (ratio === null) { + ratio = parse(this.config.ratio); + } // Get from embed + + + if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) { + ({ + ratio + } = this.embed); + } // Get from HTML5 video + + + if (ratio === null && this.isHTML5) { + const { + videoWidth, + videoHeight + } = this.media; + ratio = [videoWidth, videoHeight]; + } + + return reduceAspectRatio(ratio); + } // Set aspect ratio for responsive container + + function setAspectRatio(input) { + if (!this.isVideo) { + return {}; + } + + const { + wrapper + } = this.elements; + const ratio = getAspectRatio.call(this, input); + + if (!is.array(ratio)) { + return {}; + } + + const [x, y] = reduceAspectRatio(ratio); + const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`); + const padding = 100 / x * y; + + if (useNative) { + wrapper.style.aspectRatio = `${x}/${y}`; + } else { + wrapper.style.paddingBottom = `${padding}%`; + } // For Vimeo we have an extra <div> to hide the standard controls and UI + + + if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) { + const height = 100 / this.media.offsetWidth * parseInt(window.getComputedStyle(this.media).paddingBottom, 10); + const offset = (height - padding) / (height / 50); + + if (this.fullscreen.active) { + wrapper.style.paddingBottom = null; + } else { + this.media.style.transform = `translateY(-${offset}%)`; + } + } else if (this.isHTML5) { + wrapper.classList.add(this.config.classNames.videoFixedRatio); + } + + return { + padding, + ratio + }; + } // Round an aspect ratio to closest standard ratio + + function roundAspectRatio(x, y, tolerance = 0.05) { + const ratio = x / y; + const closestRatio = closest(Object.keys(standardRatios), ratio); // Check match is within tolerance + + if (Math.abs(closestRatio - ratio) <= tolerance) { + return standardRatios[closestRatio]; + } // No match + + + return [x, y]; + } // Get the size of the viewport + // https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions + + function getViewportSize() { + const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0); + const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0); + return [width, height]; + } + + // ========================================================================== + const html5 = { + getSources() { + if (!this.isHTML5) { + return []; + } + + const sources = Array.from(this.media.querySelectorAll('source')); // 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 + getQualityOptions() { + // Whether we're forcing all options (e.g. for streaming) + if (this.config.quality.forced) { + return this.config.quality.options; + } // Get sizes from <source> elements + + + return html5.getSources.call(this).map(source => Number(source.getAttribute('data-res'))).filter(Boolean); + }, + + setup() { + if (!this.isHTML5) { + return; + } + + const player = this; // Set speed options from config + + player.options.speed = player.config.speed.options; // Set aspect ratio if fixed + + if (!is.empty(this.config.ratio)) { + setAspectRatio.call(player); + } // Quality + + + Object.defineProperty(player.media, 'quality', { + get() { + // Get sources + const sources = html5.getSources.call(player); + const source = sources.find(s => s.getAttribute('src') === player.source); // Return size, if match is found + + return source && Number(source.getAttribute('data-res')); + }, + + set(input) { + if (player.quality === input) { + return; + } // If we're using an external handler... + + + if (player.config.quality.forced && is.function(player.config.quality.onChange)) { + player.config.quality.onChange(input); + } else { + // Get sources + const sources = html5.getSources.call(player); // Get first match for requested size + + const source = sources.find(s => Number(s.getAttribute('data-res')) === input); // No matching source found + + if (!source) { + return; + } // Get current state + + + const { + currentTime, + paused, + preload, + readyState, + playbackRate + } = player.media; // Set new source + + player.media.src = source.getAttribute('src'); // Prevent loading if preload="none" and the current source isn't loaded (#1044) + + if (preload !== 'none' || readyState) { + // Restore time + player.once('loadedmetadata', () => { + player.speed = playbackRate; + player.currentTime = currentTime; // Resume playing + + if (!paused) { + silencePromise(player.play()); + } + }); // Load new source + + player.media.load(); + } + } // Trigger change event + + + triggerEvent.call(player, player.media, 'qualitychange', false, { + quality: input + }); + } + + }); + }, + + // Cancel current network requests + // See https://github.com/sampotts/plyr/issues/174 + cancelRequests() { + if (!this.isHTML5) { + return; + } // Remove child sources + + + removeElement(html5.getSources.call(this)); // Set blank video src attribute + // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error + // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection + + this.media.setAttribute('src', this.config.blankVideo); // Load the new empty source + // This will cancel existing requests + // See https://github.com/sampotts/plyr/issues/174 + + this.media.load(); // Debugging + + this.debug.log('Cancelled network requests'); + } + + }; + + // ========================================================================== + + function generateId(prefix) { + return `${prefix}-${Math.floor(Math.random() * 10000)}`; + } // Format string + + function format(input, ...args) { + if (is.empty(input)) { + return input; + } + + return input.toString().replace(/{(\d+)}/g, (match, i) => args[i].toString()); + } // Get percentage + + function getPercentage(current, max) { + if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) { + return 0; + } + + return (current / max * 100).toFixed(2); + } // Replace all occurances of a string in a string + + const replaceAll = (input = '', find = '', replace = '') => input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\]/\\])/g, '\\$1'), 'g'), replace.toString()); // Convert to title case + + const toTitleCase = (input = '') => input.toString().replace(/\w\S*/g, text => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()); // Convert string to pascalCase + + function toPascalCase(input = '') { + let string = input.toString(); // Convert kebab case + + string = replaceAll(string, '-', ' '); // Convert snake case + + string = replaceAll(string, '_', ' '); // Convert to title case + + string = toTitleCase(string); // Convert to pascal case + + return replaceAll(string, ' ', ''); + } // Convert string to pascalCase + + function toCamelCase(input = '') { + let string = input.toString(); // Convert to pascal case + + string = toPascalCase(string); // Convert first character to lowercase + + return string.charAt(0).toLowerCase() + string.slice(1); + } // Remove HTML from a string + + function stripHTML(source) { + const fragment = document.createDocumentFragment(); + const element = document.createElement('div'); + fragment.appendChild(element); + element.innerHTML = source; + return fragment.firstChild.innerText; + } // Like outerHTML, but also works for DocumentFragment + + function getHTML(element) { + const wrapper = document.createElement('div'); + wrapper.appendChild(element); + return wrapper.innerHTML; + } + + // ========================================================================== + + const resources = { + pip: 'PIP', + airplay: 'AirPlay', + html5: 'HTML5', + vimeo: 'Vimeo', + youtube: 'YouTube' + }; + const i18n = { + get(key = '', config = {}) { + if (is.empty(key) || is.empty(config)) { + return ''; + } + + let string = getDeep(config.i18n, key); + + if (is.empty(string)) { + if (Object.keys(resources).includes(key)) { + return resources[key]; + } + + return ''; + } + + const replace = { + '{seektime}': config.seekTime, + '{title}': config.title + }; + Object.entries(replace).forEach(([k, v]) => { + string = replaceAll(string, k, v); + }); + return string; + } + + }; + + class Storage { + constructor(player) { + _defineProperty$1(this, "get", key => { + if (!Storage.supported || !this.enabled) { + return null; + } + + const store = window.localStorage.getItem(this.key); + + if (is.empty(store)) { + return null; + } + + const json = JSON.parse(store); + return is.string(key) && key.length ? json[key] : json; + }); + + _defineProperty$1(this, "set", object => { + // Bail if we don't have localStorage support or it's disabled + if (!Storage.supported || !this.enabled) { + return; + } // Can only store objectst + + + if (!is.object(object)) { + return; + } // Get current storage + + + let storage = this.get(); // Default to empty object + + if (is.empty(storage)) { + storage = {}; + } // Update the working copy of the values + + + extend(storage, object); // Update storage + + try { + window.localStorage.setItem(this.key, JSON.stringify(storage)); + } catch (_) {// Do nothing + } + }); + + this.enabled = player.config.storage.enabled; + this.key = player.config.storage.key; + } // Check for actual support (see if we can use it) + + + static get supported() { + try { + if (!('localStorage' in window)) { + return false; + } + + const test = '___test'; // Try to use it (it might be disabled, e.g. user is in private mode) + // see: https://github.com/sampotts/plyr/issues/131 + + window.localStorage.setItem(test, test); + window.localStorage.removeItem(test); + return true; + } catch (_) { + return false; + } + } + + } + + // ========================================================================== + // Fetch wrapper + // Using XHR to avoid issues with older browsers + // ========================================================================== + function fetch(url, responseType = 'text') { + return new Promise((resolve, reject) => { + try { + const request = new XMLHttpRequest(); // Check for CORS support + + if (!('withCredentials' in request)) { + return; + } + + request.addEventListener('load', () => { + if (responseType === 'text') { + try { + resolve(JSON.parse(request.responseText)); + } catch (_) { + resolve(request.responseText); + } + } else { + resolve(request.response); + } + }); + request.addEventListener('error', () => { + throw new Error(request.status); + }); + request.open('GET', url, true); // Set the required response type + + request.responseType = responseType; + request.send(); + } catch (error) { + reject(error); + } + }); + } + + // ========================================================================== + + function loadSprite(url, id) { + if (!is.string(url)) { + return; + } + + const prefix = 'cache'; + const hasId = is.string(id); + let isCached = false; + + const exists = () => document.getElementById(id) !== null; + + const update = (container, data) => { + // eslint-disable-next-line no-param-reassign + container.innerHTML = data; // Check again incase of race condition + + if (hasId && exists()) { + return; + } // Inject the SVG to the body + + + document.body.insertAdjacentElement('afterbegin', container); + }; // Only load once if ID set + + + if (!hasId || !exists()) { + const useStorage = Storage.supported; // Create container + + const container = document.createElement('div'); + container.setAttribute('hidden', ''); + + if (hasId) { + container.setAttribute('id', id); + } // Check in cache + + + if (useStorage) { + const cached = window.localStorage.getItem(`${prefix}-${id}`); + isCached = cached !== null; + + if (isCached) { + const data = JSON.parse(cached); + update(container, data.content); + } + } // Get the sprite + + + fetch(url).then(result => { + if (is.empty(result)) { + return; + } + + if (useStorage) { + try { + window.localStorage.setItem(`${prefix}-${id}`, JSON.stringify({ + content: result + })); + } catch (_) {// Do nothing + } + } + + update(container, result); + }).catch(() => {}); + } + } + + // ========================================================================== + + const getHours = value => Math.trunc(value / 60 / 60 % 60, 10); + const getMinutes = value => Math.trunc(value / 60 % 60, 10); + const getSeconds = value => Math.trunc(value % 60, 10); // Format time to UI friendly string + + function formatTime(time = 0, displayHours = false, inverted = false) { + // Bail if the value isn't a number + if (!is.number(time)) { + return formatTime(undefined, displayHours, inverted); + } // Format time component to add leading zero + + + const format = value => `0${value}`.slice(-2); // Breakdown to hours, mins, secs + + + let hours = getHours(time); + const mins = getMinutes(time); + const secs = getSeconds(time); // Do we need to display hours? + + if (displayHours || hours > 0) { + hours = `${hours}:`; + } else { + hours = ''; + } // Render + + + return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`; + } + + // ========================================================================== + + const controls = { + // Get icon URL + getIconUrl() { + const url = new URL(this.config.iconUrl, window.location); + const host = window.location.host ? window.location.host : window.top.location.host; + const cors = url.host !== host || browser.isIE && !window.svg4everybody; + return { + url: this.config.iconUrl, + cors + }; + }, + + // Find the UI controls + findElements() { + try { + this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper); // Buttons + + this.elements.buttons = { + play: getElements.call(this, this.config.selectors.buttons.play), + pause: getElement.call(this, this.config.selectors.buttons.pause), + restart: getElement.call(this, this.config.selectors.buttons.restart), + rewind: getElement.call(this, this.config.selectors.buttons.rewind), + fastForward: getElement.call(this, this.config.selectors.buttons.fastForward), + mute: getElement.call(this, this.config.selectors.buttons.mute), + pip: getElement.call(this, this.config.selectors.buttons.pip), + airplay: getElement.call(this, this.config.selectors.buttons.airplay), + settings: getElement.call(this, this.config.selectors.buttons.settings), + captions: getElement.call(this, this.config.selectors.buttons.captions), + fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen) + }; // Progress + + this.elements.progress = getElement.call(this, this.config.selectors.progress); // Inputs + + this.elements.inputs = { + seek: getElement.call(this, this.config.selectors.inputs.seek), + volume: getElement.call(this, this.config.selectors.inputs.volume) + }; // Display + + this.elements.display = { + buffer: getElement.call(this, this.config.selectors.display.buffer), + currentTime: getElement.call(this, this.config.selectors.display.currentTime), + duration: getElement.call(this, this.config.selectors.display.duration) + }; // Seek tooltip + + if (is.element(this.elements.progress)) { + this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`); + } + + return true; + } catch (error) { + // Log it + this.debug.warn('It looks like there is a problem with your custom controls HTML', error); // Restore native video controls + + this.toggleNativeControls(true); + return false; + } + }, + + // Create <svg> icon + createIcon(type, attributes) { + const namespace = 'http://www.w3.org/2000/svg'; + const iconUrl = controls.getIconUrl.call(this); + const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`; // Create <svg> + + const icon = document.createElementNS(namespace, 'svg'); + setAttributes(icon, extend(attributes, { + 'aria-hidden': 'true', + focusable: 'false' + })); // Create the <use> to reference sprite + + const use = document.createElementNS(namespace, 'use'); + const path = `${iconPath}-${type}`; // Set `href` attributes + // https://github.com/sampotts/plyr/issues/460 + // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href + + if ('href' in use) { + use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path); + } // Always set the older attribute even though it's "deprecated" (it'll be around for ages) + + + use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path); // Add <use> to <svg> + + icon.appendChild(use); + return icon; + }, + + // Create hidden text label + createLabel(key, attr = {}) { + const text = i18n.get(key, this.config); + const attributes = { ...attr, + class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ') + }; + return createElement('span', attributes, text); + }, + + // Create a badge + createBadge(text) { + if (is.empty(text)) { + return null; + } + + const badge = createElement('span', { + class: this.config.classNames.menu.value + }); + badge.appendChild(createElement('span', { + class: this.config.classNames.menu.badge + }, text)); + return badge; + }, + + // Create a <button> + createButton(buttonType, attr) { + const attributes = extend({}, attr); + let type = toCamelCase(buttonType); + const props = { + element: 'button', + toggle: false, + label: null, + icon: null, + labelPressed: null, + iconPressed: null + }; + ['element', 'icon', 'label'].forEach(key => { + if (Object.keys(attributes).includes(key)) { + props[key] = attributes[key]; + delete attributes[key]; + } + }); // Default to 'button' type to prevent form submission + + if (props.element === 'button' && !Object.keys(attributes).includes('type')) { + attributes.type = 'button'; + } // Set class name + + + if (Object.keys(attributes).includes('class')) { + if (!attributes.class.split(' ').some(c => c === this.config.classNames.control)) { + extend(attributes, { + class: `${attributes.class} ${this.config.classNames.control}` + }); + } + } else { + attributes.class = this.config.classNames.control; + } // Large play button + + + switch (buttonType) { + case 'play': + props.toggle = true; + props.label = 'play'; + props.labelPressed = 'pause'; + props.icon = 'play'; + props.iconPressed = 'pause'; + break; + + case 'mute': + props.toggle = true; + props.label = 'mute'; + props.labelPressed = 'unmute'; + props.icon = 'volume'; + props.iconPressed = 'muted'; + break; + + case 'captions': + props.toggle = true; + props.label = 'enableCaptions'; + props.labelPressed = 'disableCaptions'; + props.icon = 'captions-off'; + props.iconPressed = 'captions-on'; + break; + + case 'fullscreen': + props.toggle = true; + props.label = 'enterFullscreen'; + props.labelPressed = 'exitFullscreen'; + props.icon = 'enter-fullscreen'; + props.iconPressed = 'exit-fullscreen'; + break; + + case 'play-large': + attributes.class += ` ${this.config.classNames.control}--overlaid`; + type = 'play'; + props.label = 'play'; + props.icon = 'play'; + break; + + default: + if (is.empty(props.label)) { + props.label = type; + } + + if (is.empty(props.icon)) { + props.icon = buttonType; + } + + } + + const button = createElement(props.element); // Setup toggle icon and labels + + if (props.toggle) { + // Icon + button.appendChild(controls.createIcon.call(this, props.iconPressed, { + class: 'icon--pressed' + })); + button.appendChild(controls.createIcon.call(this, props.icon, { + class: 'icon--not-pressed' + })); // Label/Tooltip + + button.appendChild(controls.createLabel.call(this, props.labelPressed, { + class: 'label--pressed' + })); + button.appendChild(controls.createLabel.call(this, props.label, { + class: 'label--not-pressed' + })); + } else { + button.appendChild(controls.createIcon.call(this, props.icon)); + button.appendChild(controls.createLabel.call(this, props.label)); + } // Merge and set attributes + + + extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes)); + setAttributes(button, attributes); // We have multiple play buttons + + if (type === 'play') { + if (!is.array(this.elements.buttons[type])) { + this.elements.buttons[type] = []; + } + + this.elements.buttons[type].push(button); + } else { + this.elements.buttons[type] = button; + } + + return button; + }, + + // Create an <input type='range'> + createRange(type, attributes) { + // Seek input + const input = createElement('input', extend(getAttributesFromSelector(this.config.selectors.inputs[type]), { + type: 'range', + min: 0, + max: 100, + step: 0.01, + value: 0, + autocomplete: 'off', + // A11y fixes for https://github.com/sampotts/plyr/issues/905 + role: 'slider', + 'aria-label': i18n.get(type, this.config), + 'aria-valuemin': 0, + 'aria-valuemax': 100, + 'aria-valuenow': 0 + }, attributes)); + this.elements.inputs[type] = input; // Set the fill for webkit now + + controls.updateRangeFill.call(this, input); // Improve support on touch devices + + RangeTouch.setup(input); + return input; + }, + + // Create a <progress> + createProgress(type, attributes) { + const progress = createElement('progress', extend(getAttributesFromSelector(this.config.selectors.display[type]), { + min: 0, + max: 100, + value: 0, + role: 'progressbar', + 'aria-hidden': true + }, attributes)); // Create the label inside + + if (type !== 'volume') { + progress.appendChild(createElement('span', null, '0')); + const suffixKey = { + played: 'played', + buffer: 'buffered' + }[type]; + const suffix = suffixKey ? i18n.get(suffixKey, this.config) : ''; + progress.innerText = `% ${suffix.toLowerCase()}`; + } + + this.elements.display[type] = progress; + return progress; + }, + + // Create time display + createTime(type, attrs) { + const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs); + const container = createElement('div', extend(attributes, { + class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(), + 'aria-label': i18n.get(type, this.config) + }), '00:00'); // Reference for updates + + this.elements.display[type] = container; + return container; + }, + + // Bind keyboard shortcuts for a menu item + // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus + // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143 + bindMenuItemShortcuts(menuItem, type) { + // Navigate through menus via arrow keys and space + on.call(this, menuItem, 'keydown keyup', event => { + // We only care about space and ⬆️ ⬇️️ ➡️ + if (![32, 38, 39, 40].includes(event.which)) { + return; + } // Prevent play / seek + + + event.preventDefault(); + event.stopPropagation(); // We're just here to prevent the keydown bubbling + + if (event.type === 'keydown') { + return; + } + + const isRadioButton = matches(menuItem, '[role="menuitemradio"]'); // Show the respective menu + + if (!isRadioButton && [32, 39].includes(event.which)) { + controls.showMenuPanel.call(this, type, true); + } else { + let target; + + if (event.which !== 32) { + if (event.which === 40 || isRadioButton && event.which === 39) { + target = menuItem.nextElementSibling; + + if (!is.element(target)) { + target = menuItem.parentNode.firstElementChild; + } + } else { + target = menuItem.previousElementSibling; + + if (!is.element(target)) { + target = menuItem.parentNode.lastElementChild; + } + } + + setFocus.call(this, target, true); + } + } + }, false); // Enter will fire a `click` event but we still need to manage focus + // So we bind to keyup which fires after and set focus here + + on.call(this, menuItem, 'keyup', event => { + if (event.which !== 13) { + return; + } + + controls.focusFirstMenuItem.call(this, null, true); + }); + }, + + // Create a settings menu item + createMenuItem({ + value, + list, + type, + title, + badge = null, + checked = false + }) { + const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]); + const menuItem = createElement('button', extend(attributes, { + type: 'button', + role: 'menuitemradio', + class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(), + 'aria-checked': checked, + value + })); + const flex = createElement('span'); // We have to set as HTML incase of special characters + + flex.innerHTML = title; + + if (is.element(badge)) { + flex.appendChild(badge); + } + + menuItem.appendChild(flex); // Replicate radio button behaviour + + Object.defineProperty(menuItem, 'checked', { + enumerable: true, + + get() { + return menuItem.getAttribute('aria-checked') === 'true'; + }, + + set(check) { + // Ensure exclusivity + if (check) { + Array.from(menuItem.parentNode.children).filter(node => matches(node, '[role="menuitemradio"]')).forEach(node => node.setAttribute('aria-checked', 'false')); + } + + menuItem.setAttribute('aria-checked', check ? 'true' : 'false'); + } + + }); + this.listeners.bind(menuItem, 'click keyup', event => { + if (is.keyboardEvent(event) && event.which !== 32) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + menuItem.checked = true; + + switch (type) { + case 'language': + this.currentTrack = Number(value); + break; + + case 'quality': + this.quality = value; + break; + + case 'speed': + this.speed = parseFloat(value); + break; + } + + controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event)); + }, type, false); + controls.bindMenuItemShortcuts.call(this, menuItem, type); + list.appendChild(menuItem); + }, + + // Format a time for display + formatTime(time = 0, inverted = false) { + // Bail if the value isn't a number + if (!is.number(time)) { + return time; + } // Always display hours if duration is over an hour + + + const forceHours = getHours(this.duration) > 0; + return formatTime(time, forceHours, inverted); + }, + + // Update the displayed time + updateTimeDisplay(target = null, time = 0, inverted = false) { + // Bail if there's no element to display or the value isn't a number + if (!is.element(target) || !is.number(time)) { + return; + } // eslint-disable-next-line no-param-reassign + + + target.innerText = controls.formatTime(time, inverted); + }, + + // Update volume UI and storage + updateVolume() { + if (!this.supported.ui) { + return; + } // Update range + + + if (is.element(this.elements.inputs.volume)) { + controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume); + } // Update mute state + + + if (is.element(this.elements.buttons.mute)) { + this.elements.buttons.mute.pressed = this.muted || this.volume === 0; + } + }, + + // Update seek value and lower fill + setRange(target, value = 0) { + if (!is.element(target)) { + return; + } // eslint-disable-next-line + + + target.value = value; // Webkit range fill + + controls.updateRangeFill.call(this, target); + }, + + // Update <progress> elements + updateProgress(event) { + if (!this.supported.ui || !is.event(event)) { + return; + } + + let value = 0; + + const setProgress = (target, input) => { + const val = is.number(input) ? input : 0; + const progress = is.element(target) ? target : this.elements.display.buffer; // Update value and label + + if (is.element(progress)) { + progress.value = val; // Update text label inside + + const label = progress.getElementsByTagName('span')[0]; + + if (is.element(label)) { + label.childNodes[0].nodeValue = val; + } + } + }; + + if (event) { + switch (event.type) { + // Video playing + case 'timeupdate': + case 'seeking': + case 'seeked': + value = getPercentage(this.currentTime, this.duration); // Set seek range value only if it's a 'natural' time event + + if (event.type === 'timeupdate') { + controls.setRange.call(this, this.elements.inputs.seek, value); + } + + break; + // Check buffer status + + case 'playing': + case 'progress': + setProgress(this.elements.display.buffer, this.buffered * 100); + break; + } + } + }, + + // Webkit polyfill for lower fill range + updateRangeFill(target) { + // Get range from event if event passed + const range = is.event(target) ? target.target : target; // Needs to be a valid <input type='range'> + + if (!is.element(range) || range.getAttribute('type') !== 'range') { + return; + } // Set aria values for https://github.com/sampotts/plyr/issues/905 + + + if (matches(range, this.config.selectors.inputs.seek)) { + range.setAttribute('aria-valuenow', this.currentTime); + const currentTime = controls.formatTime(this.currentTime); + const duration = controls.formatTime(this.duration); + const format = i18n.get('seekLabel', this.config); + range.setAttribute('aria-valuetext', format.replace('{currentTime}', currentTime).replace('{duration}', duration)); + } else if (matches(range, this.config.selectors.inputs.volume)) { + const percent = range.value * 100; + range.setAttribute('aria-valuenow', percent); + range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`); + } else { + range.setAttribute('aria-valuenow', range.value); + } // WebKit only + + + if (!browser.isWebkit) { + return; + } // Set CSS custom property + + + range.style.setProperty('--value', `${range.value / range.max * 100}%`); + }, + + // Update hover tooltip for seeking + updateSeekTooltip(event) { + // Bail if setting not true + if (!this.config.tooltips.seek || !is.element(this.elements.inputs.seek) || !is.element(this.elements.display.seekTooltip) || this.duration === 0) { + return; + } + + const visible = `${this.config.classNames.tooltip}--visible`; + + const toggle = show => toggleClass(this.elements.display.seekTooltip, visible, show); // Hide on touch + + + if (this.touch) { + toggle(false); + return; + } // Determine percentage, if already visible + + + let percent = 0; + const clientRect = this.elements.progress.getBoundingClientRect(); + + if (is.event(event)) { + percent = 100 / clientRect.width * (event.pageX - clientRect.left); + } else if (hasClass(this.elements.display.seekTooltip, visible)) { + percent = parseFloat(this.elements.display.seekTooltip.style.left, 10); + } else { + return; + } // Set bounds + + + if (percent < 0) { + percent = 0; + } else if (percent > 100) { + percent = 100; + } // Display the time a click would seek to + + + controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent); // Set position + + this.elements.display.seekTooltip.style.left = `${percent}%`; // Show/hide the tooltip + // If the event is a moues in/out and percentage is inside bounds + + if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) { + toggle(event.type === 'mouseenter'); + } + }, + + // Handle time change event + timeUpdate(event) { + // Only invert if only one time element is displayed and used for both duration and currentTime + const invert = !is.element(this.elements.display.duration) && this.config.invertTime; // Duration + + controls.updateTimeDisplay.call(this, this.elements.display.currentTime, invert ? this.duration - this.currentTime : this.currentTime, invert); // Ignore updates while seeking + + if (event && event.type === 'timeupdate' && this.media.seeking) { + return; + } // Playing progress + + + controls.updateProgress.call(this, event); + }, + + // Show the duration on metadataloaded or durationchange events + durationUpdate() { + // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false + if (!this.supported.ui || !this.config.invertTime && this.currentTime) { + return; + } // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar. + // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415 + // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062 + // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338 + + + if (this.duration >= 2 ** 32) { + toggleHidden(this.elements.display.currentTime, true); + toggleHidden(this.elements.progress, true); + return; + } // Update ARIA values + + + if (is.element(this.elements.inputs.seek)) { + this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration); + } // If there's a spot to display duration + + + const hasDuration = is.element(this.elements.display.duration); // If there's only one time display, display duration there + + if (!hasDuration && this.config.displayDuration && this.paused) { + controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration); + } // If there's a duration element, update content + + + if (hasDuration) { + controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration); + } // Update the tooltip (if visible) + + + controls.updateSeekTooltip.call(this); + }, + + // Hide/show a tab + toggleMenuButton(setting, toggle) { + toggleHidden(this.elements.settings.buttons[setting], !toggle); + }, + + // Update the selected setting + updateSetting(setting, container, input) { + const pane = this.elements.settings.panels[setting]; + let value = null; + let list = container; + + if (setting === 'captions') { + value = this.currentTrack; + } else { + value = !is.empty(input) ? input : this[setting]; // Get default + + if (is.empty(value)) { + value = this.config[setting].default; + } // Unsupported value + + + if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) { + this.debug.warn(`Unsupported value of '${value}' for ${setting}`); + return; + } // Disabled value + + + if (!this.config[setting].options.includes(value)) { + this.debug.warn(`Disabled value of '${value}' for ${setting}`); + return; + } + } // Get the list if we need to + + + if (!is.element(list)) { + list = pane && pane.querySelector('[role="menu"]'); + } // If there's no list it means it's not been rendered... + + + if (!is.element(list)) { + return; + } // Update the label + + + const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`); + label.innerHTML = controls.getLabel.call(this, setting, value); // Find the radio option and check it + + const target = list && list.querySelector(`[value="${value}"]`); + + if (is.element(target)) { + target.checked = true; + } + }, + + // Translate a value into a nice label + getLabel(setting, value) { + switch (setting) { + case 'speed': + return value === 1 ? i18n.get('normal', this.config) : `${value}×`; + + case 'quality': + if (is.number(value)) { + const label = i18n.get(`qualityLabel.${value}`, this.config); + + if (!label.length) { + return `${value}p`; + } + + return label; + } + + return toTitleCase(value); + + case 'captions': + return captions.getLabel.call(this); + + default: + return null; + } + }, + + // Set the quality menu + setQualityMenu(options) { + // Menu required + if (!is.element(this.elements.settings.panels.quality)) { + return; + } + + const type = 'quality'; + const list = this.elements.settings.panels.quality.querySelector('[role="menu"]'); // Set options if passed and filter based on uniqueness and config + + if (is.array(options)) { + this.options.quality = dedupe(options).filter(quality => this.config.quality.options.includes(quality)); + } // Toggle the pane and tab + + + const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1; + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If we're hiding, nothing more to do + + if (!toggle) { + return; + } // Get the badge HTML for HD, 4K etc + + + const getBadge = quality => { + const label = i18n.get(`qualityBadge.${quality}`, this.config); + + if (!label.length) { + return null; + } + + return controls.createBadge.call(this, label); + }; // Sort options by the config and then render options + + + this.options.quality.sort((a, b) => { + const sorting = this.config.quality.options; + return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1; + }).forEach(quality => { + controls.createMenuItem.call(this, { + value: quality, + list, + type, + title: controls.getLabel.call(this, 'quality', quality), + badge: getBadge(quality) + }); + }); + controls.updateSetting.call(this, type, list); + }, + + // Set the looping options + + /* setLoopMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.loop)) { + return; + } + const options = ['start', 'end', 'all', 'reset']; + const list = this.elements.settings.panels.loop.querySelector('[role="menu"]'); + // Show the pane and tab + toggleHidden(this.elements.settings.buttons.loop, false); + toggleHidden(this.elements.settings.panels.loop, false); + // Toggle the pane and tab + const toggle = !is.empty(this.loop.options); + controls.toggleMenuButton.call(this, 'loop', toggle); + // Empty the menu + emptyElement(list); + options.forEach(option => { + const item = createElement('li'); + const button = createElement( + 'button', + extend(getAttributesFromSelector(this.config.selectors.buttons.loop), { + type: 'button', + class: this.config.classNames.control, + 'data-plyr-loop-action': option, + }), + i18n.get(option, this.config) + ); + if (['start', 'end'].includes(option)) { + const badge = controls.createBadge.call(this, '00:00'); + button.appendChild(badge); + } + item.appendChild(button); + list.appendChild(item); + }); + }, */ + // Get current selected caption language + // TODO: rework this to user the getter in the API? + // Set a list of available captions languages + setCaptionsMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.captions)) { + return; + } // TODO: Captions or language? Currently it's mixed + + + const type = 'captions'; + const list = this.elements.settings.panels.captions.querySelector('[role="menu"]'); + const tracks = captions.getTracks.call(this); + const toggle = Boolean(tracks.length); // Toggle the pane and tab + + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If there's no captions, bail + + if (!toggle) { + return; + } // Generate options data + + + const options = tracks.map((track, value) => ({ + value, + checked: this.captions.toggled && this.currentTrack === value, + title: captions.getLabel.call(this, track), + badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()), + list, + type: 'language' + })); // Add the "Disabled" option to turn off captions + + options.unshift({ + value: -1, + checked: !this.captions.toggled, + title: i18n.get('disabled', this.config), + list, + type: 'language' + }); // Generate options + + options.forEach(controls.createMenuItem.bind(this)); + controls.updateSetting.call(this, type, list); + }, + + // Set a list of available captions languages + setSpeedMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.speed)) { + return; + } + + const type = 'speed'; + const list = this.elements.settings.panels.speed.querySelector('[role="menu"]'); // Filter out invalid speeds + + this.options.speed = this.options.speed.filter(o => o >= this.minimumSpeed && o <= this.maximumSpeed); // Toggle the pane and tab + + const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1; + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If we're hiding, nothing more to do + + if (!toggle) { + return; + } // Create items + + + this.options.speed.forEach(speed => { + controls.createMenuItem.call(this, { + value: speed, + list, + type, + title: controls.getLabel.call(this, 'speed', speed) + }); + }); + controls.updateSetting.call(this, type, list); + }, + + // Check if we need to hide/show the settings menu + checkMenu() { + const { + buttons + } = this.elements.settings; + const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden); + toggleHidden(this.elements.settings.menu, !visible); + }, + + // Focus the first menu item in a given (or visible) menu + focusFirstMenuItem(pane, tabFocus = false) { + if (this.elements.settings.popup.hidden) { + return; + } + + let target = pane; + + if (!is.element(target)) { + target = Object.values(this.elements.settings.panels).find(p => !p.hidden); + } + + const firstItem = target.querySelector('[role^="menuitem"]'); + setFocus.call(this, firstItem, tabFocus); + }, + + // Show/hide menu + toggleMenu(input) { + const { + popup + } = this.elements.settings; + const button = this.elements.buttons.settings; // Menu and button are required + + if (!is.element(popup) || !is.element(button)) { + return; + } // True toggle by default + + + const { + hidden + } = popup; + let show = hidden; + + if (is.boolean(input)) { + show = input; + } else if (is.keyboardEvent(input) && input.which === 27) { + show = false; + } else if (is.event(input)) { + // If Plyr is in a shadowDOM, the event target is set to the component, instead of the + // Element in the shadowDOM. The path, if available, is complete. + const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target; + const isMenuItem = popup.contains(target); // If the click was inside the menu or if the click + // wasn't the button or menu item and we're trying to + // show the menu (a doc click shouldn't show the menu) + + if (isMenuItem || !isMenuItem && input.target !== button && show) { + return; + } + } // Set button attributes + + + button.setAttribute('aria-expanded', show); // Show the actual popup + + toggleHidden(popup, !show); // Add class hook + + toggleClass(this.elements.container, this.config.classNames.menu.open, show); // Focus the first item if key interaction + + if (show && is.keyboardEvent(input)) { + controls.focusFirstMenuItem.call(this, null, true); + } else if (!show && !hidden) { + // If closing, re-focus the button + setFocus.call(this, button, is.keyboardEvent(input)); + } + }, + + // Get the natural size of a menu panel + getMenuSize(tab) { + const clone = tab.cloneNode(true); + clone.style.position = 'absolute'; + clone.style.opacity = 0; + clone.removeAttribute('hidden'); // Append to parent so we get the "real" size + + tab.parentNode.appendChild(clone); // Get the sizes before we remove + + const width = clone.scrollWidth; + const height = clone.scrollHeight; // Remove from the DOM + + removeElement(clone); + return { + width, + height + }; + }, + + // Show a panel in the menu + showMenuPanel(type = '', tabFocus = false) { + const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`); // Nothing to show, bail + + if (!is.element(target)) { + return; + } // Hide all other panels + + + const container = target.parentNode; + const current = Array.from(container.children).find(node => !node.hidden); // If we can do fancy animations, we'll animate the height/width + + if (support.transitions && !support.reducedMotion) { + // Set the current width as a base + container.style.width = `${current.scrollWidth}px`; + container.style.height = `${current.scrollHeight}px`; // Get potential sizes + + const size = controls.getMenuSize.call(this, target); // Restore auto height/width + + const restore = event => { + // We're only bothered about height and width on the container + if (event.target !== container || !['width', 'height'].includes(event.propertyName)) { + return; + } // Revert back to auto + + + container.style.width = ''; + container.style.height = ''; // Only listen once + + off.call(this, container, transitionEndEvent, restore); + }; // Listen for the transition finishing and restore auto height/width + + + on.call(this, container, transitionEndEvent, restore); // Set dimensions to target + + container.style.width = `${size.width}px`; + container.style.height = `${size.height}px`; + } // Set attributes on current tab + + + toggleHidden(current, true); // Set attributes on target + + toggleHidden(target, false); // Focus the first item + + controls.focusFirstMenuItem.call(this, target, tabFocus); + }, + + // Set the download URL + setDownloadUrl() { + const button = this.elements.buttons.download; // Bail if no button + + if (!is.element(button)) { + return; + } // Set attribute + + + button.setAttribute('href', this.download); + }, + + // Build the default HTML + create(data) { + const { + bindMenuItemShortcuts, + createButton, + createProgress, + createRange, + createTime, + setQualityMenu, + setSpeedMenu, + showMenuPanel + } = controls; + this.elements.controls = null; // Larger overlaid play button + + if (is.array(this.config.controls) && this.config.controls.includes('play-large')) { + this.elements.container.appendChild(createButton.call(this, 'play-large')); + } // Create the container + + + const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper)); + this.elements.controls = container; // Default item attributes + + const defaultAttributes = { + class: 'plyr__controls__item' + }; // Loop through controls in order + + dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach(control => { + // Restart button + if (control === 'restart') { + container.appendChild(createButton.call(this, 'restart', defaultAttributes)); + } // Rewind button + + + if (control === 'rewind') { + container.appendChild(createButton.call(this, 'rewind', defaultAttributes)); + } // Play/Pause button + + + if (control === 'play') { + container.appendChild(createButton.call(this, 'play', defaultAttributes)); + } // Fast forward button + + + if (control === 'fast-forward') { + container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes)); + } // Progress + + + if (control === 'progress') { + const progressContainer = createElement('div', { + class: `${defaultAttributes.class} plyr__progress__container` + }); + const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress)); // Seek range slider + + progress.appendChild(createRange.call(this, 'seek', { + id: `plyr-seek-${data.id}` + })); // Buffer progress + + progress.appendChild(createProgress.call(this, 'buffer')); // TODO: Add loop display indicator + // Seek tooltip + + if (this.config.tooltips.seek) { + const tooltip = createElement('span', { + class: this.config.classNames.tooltip + }, '00:00'); + progress.appendChild(tooltip); + this.elements.display.seekTooltip = tooltip; + } + + this.elements.progress = progress; + progressContainer.appendChild(this.elements.progress); + container.appendChild(progressContainer); + } // Media current time display + + + if (control === 'current-time') { + container.appendChild(createTime.call(this, 'currentTime', defaultAttributes)); + } // Media duration display + + + if (control === 'duration') { + container.appendChild(createTime.call(this, 'duration', defaultAttributes)); + } // Volume controls + + + if (control === 'mute' || control === 'volume') { + let { + volume + } = this.elements; // Create the volume container if needed + + if (!is.element(volume) || !container.contains(volume)) { + volume = createElement('div', extend({}, defaultAttributes, { + class: `${defaultAttributes.class} plyr__volume`.trim() + })); + this.elements.volume = volume; + container.appendChild(volume); + } // Toggle mute button + + + if (control === 'mute') { + volume.appendChild(createButton.call(this, 'mute')); + } // Volume range control + // Ignored on iOS as it's handled globally + // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html + + + if (control === 'volume' && !browser.isIos) { + // Set the attributes + const attributes = { + max: 1, + step: 0.05, + value: this.config.volume + }; // Create the volume range slider + + volume.appendChild(createRange.call(this, 'volume', extend(attributes, { + id: `plyr-volume-${data.id}` + }))); + } + } // Toggle captions button + + + if (control === 'captions') { + container.appendChild(createButton.call(this, 'captions', defaultAttributes)); + } // Settings button / menu + + + if (control === 'settings' && !is.empty(this.config.settings)) { + const wrapper = createElement('div', extend({}, defaultAttributes, { + class: `${defaultAttributes.class} plyr__menu`.trim(), + hidden: '' + })); + wrapper.appendChild(createButton.call(this, 'settings', { + 'aria-haspopup': true, + 'aria-controls': `plyr-settings-${data.id}`, + 'aria-expanded': false + })); + const popup = createElement('div', { + class: 'plyr__menu__container', + id: `plyr-settings-${data.id}`, + hidden: '' + }); + const inner = createElement('div'); + const home = createElement('div', { + id: `plyr-settings-${data.id}-home` + }); // Create the menu + + const menu = createElement('div', { + role: 'menu' + }); + home.appendChild(menu); + inner.appendChild(home); + this.elements.settings.panels.home = home; // Build the menu items + + this.config.settings.forEach(type => { + // TODO: bundle this with the createMenuItem helper and bindings + const menuItem = createElement('button', extend(getAttributesFromSelector(this.config.selectors.buttons.settings), { + type: 'button', + class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`, + role: 'menuitem', + 'aria-haspopup': true, + hidden: '' + })); // Bind menu shortcuts for keyboard users + + bindMenuItemShortcuts.call(this, menuItem, type); // Show menu on click + + on.call(this, menuItem, 'click', () => { + showMenuPanel.call(this, type, false); + }); + const flex = createElement('span', null, i18n.get(type, this.config)); + const value = createElement('span', { + class: this.config.classNames.menu.value + }); // Speed contains HTML entities + + value.innerHTML = data[type]; + flex.appendChild(value); + menuItem.appendChild(flex); + menu.appendChild(menuItem); // Build the panes + + const pane = createElement('div', { + id: `plyr-settings-${data.id}-${type}`, + hidden: '' + }); // Back button + + const backButton = createElement('button', { + type: 'button', + class: `${this.config.classNames.control} ${this.config.classNames.control}--back` + }); // Visible label + + backButton.appendChild(createElement('span', { + 'aria-hidden': true + }, i18n.get(type, this.config))); // Screen reader label + + backButton.appendChild(createElement('span', { + class: this.config.classNames.hidden + }, i18n.get('menuBack', this.config))); // Go back via keyboard + + on.call(this, pane, 'keydown', event => { + // We only care about <- + if (event.which !== 37) { + return; + } // Prevent seek + + + event.preventDefault(); + event.stopPropagation(); // Show the respective menu + + showMenuPanel.call(this, 'home', true); + }, false); // Go back via button click + + on.call(this, backButton, 'click', () => { + showMenuPanel.call(this, 'home', false); + }); // Add to pane + + pane.appendChild(backButton); // Menu + + pane.appendChild(createElement('div', { + role: 'menu' + })); + inner.appendChild(pane); + this.elements.settings.buttons[type] = menuItem; + this.elements.settings.panels[type] = pane; + }); + popup.appendChild(inner); + wrapper.appendChild(popup); + container.appendChild(wrapper); + this.elements.settings.popup = popup; + this.elements.settings.menu = wrapper; + } // Picture in picture button + + + if (control === 'pip' && support.pip) { + container.appendChild(createButton.call(this, 'pip', defaultAttributes)); + } // Airplay button + + + if (control === 'airplay' && support.airplay) { + container.appendChild(createButton.call(this, 'airplay', defaultAttributes)); + } // Download button + + + if (control === 'download') { + const attributes = extend({}, defaultAttributes, { + element: 'a', + href: this.download, + target: '_blank' + }); // Set download attribute for HTML5 only + + if (this.isHTML5) { + attributes.download = ''; + } + + const { + download + } = this.config.urls; + + if (!is.url(download) && this.isEmbed) { + extend(attributes, { + icon: `logo-${this.provider}`, + label: this.provider + }); + } + + container.appendChild(createButton.call(this, 'download', attributes)); + } // Toggle fullscreen button + + + if (control === 'fullscreen') { + container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes)); + } + }); // Set available quality levels + + if (this.isHTML5) { + setQualityMenu.call(this, html5.getQualityOptions.call(this)); + } + + setSpeedMenu.call(this); + return container; + }, + + // Insert controls + inject() { + // Sprite + if (this.config.loadSprite) { + const icon = controls.getIconUrl.call(this); // Only load external sprite using AJAX + + if (icon.cors) { + loadSprite(icon.url, 'sprite-plyr'); + } + } // Create a unique ID + + + this.id = Math.floor(Math.random() * 10000); // Null by default + + let container = null; + this.elements.controls = null; // Set template properties + + const props = { + id: this.id, + seektime: this.config.seekTime, + title: this.config.title + }; + let update = true; // If function, run it and use output + + if (is.function(this.config.controls)) { + this.config.controls = this.config.controls.call(this, props); + } // Convert falsy controls to empty array (primarily for empty strings) + + + if (!this.config.controls) { + this.config.controls = []; + } + + if (is.element(this.config.controls) || is.string(this.config.controls)) { + // HTMLElement or Non-empty string passed as the option + container = this.config.controls; + } else { + // Create controls + container = controls.create.call(this, { + id: this.id, + seektime: this.config.seekTime, + speed: this.speed, + quality: this.quality, + captions: captions.getLabel.call(this) // TODO: Looping + // loop: 'None', + + }); + update = false; + } // Replace props with their value + + + const replace = input => { + let result = input; + Object.entries(props).forEach(([key, value]) => { + result = replaceAll(result, `{${key}}`, value); + }); + return result; + }; // Update markup + + + if (update) { + if (is.string(this.config.controls)) { + container = replace(container); + } + } // Controls container + + + let target; // Inject to custom location + + if (is.string(this.config.selectors.controls.container)) { + target = document.querySelector(this.config.selectors.controls.container); + } // Inject into the container by default + + + if (!is.element(target)) { + target = this.elements.container; + } // Inject controls HTML (needs to be before captions, hence "afterbegin") + + + const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML'; + target[insertMethod]('afterbegin', container); // Find the elements if need be + + if (!is.element(this.elements.controls)) { + controls.findElements.call(this); + } // Add pressed property to buttons + + + if (!is.empty(this.elements.buttons)) { + const addProperty = button => { + const className = this.config.classNames.controlPressed; + Object.defineProperty(button, 'pressed', { + enumerable: true, + + get() { + return hasClass(button, className); + }, + + set(pressed = false) { + toggleClass(button, className, pressed); + } + + }); + }; // Toggle classname when pressed property is set + + + Object.values(this.elements.buttons).filter(Boolean).forEach(button => { + if (is.array(button) || is.nodeList(button)) { + Array.from(button).filter(Boolean).forEach(addProperty); + } else { + addProperty(button); + } + }); + } // Edge sometimes doesn't finish the paint so force a repaint + + + if (browser.isEdge) { + repaint(target); + } // Setup tooltips + + + if (this.config.tooltips.controls) { + const { + classNames, + selectors + } = this.config; + const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`; + const labels = getElements.call(this, selector); + Array.from(labels).forEach(label => { + toggleClass(label, this.config.classNames.hidden, false); + toggleClass(label, this.config.classNames.tooltip, true); + }); + } + } + + }; + + // ========================================================================== + /** + * Parse a string to a URL object + * @param {String} input - the URL to be parsed + * @param {Boolean} safe - failsafe parsing + */ + + function parseUrl(input, safe = true) { + let url = input; + + if (safe) { + const parser = document.createElement('a'); + parser.href = url; + url = parser.href; + } + + try { + return new URL(url); + } catch (_) { + return null; + } + } // Convert object to URLSearchParams + + function buildUrlParams(input) { + const params = new URLSearchParams(); + + if (is.object(input)) { + Object.entries(input).forEach(([key, value]) => { + params.set(key, value); + }); + } + + return params; + } + + // ========================================================================== + const captions = { + // Setup captions + setup() { + // Requires UI support + if (!this.supported.ui) { + return; + } // Only Vimeo and HTML5 video supported at this point + + + if (!this.isVideo || this.isYouTube || this.isHTML5 && !support.textTracks) { + // Clear menu and hide + if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) { + controls.setCaptionsMenu.call(this); + } + + return; + } // Inject the container + + + if (!is.element(this.elements.captions)) { + this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions)); + insertAfter(this.elements.captions, this.elements.wrapper); + } // Fix IE captions if CORS is used + // Fetch captions and inject as blobs instead (data URIs not supported!) + + + if (browser.isIE && window.URL) { + const elements = this.media.querySelectorAll('track'); + Array.from(elements).forEach(track => { + const src = track.getAttribute('src'); + const url = parseUrl(src); + + if (url !== null && url.hostname !== window.location.href.hostname && ['http:', 'https:'].includes(url.protocol)) { + fetch(src, 'blob').then(blob => { + track.setAttribute('src', window.URL.createObjectURL(blob)); + }).catch(() => { + removeElement(track); + }); + } + }); + } // Get and set initial data + // The "preferred" options are not realized unless / until the wanted language has a match + // * languages: Array of user's browser languages. + // * language: The language preferred by user settings or config + // * active: The state preferred by user settings or config + // * toggled: The real captions state + + + const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en']; + const languages = dedupe(browserLanguages.map(language => language.split('-')[0])); + let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase(); // Use first browser language when language is 'auto' + + if (language === 'auto') { + [language] = languages; + } + + let active = this.storage.get('captions'); + + if (!is.boolean(active)) { + ({ + active + } = this.config.captions); + } + + Object.assign(this.captions, { + toggled: false, + active, + language, + languages + }); // Watch changes to textTracks and update captions menu + + if (this.isHTML5) { + const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack'; + on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this)); + } // Update available languages in list next tick (the event must not be triggered before the listeners) + + + setTimeout(captions.update.bind(this), 0); + }, + + // Update available language options in settings based on tracks + update() { + const tracks = captions.getTracks.call(this, true); // Get the wanted language + + const { + active, + language, + meta, + currentTrackNode + } = this.captions; + const languageExists = Boolean(tracks.find(track => track.language === language)); // Handle tracks (add event listener and "pseudo"-default) + + if (this.isHTML5 && this.isVideo) { + tracks.filter(track => !meta.get(track)).forEach(track => { + this.debug.log('Track added', track); // Attempt to store if the original dom element was "default" + + meta.set(track, { + default: track.mode === 'showing' + }); // Turn off native caption rendering to avoid double captions + // Note: mode='hidden' forces a track to download. To ensure every track + // isn't downloaded at once, only 'showing' tracks should be reassigned + // eslint-disable-next-line no-param-reassign + + if (track.mode === 'showing') { + // eslint-disable-next-line no-param-reassign + track.mode = 'hidden'; + } // Add event listener for cue changes + + + on.call(this, track, 'cuechange', () => captions.updateCues.call(this)); + }); + } // Update language first time it matches, or if the previous matching track was removed + + + if (languageExists && this.language !== language || !tracks.includes(currentTrackNode)) { + captions.setLanguage.call(this, language); + captions.toggle.call(this, active && languageExists); + } // Enable or disable captions based on track length + + + if (this.elements) { + toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks)); + } // Update available languages in list + + + if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) { + controls.setCaptionsMenu.call(this); + } + }, + + // Toggle captions display + // Used internally for the toggleCaptions method, with the passive option forced to false + toggle(input, passive = true) { + // If there's no full support + if (!this.supported.ui) { + return; + } + + const { + toggled + } = this.captions; // Current state + + const activeClass = this.config.classNames.captions.active; // Get the next state + // If the method is called without parameter, toggle based on current value + + const active = is.nullOrUndefined(input) ? !toggled : input; // Update state and trigger event + + if (active !== toggled) { + // When passive, don't override user preferences + if (!passive) { + this.captions.active = active; + this.storage.set({ + captions: active + }); + } // Force language if the call isn't passive and there is no matching language to toggle to + + + if (!this.language && active && !passive) { + const tracks = captions.getTracks.call(this); + const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true); // Override user preferences to avoid switching languages if a matching track is added + + this.captions.language = track.language; // Set caption, but don't store in localStorage as user preference + + captions.set.call(this, tracks.indexOf(track)); + return; + } // Toggle button if it's enabled + + + if (this.elements.buttons.captions) { + this.elements.buttons.captions.pressed = active; + } // Add class hook + + + toggleClass(this.elements.container, activeClass, active); + this.captions.toggled = active; // Update settings menu + + controls.updateSetting.call(this, 'captions'); // Trigger event (not used internally) + + triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled'); + } // Wait for the call stack to clear before setting mode='hidden' + // on the active track - forcing the browser to download it + + + setTimeout(() => { + if (active && this.captions.toggled) { + this.captions.currentTrackNode.mode = 'hidden'; + } + }); + }, + + // Set captions by track index + // Used internally for the currentTrack setter with the passive option forced to false + set(index, passive = true) { + const tracks = captions.getTracks.call(this); // Disable captions if setting to -1 + + if (index === -1) { + captions.toggle.call(this, false, passive); + return; + } + + if (!is.number(index)) { + this.debug.warn('Invalid caption argument', index); + return; + } + + if (!(index in tracks)) { + this.debug.warn('Track not found', index); + return; + } + + if (this.captions.currentTrack !== index) { + this.captions.currentTrack = index; + const track = tracks[index]; + const { + language + } = track || {}; // Store reference to node for invalidation on remove + + this.captions.currentTrackNode = track; // Update settings menu + + controls.updateSetting.call(this, 'captions'); // When passive, don't override user preferences + + if (!passive) { + this.captions.language = language; + this.storage.set({ + language + }); + } // Handle Vimeo captions + + + if (this.isVimeo) { + this.embed.enableTextTrack(language); + } // Trigger event + + + triggerEvent.call(this, this.media, 'languagechange'); + } // Show captions + + + captions.toggle.call(this, true, passive); + + if (this.isHTML5 && this.isVideo) { + // If we change the active track while a cue is already displayed we need to update it + captions.updateCues.call(this); + } + }, + + // Set captions by language + // Used internally for the language setter with the passive option forced to false + setLanguage(input, passive = true) { + if (!is.string(input)) { + this.debug.warn('Invalid language argument', input); + return; + } // Normalize + + + const language = input.toLowerCase(); + this.captions.language = language; // Set currentTrack + + const tracks = captions.getTracks.call(this); + const track = captions.findTrack.call(this, [language]); + captions.set.call(this, tracks.indexOf(track), passive); + }, + + // Get current valid caption tracks + // If update is false it will also ignore tracks without metadata + // This is used to "freeze" the language options when captions.update is false + getTracks(update = false) { + // Handle media or textTracks missing or null + const tracks = Array.from((this.media || {}).textTracks || []); // For HTML5, use cache instead of current tracks when it exists (if captions.update is false) + // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata) + + return tracks.filter(track => !this.isHTML5 || update || this.captions.meta.has(track)).filter(track => ['captions', 'subtitles'].includes(track.kind)); + }, + + // Match tracks based on languages and get the first + findTrack(languages, force = false) { + const tracks = captions.getTracks.call(this); + + const sortIsDefault = track => Number((this.captions.meta.get(track) || {}).default); + + const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a)); + let track; + languages.every(language => { + track = sorted.find(t => t.language === language); + return !track; // Break iteration if there is a match + }); // If no match is found but is required, get first + + return track || (force ? sorted[0] : undefined); + }, + + // Get the current track + getCurrentTrack() { + return captions.getTracks.call(this)[this.currentTrack]; + }, + + // Get UI label for track + getLabel(track) { + let currentTrack = track; + + if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) { + currentTrack = captions.getCurrentTrack.call(this); + } + + if (is.track(currentTrack)) { + if (!is.empty(currentTrack.label)) { + return currentTrack.label; + } + + if (!is.empty(currentTrack.language)) { + return track.language.toUpperCase(); + } + + return i18n.get('enabled', this.config); + } + + return i18n.get('disabled', this.config); + }, + + // Update captions using current track's active cues + // Also optional array argument in case there isn't any track (ex: vimeo) + updateCues(input) { + // Requires UI + if (!this.supported.ui) { + return; + } + + if (!is.element(this.elements.captions)) { + this.debug.warn('No captions element to render to'); + return; + } // Only accept array or empty input + + + if (!is.nullOrUndefined(input) && !Array.isArray(input)) { + this.debug.warn('updateCues: Invalid input', input); + return; + } + + let cues = input; // Get cues from track + + if (!cues) { + const track = captions.getCurrentTrack.call(this); + cues = Array.from((track || {}).activeCues || []).map(cue => cue.getCueAsHTML()).map(getHTML); + } // Set new caption text + + + const content = cues.map(cueText => cueText.trim()).join('\n'); + const changed = content !== this.elements.captions.innerHTML; + + if (changed) { + // Empty the container and create a new child element + emptyElement(this.elements.captions); + const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption)); + caption.innerHTML = content; + this.elements.captions.appendChild(caption); // Trigger event + + triggerEvent.call(this, this.media, 'cuechange'); + } + } + + }; + + // ========================================================================== + // Plyr default config + // ========================================================================== + const defaults = { + // Disable + enabled: true, + // Custom media title + title: '', + // Logging to console + debug: false, + // Auto play (if supported) + autoplay: false, + // Only allow one media playing at once (vimeo only) + autopause: true, + // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present) + // TODO: Remove iosNative fullscreen option in favour of this (logic needs work) + playsinline: true, + // Default time to skip when rewind/fast forward + seekTime: 10, + // Default volume + volume: 1, + muted: false, + // Pass a custom duration + duration: null, + // Display the media duration on load in the current time position + // If you have opted to display both duration and currentTime, this is ignored + displayDuration: true, + // Invert the current time to be a countdown + invertTime: true, + // Clicking the currentTime inverts it's value to show time left rather than elapsed + toggleInvert: true, + // Force an aspect ratio + // The format must be `'w:h'` (e.g. `'16:9'`) + ratio: null, + // Click video container to play/pause + clickToPlay: true, + // Auto hide the controls + hideControls: true, + // Reset to start when playback ended + resetOnEnd: false, + // Disable the standard context menu + disableContextMenu: true, + // Sprite (for icons) + loadSprite: true, + iconPrefix: 'plyr', + iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg', + // Blank video (used to prevent errors on source change) + blankVideo: 'https://cdn.plyr.io/static/blank.mp4', + // Quality default + quality: { + default: 576, + // The options to display in the UI, if available for the source media + options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240], + forced: false, + onChange: null + }, + // Set loops + loop: { + active: false // start: null, + // end: null, + + }, + // Speed default and options to display + speed: { + selected: 1, + // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x) + options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4] + }, + // Keyboard shortcut settings + keyboard: { + focused: true, + global: false + }, + // Display tooltips + tooltips: { + controls: false, + seek: true + }, + // Captions settings + captions: { + active: false, + language: 'auto', + // Listen to new tracks added after Plyr is initialized. + // This is needed for streaming captions, but may result in unselectable options + update: false + }, + // Fullscreen settings + fullscreen: { + enabled: true, + // Allow fullscreen? + fallback: true, + // Fallback using full viewport/window + iosNative: false // Use the native fullscreen in iOS (disables custom controls) + // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode + // Non-ancestors of the player element will be ignored + // container: null, // defaults to the player element + + }, + // Local storage + storage: { + enabled: true, + key: 'plyr' + }, + // Default controls + controls: ['play-large', // 'restart', + // 'rewind', + 'play', // 'fast-forward', + 'progress', 'current-time', // 'duration', + 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', // 'download', + 'fullscreen'], + settings: ['captions', 'quality', 'speed'], + // Localisation + i18n: { + restart: 'Restart', + rewind: 'Rewind {seektime}s', + play: 'Play', + pause: 'Pause', + fastForward: 'Forward {seektime}s', + seek: 'Seek', + seekLabel: '{currentTime} of {duration}', + played: 'Played', + buffered: 'Buffered', + currentTime: 'Current time', + duration: 'Duration', + volume: 'Volume', + mute: 'Mute', + unmute: 'Unmute', + enableCaptions: 'Enable captions', + disableCaptions: 'Disable captions', + download: 'Download', + enterFullscreen: 'Enter fullscreen', + exitFullscreen: 'Exit fullscreen', + frameTitle: 'Player for {title}', + captions: 'Captions', + settings: 'Settings', + pip: 'PIP', + menuBack: 'Go back to previous menu', + speed: 'Speed', + normal: 'Normal', + quality: 'Quality', + loop: 'Loop', + start: 'Start', + end: 'End', + all: 'All', + reset: 'Reset', + disabled: 'Disabled', + enabled: 'Enabled', + advertisement: 'Ad', + qualityBadge: { + 2160: '4K', + 1440: 'HD', + 1080: 'HD', + 720: 'HD', + 576: 'SD', + 480: 'SD' + } + }, + // URLs + urls: { + download: null, + vimeo: { + sdk: 'https://player.vimeo.com/api/player.js', + iframe: 'https://player.vimeo.com/video/{0}?{1}', + api: 'https://vimeo.com/api/oembed.json?url={0}' + }, + youtube: { + sdk: 'https://www.youtube.com/iframe_api', + api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}' + }, + googleIMA: { + sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js' + } + }, + // Custom control listeners + listeners: { + seek: null, + play: null, + pause: null, + restart: null, + rewind: null, + fastForward: null, + mute: null, + volume: null, + captions: null, + download: null, + fullscreen: null, + pip: null, + airplay: null, + speed: null, + quality: null, + loop: null, + language: null + }, + // Events to watch and bubble + events: [// Events to watch on HTML5 media elements and bubble + // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events + 'ended', 'progress', 'stalled', 'playing', 'waiting', 'canplay', 'canplaythrough', 'loadstart', 'loadeddata', 'loadedmetadata', 'timeupdate', 'volumechange', 'play', 'pause', 'error', 'seeking', 'seeked', 'emptied', 'ratechange', 'cuechange', // Custom events + 'download', 'enterfullscreen', 'exitfullscreen', 'captionsenabled', 'captionsdisabled', 'languagechange', 'controlshidden', 'controlsshown', 'ready', // YouTube + 'statechange', // Quality + 'qualitychange', // Ads + 'adsloaded', 'adscontentpause', 'adscontentresume', 'adstarted', 'adsmidpoint', 'adscomplete', 'adsallcomplete', 'adsimpression', 'adsclick'], + // Selectors + // Change these to match your template if using custom HTML + selectors: { + editable: 'input, textarea, select, [contenteditable]', + container: '.plyr', + controls: { + container: null, + wrapper: '.plyr__controls' + }, + labels: '[data-plyr]', + buttons: { + play: '[data-plyr="play"]', + pause: '[data-plyr="pause"]', + restart: '[data-plyr="restart"]', + rewind: '[data-plyr="rewind"]', + fastForward: '[data-plyr="fast-forward"]', + mute: '[data-plyr="mute"]', + captions: '[data-plyr="captions"]', + download: '[data-plyr="download"]', + fullscreen: '[data-plyr="fullscreen"]', + pip: '[data-plyr="pip"]', + airplay: '[data-plyr="airplay"]', + settings: '[data-plyr="settings"]', + loop: '[data-plyr="loop"]' + }, + inputs: { + seek: '[data-plyr="seek"]', + volume: '[data-plyr="volume"]', + speed: '[data-plyr="speed"]', + language: '[data-plyr="language"]', + quality: '[data-plyr="quality"]' + }, + display: { + currentTime: '.plyr__time--current', + duration: '.plyr__time--duration', + buffer: '.plyr__progress__buffer', + loop: '.plyr__progress__loop', + // Used later + volume: '.plyr__volume--display' + }, + progress: '.plyr__progress', + captions: '.plyr__captions', + caption: '.plyr__caption' + }, + // Class hooks added to the player in different states + classNames: { + type: 'plyr--{0}', + provider: 'plyr--{0}', + video: 'plyr__video-wrapper', + embed: 'plyr__video-embed', + videoFixedRatio: 'plyr__video-wrapper--fixed-ratio', + embedContainer: 'plyr__video-embed__container', + poster: 'plyr__poster', + posterEnabled: 'plyr__poster-enabled', + ads: 'plyr__ads', + control: 'plyr__control', + controlPressed: 'plyr__control--pressed', + playing: 'plyr--playing', + paused: 'plyr--paused', + stopped: 'plyr--stopped', + loading: 'plyr--loading', + hover: 'plyr--hover', + tooltip: 'plyr__tooltip', + cues: 'plyr__cues', + hidden: 'plyr__sr-only', + hideControls: 'plyr--hide-controls', + isIos: 'plyr--is-ios', + isTouch: 'plyr--is-touch', + uiSupported: 'plyr--full-ui', + noTransition: 'plyr--no-transition', + display: { + time: 'plyr__time' + }, + menu: { + value: 'plyr__menu__value', + badge: 'plyr__badge', + open: 'plyr--menu-open' + }, + captions: { + enabled: 'plyr--captions-enabled', + active: 'plyr--captions-active' + }, + fullscreen: { + enabled: 'plyr--fullscreen-enabled', + fallback: 'plyr--fullscreen-fallback' + }, + pip: { + supported: 'plyr--pip-supported', + active: 'plyr--pip-active' + }, + airplay: { + supported: 'plyr--airplay-supported', + 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 + attributes: { + embed: { + provider: 'data-plyr-provider', + id: 'data-plyr-embed-id', + hash: 'data-plyr-embed-hash' + } + }, + // Advertisements plugin + // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio + 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, + // Custom settings from Plyr + customControls: true, + referrerPolicy: null, + // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy + // Whether the owner of the video has a Pro or Business account + // (which allows us to properly hide controls without CSS hacks, etc) + premium: false + }, + // YouTube plugin + youtube: { + 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) + // Custom settings from Plyr + customControls: true, + noCookie: false // Whether to use an alternative version of YouTube without cookies + + } + }; + + // ========================================================================== + // Plyr states + // ========================================================================== + const pip = { + active: 'picture-in-picture', + inactive: 'inline' + }; + + // ========================================================================== + // Plyr supported types and providers + // ========================================================================== + const providers = { + html5: 'html5', + youtube: 'youtube', + vimeo: 'vimeo' + }; + const types = { + audio: 'audio', + video: 'video' + }; + /** + * Get provider by URL + * @param {String} url + */ + + function getProviderByUrl(url) { + // YouTube + if (/^(https?:\/\/)?(www\.)?(youtube\.com|youtube-nocookie\.com|youtu\.?be)\/.+$/.test(url)) { + return providers.youtube; + } // Vimeo + + + if (/^https?:\/\/player.vimeo.com\/video\/\d{0,9}(?=\b|\/)/.test(url)) { + return providers.vimeo; + } + + return null; + } + + // ========================================================================== + // Console wrapper + // ========================================================================== + const noop = () => {}; + + class Console { + constructor(enabled = false) { + this.enabled = window.console && enabled; + + if (this.enabled) { + this.log('Debugging enabled'); + } + } + + get log() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.log, console) : noop; + } + + get warn() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop; + } + + get error() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.error, console) : noop; + } + + } + + class Fullscreen { + constructor(player) { + _defineProperty$1(this, "onChange", () => { + if (!this.enabled) { + return; + } // Update toggle button + + + const button = this.player.elements.buttons.fullscreen; + + if (is.element(button)) { + button.pressed = this.active; + } // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up + + + const target = this.target === this.player.media ? this.target : this.player.elements.container; // Trigger an event + + triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true); + }); + + _defineProperty$1(this, "toggleFallback", (toggle = false) => { + // Store or restore scroll position + if (toggle) { + this.scrollPosition = { + x: window.scrollX || 0, + y: window.scrollY || 0 + }; + } else { + window.scrollTo(this.scrollPosition.x, this.scrollPosition.y); + } // Toggle scroll + + + document.body.style.overflow = toggle ? 'hidden' : ''; // Toggle class hook + + toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle); // Force full viewport on iPhone X+ + + if (browser.isIos) { + let viewport = document.head.querySelector('meta[name="viewport"]'); + const property = 'viewport-fit=cover'; // Inject the viewport meta if required + + if (!viewport) { + viewport = document.createElement('meta'); + viewport.setAttribute('name', 'viewport'); + } // Check if the property already exists + + + const hasProperty = is.string(viewport.content) && viewport.content.includes(property); + + if (toggle) { + this.cleanupViewport = !hasProperty; + + if (!hasProperty) { + viewport.content += `,${property}`; + } + } else if (this.cleanupViewport) { + viewport.content = viewport.content.split(',').filter(part => part.trim() !== property).join(','); + } + } // Toggle button and fire events + + + this.onChange(); + }); + + _defineProperty$1(this, "trapFocus", event => { + // Bail if iOS, not active, not the tab key + if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) { + return; + } // Get the current focused element + + + const focused = document.activeElement; + const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]'); + const [first] = focusable; + const last = focusable[focusable.length - 1]; + + if (focused === last && !event.shiftKey) { + // Move focus to first element that can be tabbed if Shift isn't used + first.focus(); + event.preventDefault(); + } else if (focused === first && event.shiftKey) { + // Move focus to last element that can be tabbed if Shift is used + last.focus(); + event.preventDefault(); + } + }); + + _defineProperty$1(this, "update", () => { + if (this.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'); + } // Add styling hook to show button + + + toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled); + }); + + _defineProperty$1(this, "enter", () => { + if (!this.enabled) { + return; + } // iOS native fullscreen doesn't need the request step + + + if (browser.isIos && this.player.config.fullscreen.iosNative) { + if (this.player.isVimeo) { + this.player.embed.requestFullscreen(); + } else { + this.target.webkitEnterFullscreen(); + } + } else if (!Fullscreen.native || this.forceFallback) { + this.toggleFallback(true); + } else if (!this.prefix) { + this.target.requestFullscreen({ + navigationUI: 'hide' + }); + } else if (!is.empty(this.prefix)) { + this.target[`${this.prefix}Request${this.property}`](); + } + }); + + _defineProperty$1(this, "exit", () => { + if (!this.enabled) { + return; + } // iOS native fullscreen + + + if (browser.isIos && this.player.config.fullscreen.iosNative) { + this.target.webkitExitFullscreen(); + silencePromise(this.player.play()); + } else if (!Fullscreen.native || this.forceFallback) { + this.toggleFallback(false); + } else if (!this.prefix) { + (document.cancelFullScreen || document.exitFullscreen).call(document); + } else if (!is.empty(this.prefix)) { + const action = this.prefix === 'moz' ? 'Cancel' : 'Exit'; + document[`${this.prefix}${action}${this.property}`](); + } + }); + + _defineProperty$1(this, "toggle", () => { + if (!this.active) { + this.enter(); + } else { + this.exit(); + } + }); + + // Keep reference to parent + this.player = player; // Get prefix + + this.prefix = Fullscreen.prefix; + this.property = Fullscreen.property; // 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'; // Get the fullscreen element + // Checks container is an ancestor, defaults to null + + this.player.elements.fullscreen = player.config.fullscreen.container && closest$1(this.player.elements.container, player.config.fullscreen.container); // Register event listeners + // Handle event (incase user presses escape etc) + + on.call(this.player, document, this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`, () => { + // TODO: Filter for target?? + this.onChange(); + }); // Fullscreen toggle on double click + + on.call(this.player, this.player.elements.container, 'dblclick', event => { + // Ignore double click in controls + if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) { + return; + } + + this.player.listeners.proxy(event, this.toggle, 'fullscreen'); + }); // Tap focus when in fullscreen + + on.call(this, this.player.elements.container, 'keydown', event => this.trapFocus(event)); // Update the UI + + this.update(); // this.toggle = this.toggle.bind(this); + } // Determine if native supported + + + static get native() { + return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled); + } // If we're actually using native + + + get usingNative() { + return Fullscreen.native && !this.forceFallback; + } // Get the prefix for handlers + + + static get prefix() { + // No prefix + if (is.function(document.exitFullscreen)) { + return ''; + } // Check for fullscreen support by vendor prefix + + + let value = ''; + const prefixes = ['webkit', 'moz', 'ms']; + prefixes.some(pre => { + if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) { + value = pre; + return true; + } + + return false; + }); + return value; + } + + static get property() { + return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen'; + } // Determine if fullscreen is enabled + + + get enabled() { + return (Fullscreen.native || this.player.config.fullscreen.fallback) && this.player.config.fullscreen.enabled && this.player.supported.ui && this.player.isVideo; + } // Get active state + + + get active() { + if (!this.enabled) { + return false; + } // Fallback using classname + + + if (!Fullscreen.native || this.forceFallback) { + return hasClass(this.target, this.player.config.classNames.fullscreen.fallback); + } + + const element = !this.prefix ? this.target.getRootNode().fullscreenElement : this.target.getRootNode()[`${this.prefix}${this.property}Element`]; + return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target; + } // Get target element + + + get target() { + return browser.isIos && this.player.config.fullscreen.iosNative ? this.player.media : this.player.elements.fullscreen || this.player.elements.container; + } + + } + + // ========================================================================== + // Load image avoiding xhr/fetch CORS issues + // Server status can't be obtained this way unfortunately, so this uses "naturalWidth" to determine if the image has loaded + // By default it checks if it is at least 1px, but you can add a second argument to change this + // ========================================================================== + function loadImage(src, minWidth = 1) { + return new Promise((resolve, reject) => { + const image = new Image(); + + const handler = () => { + delete image.onload; + delete image.onerror; + (image.naturalWidth >= minWidth ? resolve : reject)(image); + }; + + Object.assign(image, { + onload: handler, + onerror: handler, + src + }); + }); + } + + // ========================================================================== + const ui = { + addStyleHook() { + toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true); + toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui); + }, + + // Toggle native HTML5 media controls + toggleNativeControls(toggle = false) { + if (toggle && this.isHTML5) { + this.media.setAttribute('controls', ''); + } else { + this.media.removeAttribute('controls'); + } + }, + + // Setup the UI + build() { + // Re-attach media element listeners + // TODO: Use event bubbling? + this.listeners.media(); // Don't setup interface if no support + + if (!this.supported.ui) { + this.debug.warn(`Basic support only for ${this.provider} ${this.type}`); // Restore native controls + + ui.toggleNativeControls.call(this, true); // Bail + + return; + } // Inject custom controls if not present + + + if (!is.element(this.elements.controls)) { + // Inject custom controls + controls.inject.call(this); // Re-attach control listeners + + this.listeners.controls(); + } // Remove native controls + + + ui.toggleNativeControls.call(this); // Setup captions for HTML5 + + if (this.isHTML5) { + captions.setup.call(this); + } // Reset volume + + + this.volume = null; // Reset mute state + + this.muted = null; // Reset loop state + + this.loop = null; // Reset quality setting + + this.quality = null; // Reset speed + + this.speed = null; // Reset volume display + + controls.updateVolume.call(this); // Reset time display + + controls.timeUpdate.call(this); // Reset duration display + + controls.durationUpdate.call(this); // Update the UI + + ui.checkPlaying.call(this); // Check for picture-in-picture support + + toggleClass(this.elements.container, this.config.classNames.pip.supported, support.pip && this.isHTML5 && this.isVideo); // Check for airplay support + + toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5); // Add iOS class + + toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos); // Add touch class + + toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch); // Ready for API calls + + this.ready = true; // Ready event at end of execution stack + + setTimeout(() => { + triggerEvent.call(this, this.media, 'ready'); + }, 0); // Set the title + + ui.setTitle.call(this); // Assure the poster image is set, if the property was added before the element was created + + if (this.poster) { + ui.setPoster.call(this, this.poster, false).catch(() => {}); + } // Manually set the duration if user has overridden it. + // The event listeners for it doesn't get called if preload is disabled (#701) + + + if (this.config.duration) { + controls.durationUpdate.call(this); + } + }, + + // Setup aria attribute for play and iframe title + setTitle() { + // Find the current text + let label = i18n.get('play', this.config); // If there's a media title set, use that for the label + + if (is.string(this.config.title) && !is.empty(this.config.title)) { + label += `, ${this.config.title}`; + } // If there's a play button, set label + + + Array.from(this.elements.buttons.play || []).forEach(button => { + button.setAttribute('aria-label', label); + }); // Set iframe title + // https://github.com/sampotts/plyr/issues/124 + + if (this.isEmbed) { + const iframe = getElement.call(this, 'iframe'); + + if (!is.element(iframe)) { + return; + } // Default to media type + + + const title = !is.empty(this.config.title) ? this.config.title : 'video'; + const format = i18n.get('frameTitle', this.config); + iframe.setAttribute('title', format.replace('{title}', title)); + } + }, + + // Toggle poster + togglePoster(enable) { + toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable); + }, + + // Set the poster image (async) + // Used internally for the poster setter, with the passive option forced to false + setPoster(poster, passive = true) { + // Don't override if call is passive + if (passive && this.poster) { + return Promise.reject(new Error('Poster already set')); + } // Set property synchronously to respect the call order + + + this.media.setAttribute('data-poster', poster); // Show the poster + + this.elements.poster.removeAttribute('hidden'); // Wait until ui is ready + + return ready.call(this) // Load image + .then(() => loadImage(poster)).catch(error => { + // Hide poster on error unless it's been set by another call + if (poster === this.poster) { + ui.togglePoster.call(this, false); + } // Rethrow + + + throw error; + }).then(() => { + // Prevent race conditions + if (poster !== this.poster) { + throw new Error('setPoster cancelled by later call to setPoster'); + } + }).then(() => { + Object.assign(this.elements.poster.style, { + backgroundImage: `url('${poster}')`, + // Reset backgroundSize as well (since it can be set to "cover" for padded thumbnails for youtube) + backgroundSize: '' + }); + ui.togglePoster.call(this, true); + return poster; + }); + }, + + // Check playing state + checkPlaying(event) { + // Class hooks + toggleClass(this.elements.container, this.config.classNames.playing, this.playing); + toggleClass(this.elements.container, this.config.classNames.paused, this.paused); + toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped); // Set state + + Array.from(this.elements.buttons.play || []).forEach(target => { + Object.assign(target, { + pressed: this.playing + }); + target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config)); + }); // Only update controls on non timeupdate events + + if (is.event(event) && event.type === 'timeupdate') { + return; + } // Toggle controls + + + ui.toggleControls.call(this); + }, + + // Check if media is loading + checkLoading(event) { + this.loading = ['stalled', 'waiting'].includes(event.type); // Clear timer + + clearTimeout(this.timers.loading); // Timer to prevent flicker when seeking + + this.timers.loading = setTimeout(() => { + // Update progress bar loading class state + toggleClass(this.elements.container, this.config.classNames.loading, this.loading); // Update controls visibility + + ui.toggleControls.call(this); + }, this.loading ? 250 : 0); + }, + + // Toggle controls based on state and `force` argument + toggleControls(force) { + const { + controls: controlsElement + } = this.elements; + + if (controlsElement && this.config.hideControls) { + // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.) + const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now(); // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide + + this.toggleControls(Boolean(force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek)); + } + }, + + // Migrate any custom properties from the media to the parent + migrateStyles() { + // Loop through values (as they are the keys when the object is spread 🤔) + Object.values({ ...this.media.style + }) // We're only fussed about Plyr specific properties + .filter(key => !is.empty(key) && is.string(key) && key.startsWith('--plyr')).forEach(key => { + // Set on the container + this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key)); // Clean up from media element + + this.media.style.removeProperty(key); + }); // Remove attribute if empty + + if (is.empty(this.media.style)) { + this.media.removeAttribute('style'); + } + } + + }; + + class Listeners { + constructor(_player) { + _defineProperty$1(this, "firstTouch", () => { + const { + player + } = this; + const { + elements + } = player; + player.touch = true; // Add touch class + + toggleClass(elements.container, player.config.classNames.isTouch, true); + }); + + _defineProperty$1(this, "setTabFocus", event => { + const { + player + } = this; + const { + elements + } = player; + clearTimeout(this.focusTimer); // Ignore any key other than tab + + if (event.type === 'keydown' && event.which !== 9) { + return; + } // Store reference to event timeStamp + + + if (event.type === 'keydown') { + this.lastKeyDown = event.timeStamp; + } // Remove current classes + + + const removeCurrent = () => { + const className = player.config.classNames.tabFocus; + const current = getElements.call(player, `.${className}`); + toggleClass(current, className, false); + }; // Determine if a key was pressed to trigger this event + + + const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20; // Ignore focus events if a key was pressed prior + + if (event.type === 'focus' && !wasKeyDown) { + return; + } // Remove all current + + + removeCurrent(); // Delay the adding of classname until the focus has changed + // This event fires before the focusin event + + if (event.type !== 'focusout') { + this.focusTimer = setTimeout(() => { + const focused = document.activeElement; // Ignore if current focus element isn't inside the player + + if (!elements.container.contains(focused)) { + return; + } + + toggleClass(document.activeElement, player.config.classNames.tabFocus, true); + }, 10); + } + }); + + _defineProperty$1(this, "global", (toggle = true) => { + const { + player + } = this; // Keyboard shortcuts + + if (player.config.keyboard.global) { + toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false); + } // Click anywhere closes menu + + + toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle); // Detect touch by events + + once.call(player, document.body, 'touchstart', this.firstTouch); // Tab focus detection + + toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true); + }); + + _defineProperty$1(this, "container", () => { + const { + player + } = this; + const { + config, + elements, + timers + } = player; // Keyboard shortcuts + + if (!config.keyboard.global && config.keyboard.focused) { + on.call(player, elements.container, 'keydown keyup', this.handleKey, false); + } // Toggle controls on mouse events and entering fullscreen + + + on.call(player, elements.container, 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen', event => { + const { + controls: controlsElement + } = elements; // Remove button states for fullscreen + + if (controlsElement && event.type === 'enterfullscreen') { + controlsElement.pressed = false; + controlsElement.hover = false; + } // Show, then hide after a timeout unless another control event occurs + + + const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type); + let delay = 0; + + if (show) { + ui.toggleControls.call(player, true); // Use longer timeout for touch devices + + delay = player.touch ? 3000 : 2000; + } // Clear timer + + + clearTimeout(timers.controls); // Set new timer to prevent flicker when seeking + + timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay); + }); // Set a gutter for Vimeo + + const setGutter = () => { + if (!player.isVimeo || player.config.vimeo.premium) { + return; + } + + const target = elements.wrapper; + const { + active + } = player.fullscreen; + const [videoWidth, videoHeight] = getAspectRatio.call(player); + const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`); // If not active, remove styles + + if (!active) { + if (useNativeAspectRatio) { + target.style.width = null; + target.style.height = null; + } else { + target.style.maxWidth = null; + target.style.margin = null; + } + + return; + } // Determine which dimension will overflow and constrain view + + + const [viewportWidth, viewportHeight] = getViewportSize(); + const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight; + + if (useNativeAspectRatio) { + target.style.width = overflow ? 'auto' : '100%'; + target.style.height = overflow ? '100%' : 'auto'; + } else { + target.style.maxWidth = overflow ? `${viewportHeight / videoHeight * videoWidth}px` : null; + target.style.margin = overflow ? '0 auto' : null; + } + }; // Handle resizing + + + const resized = () => { + clearTimeout(timers.resized); + timers.resized = setTimeout(setGutter, 50); + }; + + on.call(player, elements.container, 'enterfullscreen exitfullscreen', event => { + const { + target + } = player.fullscreen; // Ignore events not from target + + if (target !== elements.container) { + return; + } // If it's not an embed and no ratio specified + + + if (!player.isEmbed && is.empty(player.config.ratio)) { + return; + } // Set Vimeo gutter + + + setGutter(); // Watch for resizes + + const method = event.type === 'enterfullscreen' ? on : off; + method.call(player, window, 'resize', resized); + }); + }); + + _defineProperty$1(this, "media", () => { + const { + player + } = this; + const { + elements + } = player; // Time change on media + + on.call(player, player.media, 'timeupdate seeking seeked', event => controls.timeUpdate.call(player, event)); // Display duration + + on.call(player, player.media, 'durationchange loadeddata loadedmetadata', event => controls.durationUpdate.call(player, event)); // Handle the media finishing + + on.call(player, player.media, 'ended', () => { + // Show poster on end + if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) { + // Restart + player.restart(); // Call pause otherwise IE11 will start playing the video again + + player.pause(); + } + }); // Check for buffer progress + + on.call(player, player.media, 'progress playing seeking seeked', event => controls.updateProgress.call(player, event)); // Handle volume changes + + on.call(player, player.media, 'volumechange', event => controls.updateVolume.call(player, event)); // Handle play/pause + + on.call(player, player.media, 'playing play pause ended emptied timeupdate', event => ui.checkPlaying.call(player, event)); // Loading state + + on.call(player, player.media, 'waiting canplay seeked playing', event => ui.checkLoading.call(player, event)); // Click video + + if (player.supported.ui && player.config.clickToPlay && !player.isAudio) { + // Re-fetch the wrapper + const wrapper = getElement.call(player, `.${player.config.classNames.video}`); // Bail if there's no wrapper (this should never happen) + + if (!is.element(wrapper)) { + return; + } // On click play, pause or restart + + + on.call(player, elements.container, 'click', event => { + const targets = [elements.container, wrapper]; // Ignore if click if not container or in video wrapper + + if (!targets.includes(event.target) && !wrapper.contains(event.target)) { + return; + } // Touch devices will just show controls (if hidden) + + + if (player.touch && player.config.hideControls) { + return; + } + + if (player.ended) { + this.proxy(event, player.restart, 'restart'); + this.proxy(event, () => { + silencePromise(player.play()); + }, 'play'); + } else { + this.proxy(event, () => { + silencePromise(player.togglePlay()); + }, 'play'); + } + }); + } // Disable right click + + + if (player.supported.ui && player.config.disableContextMenu) { + on.call(player, elements.wrapper, 'contextmenu', event => { + event.preventDefault(); + }, false); + } // Volume change + + + on.call(player, player.media, 'volumechange', () => { + // Save to storage + player.storage.set({ + volume: player.volume, + muted: player.muted + }); + }); // Speed change + + on.call(player, player.media, 'ratechange', () => { + // Update UI + controls.updateSetting.call(player, 'speed'); // Save to storage + + player.storage.set({ + speed: player.speed + }); + }); // Quality change + + on.call(player, player.media, 'qualitychange', event => { + // Update UI + controls.updateSetting.call(player, 'quality', null, event.detail.quality); + }); // Update download link when ready and if quality changes + + on.call(player, player.media, 'ready qualitychange', () => { + controls.setDownloadUrl.call(player); + }); // Proxy events to container + // Bubble up key events for Edge + + const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' '); + on.call(player, player.media, proxyEvents, event => { + let { + detail = {} + } = event; // Get error details from media + + if (event.type === 'error') { + detail = player.media.error; + } + + triggerEvent.call(player, elements.container, event.type, true, detail); + }); + }); + + _defineProperty$1(this, "proxy", (event, defaultHandler, customHandlerKey) => { + const { + player + } = this; + const customHandler = player.config.listeners[customHandlerKey]; + const hasCustomHandler = is.function(customHandler); + let returned = true; // Execute custom handler + + if (hasCustomHandler) { + returned = customHandler.call(player, event); + } // Only call default handler if not prevented in custom handler + + + if (returned !== false && is.function(defaultHandler)) { + defaultHandler.call(player, event); + } + }); + + _defineProperty$1(this, "bind", (element, type, defaultHandler, customHandlerKey, passive = true) => { + const { + player + } = this; + const customHandler = player.config.listeners[customHandlerKey]; + const hasCustomHandler = is.function(customHandler); + on.call(player, element, type, event => this.proxy(event, defaultHandler, customHandlerKey), passive && !hasCustomHandler); + }); + + _defineProperty$1(this, "controls", () => { + const { + player + } = this; + const { + elements + } = player; // IE doesn't support input event, so we fallback to change + + const inputEvent = browser.isIE ? 'change' : 'input'; // Play/pause toggle + + if (elements.buttons.play) { + Array.from(elements.buttons.play).forEach(button => { + this.bind(button, 'click', () => { + silencePromise(player.togglePlay()); + }, 'play'); + }); + } // Pause + + + this.bind(elements.buttons.restart, 'click', player.restart, 'restart'); // Rewind + + this.bind(elements.buttons.rewind, 'click', () => { + // Record seek time so we can prevent hiding controls for a few seconds after rewind + player.lastSeekTime = Date.now(); + player.rewind(); + }, 'rewind'); // Rewind + + this.bind(elements.buttons.fastForward, 'click', () => { + // Record seek time so we can prevent hiding controls for a few seconds after fast forward + player.lastSeekTime = Date.now(); + player.forward(); + }, 'fastForward'); // Mute toggle + + this.bind(elements.buttons.mute, 'click', () => { + player.muted = !player.muted; + }, 'mute'); // Captions toggle + + this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions()); // Download + + this.bind(elements.buttons.download, 'click', () => { + triggerEvent.call(player, player.media, 'download'); + }, 'download'); // Fullscreen toggle + + this.bind(elements.buttons.fullscreen, 'click', () => { + player.fullscreen.toggle(); + }, 'fullscreen'); // Picture-in-Picture + + this.bind(elements.buttons.pip, 'click', () => { + player.pip = 'toggle'; + }, 'pip'); // Airplay + + this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay'); // Settings menu - click toggle + + this.bind(elements.buttons.settings, 'click', event => { + // Prevent the document click listener closing the menu + event.stopPropagation(); + event.preventDefault(); + controls.toggleMenu.call(player, event); + }, null, false); // Can't be passive as we're preventing default + // Settings menu - keyboard toggle + // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus + // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143 + + this.bind(elements.buttons.settings, 'keyup', event => { + const code = event.which; // We only care about space and return + + if (![13, 32].includes(code)) { + return; + } // Because return triggers a click anyway, all we need to do is set focus + + + if (code === 13) { + controls.focusFirstMenuItem.call(player, null, true); + return; + } // Prevent scroll + + + event.preventDefault(); // Prevent playing video (Firefox) + + event.stopPropagation(); // Toggle menu + + controls.toggleMenu.call(player, event); + }, null, false // Can't be passive as we're preventing default + ); // Escape closes menu + + this.bind(elements.settings.menu, 'keydown', event => { + if (event.which === 27) { + controls.toggleMenu.call(player, event); + } + }); // Set range input alternative "value", which matches the tooltip time (#954) + + this.bind(elements.inputs.seek, 'mousedown mousemove', event => { + const rect = elements.progress.getBoundingClientRect(); + const percent = 100 / rect.width * (event.pageX - rect.left); + event.currentTarget.setAttribute('seek-value', percent); + }); // Pause while seeking + + this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', event => { + const seek = event.currentTarget; + const code = event.keyCode ? event.keyCode : event.which; + const attribute = 'play-on-seeked'; + + if (is.keyboardEvent(event) && code !== 39 && code !== 37) { + return; + } // Record seek time so we can prevent hiding controls for a few seconds after seek + + + player.lastSeekTime = Date.now(); // Was playing before? + + const play = seek.hasAttribute(attribute); // Done seeking + + const done = ['mouseup', 'touchend', 'keyup'].includes(event.type); // If we're done seeking and it was playing, resume playback + + if (play && done) { + seek.removeAttribute(attribute); + silencePromise(player.play()); + } else if (!done && player.playing) { + seek.setAttribute(attribute, ''); + player.pause(); + } + }); // Fix range inputs on iOS + // Super weird iOS bug where after you interact with an <input type="range">, + // it takes over further interactions on the page. This is a hack + + if (browser.isIos) { + const inputs = getElements.call(player, 'input[type="range"]'); + Array.from(inputs).forEach(input => this.bind(input, inputEvent, event => repaint(event.target))); + } // Seek + + + this.bind(elements.inputs.seek, inputEvent, event => { + const seek = event.currentTarget; // If it exists, use seek-value instead of "value" for consistency with tooltip time (#954) + + let seekTo = seek.getAttribute('seek-value'); + + if (is.empty(seekTo)) { + seekTo = seek.value; + } + + seek.removeAttribute('seek-value'); + player.currentTime = seekTo / seek.max * player.duration; + }, 'seek'); // Seek tooltip + + this.bind(elements.progress, 'mouseenter mouseleave mousemove', event => 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 touchend 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 => { + this.bind(element, 'input', event => controls.updateRangeFill.call(player, event.target)); + }); + } // Current time invert + // Only if one time element is used for both currentTime and duration + + + if (player.config.toggleInvert && !is.element(elements.display.duration)) { + this.bind(elements.display.currentTime, 'click', () => { + // Do nothing if we're at the start + if (player.currentTime === 0) { + return; + } + + player.config.invertTime = !player.config.invertTime; + controls.timeUpdate.call(player); + }); + } // Volume + + + this.bind(elements.inputs.volume, inputEvent, event => { + player.volume = event.target.value; + }, 'volume'); // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting) + + this.bind(elements.controls, 'mouseenter mouseleave', event => { + elements.controls.hover = !player.touch && event.type === 'mouseenter'; + }); // Also update controls.hover state for any non-player children of fullscreen element (as above) + + if (elements.fullscreen) { + Array.from(elements.fullscreen.children).filter(c => !c.contains(elements.container)).forEach(child => { + this.bind(child, 'mouseenter mouseleave', event => { + if (elements.controls) { + elements.controls.hover = !player.touch && event.type === 'mouseenter'; + } + }); + }); + } // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting) + + + this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', event => { + elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type); + }); // Show controls when they receive focus (e.g., when using keyboard tab key) + + this.bind(elements.controls, 'focusin', () => { + const { + config, + timers + } = player; // Skip transition to prevent focus from scrolling the parent element + + toggleClass(elements.controls, config.classNames.noTransition, true); // Toggle + + ui.toggleControls.call(player, true); // Restore transition + + setTimeout(() => { + toggleClass(elements.controls, config.classNames.noTransition, false); + }, 0); // Delay a little more for mouse users + + const delay = this.touch ? 3000 : 4000; // Clear timer + + clearTimeout(timers.controls); // Hide again after delay + + timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay); + }); // Mouse wheel for volume + + this.bind(elements.inputs.volume, 'wheel', event => { + // Detect "natural" scroll - suppored on OS X Safari only + // Other browsers on OS X will be inverted until support improves + const inverted = event.webkitDirectionInvertedFromDevice; // Get delta from event. Invert if `inverted` is true + + const [x, y] = [event.deltaX, -event.deltaY].map(value => inverted ? -value : value); // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta) + + const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y); // Change the volume by 2% + + player.increaseVolume(direction / 50); // Don't break page scrolling at max and min + + const { + volume + } = player.media; + + if (direction === 1 && volume < 1 || direction === -1 && volume > 0) { + event.preventDefault(); + } + }, 'volume', false); + }); + + this.player = _player; + this.lastKey = null; + this.focusTimer = null; + this.lastKeyDown = null; + this.handleKey = this.handleKey.bind(this); + this.toggleMenu = this.toggleMenu.bind(this); + this.setTabFocus = this.setTabFocus.bind(this); + this.firstTouch = this.firstTouch.bind(this); + } // Handle key presses + + + handleKey(event) { + const { + player + } = this; + const { + elements + } = player; + const code = event.keyCode ? event.keyCode : event.which; + const pressed = event.type === 'keydown'; + const repeat = pressed && code === this.lastKey; // Bail if a modifier key is set + + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { + return; + } // If the event is bubbled from the media element + // Firefox doesn't get the keycode for whatever reason + + + if (!is.number(code)) { + return; + } // Seek by the number keys + + + const seekByKey = () => { + // Divide the max duration into 10th's and times by the number value + player.currentTime = player.duration / 10 * (code - 48); + }; // Handle the key on keydown + // Reset on keyup + + + if (pressed) { + // Check focused element + // and if the focused element is not editable (e.g. text input) + // and any that accept key input http://webaim.org/techniques/keyboard/ + const focused = document.activeElement; + + if (is.element(focused)) { + const { + editable + } = player.config.selectors; + const { + seek + } = elements.inputs; + + if (focused !== seek && matches(focused, editable)) { + return; + } + + if (event.which === 32 && matches(focused, 'button, [role^="menuitem"]')) { + return; + } + } // Which keycodes should we prevent default + + + const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79]; // If the code is found prevent default (e.g. prevent scrolling for arrows) + + if (preventDefault.includes(code)) { + event.preventDefault(); + event.stopPropagation(); + } + + switch (code) { + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + // 0-9 + if (!repeat) { + seekByKey(); + } + + break; + + case 32: + case 75: + // Space and K key + if (!repeat) { + silencePromise(player.togglePlay()); + } + + break; + + case 38: + // Arrow up + player.increaseVolume(0.1); + break; + + case 40: + // Arrow down + player.decreaseVolume(0.1); + break; + + case 77: + // M key + if (!repeat) { + player.muted = !player.muted; + } + + break; + + case 39: + // Arrow forward + player.forward(); + break; + + case 37: + // Arrow back + player.rewind(); + break; + + case 70: + // F key + player.fullscreen.toggle(); + break; + + case 67: + // C key + if (!repeat) { + player.toggleCaptions(); + } + + break; + + case 76: + // L key + player.loop = !player.loop; + break; + } // Escape is handle natively when in full screen + // So we only need to worry about non native + + + if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) { + player.fullscreen.toggle(); + } // Store last code for next cycle + + + this.lastKey = code; + } else { + this.lastKey = null; + } + } // Toggle menu + + + toggleMenu(event) { + controls.toggleMenu.call(this.player, event); + } // Device is touch enabled + + + } + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var loadjs_umd = createCommonjsModule(function (module, exports) { + (function (root, factory) { + { + module.exports = factory(); + } + })(commonjsGlobal, function () { + /** + * Global dependencies. + * @global {Object} document - DOM + */ + var devnull = function () {}, + bundleIdCache = {}, + bundleResultCache = {}, + bundleCallbackQueue = {}; + /** + * Subscribe to bundle load event. + * @param {string[]} bundleIds - Bundle ids + * @param {Function} callbackFn - The callback function + */ + + + function subscribe(bundleIds, callbackFn) { + // listify + bundleIds = bundleIds.push ? bundleIds : [bundleIds]; + var depsNotFound = [], + i = bundleIds.length, + numWaiting = i, + fn, + bundleId, + r, + q; // define callback function + + fn = function (bundleId, pathsNotFound) { + if (pathsNotFound.length) depsNotFound.push(bundleId); + numWaiting--; + if (!numWaiting) callbackFn(depsNotFound); + }; // register callback + + + while (i--) { + bundleId = bundleIds[i]; // execute callback if in result cache + + r = bundleResultCache[bundleId]; + + if (r) { + fn(bundleId, r); + continue; + } // add to callback queue + + + q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || []; + q.push(fn); + } + } + /** + * Publish bundle load event. + * @param {string} bundleId - Bundle id + * @param {string[]} pathsNotFound - List of files not found + */ + + + function publish(bundleId, pathsNotFound) { + // exit if id isn't defined + if (!bundleId) return; + var q = bundleCallbackQueue[bundleId]; // cache result + + bundleResultCache[bundleId] = pathsNotFound; // exit if queue is empty + + if (!q) return; // empty callback queue + + while (q.length) { + q[0](bundleId, pathsNotFound); + q.splice(0, 1); + } + } + /** + * Execute callbacks. + * @param {Object or Function} args - The callback args + * @param {string[]} depsNotFound - List of dependencies not found + */ + + + function executeCallbacks(args, depsNotFound) { + // accept function as argument + if (args.call) args = { + success: args + }; // success and error callbacks + + if (depsNotFound.length) (args.error || devnull)(depsNotFound);else (args.success || devnull)(args); + } + /** + * Load individual file. + * @param {string} path - The file path + * @param {Function} callbackFn - The callback function + */ + + + function loadFile(path, callbackFn, args, numTries) { + var doc = document, + async = args.async, + maxTries = (args.numRetries || 0) + 1, + beforeCallbackFn = args.before || devnull, + pathname = path.replace(/[\?|#].*$/, ''), + pathStripped = path.replace(/^(css|img)!/, ''), + isLegacyIECss, + e; + numTries = numTries || 0; + + if (/(^css!|\.css$)/.test(pathname)) { + // css + e = doc.createElement('link'); + e.rel = 'stylesheet'; + e.href = pathStripped; // tag IE9+ + + isLegacyIECss = 'hideFocus' in e; // use preload in IE Edge (to detect load errors) + + if (isLegacyIECss && e.relList) { + isLegacyIECss = 0; + e.rel = 'preload'; + e.as = 'style'; + } + } else if (/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(pathname)) { + // image + e = doc.createElement('img'); + e.src = pathStripped; + } else { + // javascript + e = doc.createElement('script'); + e.src = path; + e.async = async === undefined ? true : async; + } + + e.onload = e.onerror = e.onbeforeload = function (ev) { + var result = ev.type[0]; // treat empty stylesheets as failures to get around lack of onerror + // support in IE9-11 + + if (isLegacyIECss) { + try { + if (!e.sheet.cssText.length) result = 'e'; + } catch (x) { + // sheets objects created from load errors don't allow access to + // `cssText` (unless error is Code:18 SecurityError) + if (x.code != 18) result = 'e'; + } + } // handle retries in case of load failure + + + if (result == 'e') { + // increment counter + numTries += 1; // exit function and try again + + if (numTries < maxTries) { + return loadFile(path, callbackFn, args, numTries); + } + } else if (e.rel == 'preload' && e.as == 'style') { + // activate preloaded stylesheets + return e.rel = 'stylesheet'; // jshint ignore:line + } // execute callback + + + callbackFn(path, result, ev.defaultPrevented); + }; // add to document (unless callback returns `false`) + + + if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e); + } + /** + * Load multiple files. + * @param {string[]} paths - The file paths + * @param {Function} callbackFn - The callback function + */ + + + function loadFiles(paths, callbackFn, args) { + // listify paths + paths = paths.push ? paths : [paths]; + var numWaiting = paths.length, + x = numWaiting, + pathsNotFound = [], + fn, + i; // define callback function + + fn = function (path, result, defaultPrevented) { + // handle error + if (result == 'e') pathsNotFound.push(path); // handle beforeload event. If defaultPrevented then that means the load + // will be blocked (ex. Ghostery/ABP on Safari) + + if (result == 'b') { + if (defaultPrevented) pathsNotFound.push(path);else return; + } + + numWaiting--; + if (!numWaiting) callbackFn(pathsNotFound); + }; // load scripts + + + for (i = 0; i < x; i++) loadFile(paths[i], fn, args); + } + /** + * Initiate script load and register bundle. + * @param {(string|string[])} paths - The file paths + * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success + * callback or (3) object literal with success/error arguments, numRetries, + * etc. + * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object + * literal with success/error arguments, numRetries, etc. + */ + + + function loadjs(paths, arg1, arg2) { + var bundleId, args; // bundleId (if string) + + if (arg1 && arg1.trim) bundleId = arg1; // args (default is {}) + + args = (bundleId ? arg2 : arg1) || {}; // throw error if bundle is already defined + + if (bundleId) { + if (bundleId in bundleIdCache) { + throw "LoadJS"; + } else { + bundleIdCache[bundleId] = true; + } + } + + function loadFn(resolve, reject) { + loadFiles(paths, function (pathsNotFound) { + // execute callbacks + executeCallbacks(args, pathsNotFound); // resolve Promise + + if (resolve) { + executeCallbacks({ + success: resolve, + error: reject + }, pathsNotFound); + } // publish bundle load event + + + publish(bundleId, pathsNotFound); + }, args); + } + + if (args.returnPromise) return new Promise(loadFn);else loadFn(); + } + /** + * Execute callbacks when dependencies have been satisfied. + * @param {(string|string[])} deps - List of bundle ids + * @param {Object} args - success/error arguments + */ + + + loadjs.ready = function ready(deps, args) { + // subscribe to bundle load event + subscribe(deps, function (depsNotFound) { + // execute callbacks + executeCallbacks(args, depsNotFound); + }); + return loadjs; + }; + /** + * Manually satisfy bundle dependencies. + * @param {string} bundleId - The bundle id + */ + + + loadjs.done = function done(bundleId) { + publish(bundleId, []); + }; + /** + * Reset loadjs dependencies statuses + */ + + + loadjs.reset = function reset() { + bundleIdCache = {}; + bundleResultCache = {}; + bundleCallbackQueue = {}; + }; + /** + * Determine if bundle has already been defined + * @param String} bundleId - The bundle id + */ + + + loadjs.isDefined = function isDefined(bundleId) { + return bundleId in bundleIdCache; + }; // export + + + return loadjs; + }); + }); + + // ========================================================================== + function loadScript(url) { + return new Promise((resolve, reject) => { + loadjs_umd(url, { + success: resolve, + error: reject + }); + }); + } + + // ========================================================================== + + function parseId$1(url) { + if (is.empty(url)) { + return null; + } + + if (is.number(Number(url))) { + return url; + } + + const regex = /^.*(vimeo.com\/|video\/)(\d+).*/; + return url.match(regex) ? RegExp.$2 : url; + } // Try to extract a hash for private videos from the URL + + + function parseHash(url) { + /* This regex matches a hexadecimal hash if given in any of these forms: + * - [https://player.]vimeo.com/video/{id}/{hash}[?params] + * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms] + * - [https://player.]vimeo.com/video/{id}?[params]&h={hash} + * - video/{id}/{hash} + * If matched, the hash is available in the named group `hash` + */ + const regex = /^.*(?:vimeo.com\/|video\/)(?:\d+)(?:\?.*&*h=|\/)+(?<hash>[\d,a-f]+)/; + const found = url.match(regex); + return found ? found.groups.hash : null; + } // Set playback state and trigger change (only on actual change) + + + function assurePlaybackState$1(play) { + if (play && !this.embed.hasPlayed) { + this.embed.hasPlayed = true; + } + + if (this.media.paused === play) { + this.media.paused = !play; + triggerEvent.call(this, this.media, play ? 'play' : 'pause'); + } + } + + const vimeo = { + setup() { + const player = this; // Add embed class for responsive + + toggleClass(player.elements.wrapper, player.config.classNames.embed, true); // Set speed options from config + + player.options.speed = player.config.speed.options; // Set intial ratio + + setAspectRatio.call(player); // Load the SDK if not already + + if (!is.object(window.Vimeo)) { + loadScript(player.config.urls.vimeo.sdk).then(() => { + vimeo.ready.call(player); + }).catch(error => { + player.debug.warn('Vimeo SDK (player.js) failed to load', error); + }); + } else { + vimeo.ready.call(player); + } + }, + + // API Ready + ready() { + const player = this; + const config = player.config.vimeo; + const { + premium, + referrerPolicy, + ...frameParams + } = config; // Get the source URL or ID + + let source = player.media.getAttribute('src'); + let hash = ''; // Get from <div> if needed + + if (is.empty(source)) { + source = player.media.getAttribute(player.config.attributes.embed.id); // hash can also be set as attribute on the <div> + + hash = player.media.getAttribute(player.config.attributes.embed.hash); + } else { + hash = parseHash(source); + } + + const hashParam = hash ? { + h: hash + } : {}; // If the owner has a pro or premium account then we can hide controls etc + + if (premium) { + Object.assign(frameParams, { + controls: false, + sidedock: false + }); + } // Get Vimeo params for the iframe + + + const params = buildUrlParams({ + loop: player.config.loop.active, + autoplay: player.autoplay, + muted: player.muted, + gesture: 'media', + playsinline: !this.config.fullscreen.iosNative, + // hash has to be added to iframe-URL + ...hashParam, + ...frameParams + }); + const id = parseId$1(source); // Build an iframe + + const iframe = createElement('iframe'); + const src = format(player.config.urls.vimeo.iframe, id, params); + iframe.setAttribute('src', src); + iframe.setAttribute('allowfullscreen', ''); + iframe.setAttribute('allow', ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; ')); // Set the referrer policy if required + + if (!is.empty(referrerPolicy)) { + iframe.setAttribute('referrerPolicy', referrerPolicy); + } // Inject the package + + + if (premium || !config.customControls) { + iframe.setAttribute('data-poster', player.poster); + player.media = replaceElement(iframe, player.media); + } else { + const wrapper = createElement('div', { + class: player.config.classNames.embedContainer, + 'data-poster': player.poster + }); + wrapper.appendChild(iframe); + player.media = replaceElement(wrapper, player.media); + } // Get poster image + + + if (!config.customControls) { + fetch(format(player.config.urls.vimeo.api, src)).then(response => { + if (is.empty(response) || !response.thumbnail_url) { + return; + } // Set and show poster + + + ui.setPoster.call(player, response.thumbnail_url).catch(() => {}); + }); + } // Setup instance + // https://github.com/vimeo/player.js + + + player.embed = new window.Vimeo.Player(iframe, { + autopause: player.config.autopause, + muted: player.muted + }); + player.media.paused = true; + player.media.currentTime = 0; // Disable native text track rendering + + if (player.supported.ui) { + player.embed.disableTextTrack(); + } // Create a faux HTML5 API using the Vimeo API + + + player.media.play = () => { + assurePlaybackState$1.call(player, true); + return player.embed.play(); + }; + + player.media.pause = () => { + assurePlaybackState$1.call(player, false); + return player.embed.pause(); + }; + + player.media.stop = () => { + player.pause(); + player.currentTime = 0; + }; // Seeking + + + let { + currentTime + } = player.media; + Object.defineProperty(player.media, 'currentTime', { + get() { + return currentTime; + }, + + set(time) { + // Vimeo will automatically play on seek if the video hasn't been played before + // Get current paused state and volume etc + const { + embed, + media, + paused, + volume + } = player; + const restorePause = paused && !embed.hasPlayed; // Set seeking state and trigger event + + media.seeking = true; + triggerEvent.call(player, media, 'seeking'); // If paused, mute until seek is complete + + Promise.resolve(restorePause && embed.setVolume(0)) // Seek + .then(() => embed.setCurrentTime(time)) // Restore paused + .then(() => restorePause && embed.pause()) // Restore volume + .then(() => restorePause && embed.setVolume(volume)).catch(() => {// Do nothing + }); + } + + }); // Playback speed + + let speed = player.config.speed.selected; + Object.defineProperty(player.media, 'playbackRate', { + get() { + return speed; + }, + + set(input) { + player.embed.setPlaybackRate(input).then(() => { + speed = input; + triggerEvent.call(player, player.media, 'ratechange'); + }).catch(() => { + // Cannot set Playback Rate, Video is probably not on Pro account + player.options.speed = [1]; + }); + } + + }); // Volume + + let { + volume + } = player.config; + Object.defineProperty(player.media, 'volume', { + get() { + return volume; + }, + + set(input) { + player.embed.setVolume(input).then(() => { + volume = input; + triggerEvent.call(player, player.media, 'volumechange'); + }); + } + + }); // Muted + + let { + muted + } = player.config; + Object.defineProperty(player.media, 'muted', { + get() { + return muted; + }, + + set(input) { + const toggle = is.boolean(input) ? input : false; + player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => { + muted = toggle; + triggerEvent.call(player, player.media, 'volumechange'); + }); + } + + }); // Loop + + let { + loop + } = player.config; + Object.defineProperty(player.media, 'loop', { + get() { + return loop; + }, + + set(input) { + const toggle = is.boolean(input) ? input : player.config.loop.active; + player.embed.setLoop(toggle).then(() => { + loop = toggle; + }); + } + + }); // Source + + let currentSrc; + player.embed.getVideoUrl().then(value => { + currentSrc = value; + controls.setDownloadUrl.call(player); + }).catch(error => { + this.debug.warn(error); + }); + Object.defineProperty(player.media, 'currentSrc', { + get() { + return currentSrc; + } + + }); // Ended + + Object.defineProperty(player.media, 'ended', { + get() { + return player.currentTime === player.duration; + } + + }); // Set aspect ratio based on video size + + Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(dimensions => { + const [width, height] = dimensions; + player.embed.ratio = roundAspectRatio(width, height); + setAspectRatio.call(this); + }); // Set autopause + + player.embed.setAutopause(player.config.autopause).then(state => { + player.config.autopause = state; + }); // Get title + + player.embed.getVideoTitle().then(title => { + player.config.title = title; + ui.setTitle.call(this); + }); // Get current time + + player.embed.getCurrentTime().then(value => { + currentTime = value; + triggerEvent.call(player, player.media, 'timeupdate'); + }); // Get duration + + player.embed.getDuration().then(value => { + player.media.duration = value; + triggerEvent.call(player, player.media, 'durationchange'); + }); // Get captions + + player.embed.getTextTracks().then(tracks => { + player.media.textTracks = tracks; + captions.setup.call(player); + }); + player.embed.on('cuechange', ({ + cues = [] + }) => { + const strippedCues = cues.map(cue => stripHTML(cue.text)); + captions.updateCues.call(player, strippedCues); + }); + player.embed.on('loaded', () => { + // Assure state and events are updated on autoplay + player.embed.getPaused().then(paused => { + assurePlaybackState$1.call(player, !paused); + + if (!paused) { + triggerEvent.call(player, player.media, 'playing'); + } + }); + + if (is.element(player.embed.element) && player.supported.ui) { + const frame = player.embed.element; // Fix keyboard focus issues + // https://github.com/sampotts/plyr/issues/317 + + frame.setAttribute('tabindex', -1); + } + }); + player.embed.on('bufferstart', () => { + triggerEvent.call(player, player.media, 'waiting'); + }); + player.embed.on('bufferend', () => { + triggerEvent.call(player, player.media, 'playing'); + }); + player.embed.on('play', () => { + assurePlaybackState$1.call(player, true); + triggerEvent.call(player, player.media, 'playing'); + }); + player.embed.on('pause', () => { + assurePlaybackState$1.call(player, false); + }); + player.embed.on('timeupdate', data => { + player.media.seeking = false; + currentTime = data.seconds; + triggerEvent.call(player, player.media, 'timeupdate'); + }); + player.embed.on('progress', data => { + player.media.buffered = data.percent; + triggerEvent.call(player, player.media, 'progress'); // Check all loaded + + if (parseInt(data.percent, 10) === 1) { + triggerEvent.call(player, player.media, 'canplaythrough'); + } // Get duration as if we do it before load, it gives an incorrect value + // https://github.com/sampotts/plyr/issues/891 + + + player.embed.getDuration().then(value => { + if (value !== player.media.duration) { + player.media.duration = value; + triggerEvent.call(player, player.media, 'durationchange'); + } + }); + }); + player.embed.on('seeked', () => { + player.media.seeking = false; + triggerEvent.call(player, player.media, 'seeked'); + }); + player.embed.on('ended', () => { + player.media.paused = true; + triggerEvent.call(player, player.media, 'ended'); + }); + player.embed.on('error', detail => { + player.media.error = detail; + triggerEvent.call(player, player.media, 'error'); + }); // Rebuild UI + + if (config.customControls) { + setTimeout(() => ui.build.call(player), 0); + } + } + + }; + + // ========================================================================== + + function parseId(url) { + if (is.empty(url)) { + return null; + } + + const regex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/; + return url.match(regex) ? RegExp.$2 : url; + } // Set playback state and trigger change (only on actual change) + + + function assurePlaybackState(play) { + if (play && !this.embed.hasPlayed) { + this.embed.hasPlayed = true; + } + + if (this.media.paused === play) { + this.media.paused = !play; + triggerEvent.call(this, this.media, play ? 'play' : 'pause'); + } + } + + function getHost(config) { + if (config.noCookie) { + return 'https://www.youtube-nocookie.com'; + } + + if (window.location.protocol === 'http:') { + return 'http://www.youtube.com'; + } // Use YouTube's default + + + return undefined; + } + + const youtube = { + setup() { + // Add embed class for responsive + toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Setup API + + if (is.object(window.YT) && is.function(window.YT.Player)) { + youtube.ready.call(this); + } else { + // Reference current global callback + const callback = window.onYouTubeIframeAPIReady; // Set callback to process queue + + window.onYouTubeIframeAPIReady = () => { + // Call global callback if set + if (is.function(callback)) { + callback(); + } + + youtube.ready.call(this); + }; // Load the SDK + + + loadScript(this.config.urls.youtube.sdk).catch(error => { + this.debug.warn('YouTube API failed to load', error); + }); + } + }, + + // Get the media title + getTitle(videoId) { + const url = format(this.config.urls.youtube.api, videoId); + fetch(url).then(data => { + if (is.object(data)) { + const { + title, + height, + width + } = data; // Set title + + this.config.title = title; + ui.setTitle.call(this); // Set aspect ratio + + this.embed.ratio = roundAspectRatio(width, height); + } + + setAspectRatio.call(this); + }).catch(() => { + // Set aspect ratio + setAspectRatio.call(this); + }); + }, + + // API ready + ready() { + const player = this; + const config = player.config.youtube; // Ignore already setup (race condition) + + const currentId = player.media && player.media.getAttribute('id'); + + if (!is.empty(currentId) && currentId.startsWith('youtube-')) { + return; + } // Get the source URL or ID + + + let source = player.media.getAttribute('src'); // Get from <div> if needed + + if (is.empty(source)) { + source = player.media.getAttribute(this.config.attributes.embed.id); + } // Replace the <iframe> with a <div> due to YouTube API issues + + + const videoId = parseId(source); + const id = generateId(player.provider); // Replace media element + + const container = createElement('div', { + id, + 'data-poster': config.customControls ? player.poster : undefined + }); + player.media = replaceElement(container, player.media); // Only load the poster when using custom controls + + if (config.customControls) { + const posterSrc = s => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`; // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide) + + + loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded + .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3 + .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists + .then(image => ui.setPoster.call(player, image.src)).then(src => { + // If the image is padded, use background-size "cover" instead (like youtube does too with their posters) + if (!src.includes('maxres')) { + player.elements.poster.style.backgroundSize = 'cover'; + } + }).catch(() => {}); + } // Setup instance + // https://developers.google.com/youtube/iframe_api_reference + + + player.embed = new window.YT.Player(player.media, { + videoId, + host: getHost(config), + playerVars: extend({}, { + // Autoplay + autoplay: player.config.autoplay ? 1 : 0, + // iframe interface language + hl: player.config.hl, + // Only show controls if not fully supported or opted out + controls: player.supported.ui && config.customControls ? 0 : 1, + // Disable keyboard as we handle it + disablekb: 1, + // Allow iOS inline playback + playsinline: !player.config.fullscreen.iosNative ? 1 : 0, + // 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 + if (!player.media.error) { + const code = event.data; // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError + + const message = { + 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.', + 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.', + 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.', + 101: 'The owner of the requested video does not allow it to be played in embedded players.', + 150: 'The owner of the requested video does not allow it to be played in embedded players.' + }[code] || 'An unknown error occured'; + player.media.error = { + code, + message + }; + triggerEvent.call(player, player.media, 'error'); + } + }, + + onPlaybackRateChange(event) { + // Get the instance + const instance = event.target; // Get current speed + + player.media.playbackRate = instance.getPlaybackRate(); + triggerEvent.call(player, player.media, 'ratechange'); + }, + + onReady(event) { + // Bail if onReady has already been called. See issue #1108 + if (is.function(player.media.play)) { + return; + } // Get the instance + + + const instance = event.target; // Get the title + + youtube.getTitle.call(player, videoId); // Create a faux HTML5 API using the YouTube API + + player.media.play = () => { + assurePlaybackState.call(player, true); + instance.playVideo(); + }; + + player.media.pause = () => { + assurePlaybackState.call(player, false); + instance.pauseVideo(); + }; + + player.media.stop = () => { + instance.stopVideo(); + }; + + player.media.duration = instance.getDuration(); + player.media.paused = true; // Seeking + + player.media.currentTime = 0; + Object.defineProperty(player.media, 'currentTime', { + get() { + return Number(instance.getCurrentTime()); + }, + + set(time) { + // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet). + if (player.paused && !player.embed.hasPlayed) { + player.embed.mute(); + } // Set seeking state and trigger event + + + player.media.seeking = true; + triggerEvent.call(player, player.media, 'seeking'); // Seek after events sent + + instance.seekTo(time); + } + + }); // Playback speed + + Object.defineProperty(player.media, 'playbackRate', { + get() { + return instance.getPlaybackRate(); + }, + + set(input) { + instance.setPlaybackRate(input); + } + + }); // Volume + + let { + volume + } = player.config; + Object.defineProperty(player.media, 'volume', { + get() { + return volume; + }, + + set(input) { + volume = input; + instance.setVolume(volume * 100); + triggerEvent.call(player, player.media, 'volumechange'); + } + + }); // Muted + + let { + muted + } = player.config; + Object.defineProperty(player.media, 'muted', { + get() { + return muted; + }, + + set(input) { + const toggle = is.boolean(input) ? input : muted; + muted = toggle; + instance[toggle ? 'mute' : 'unMute'](); + instance.setVolume(volume * 100); + triggerEvent.call(player, player.media, 'volumechange'); + } + + }); // Source + + Object.defineProperty(player.media, 'currentSrc', { + get() { + return instance.getVideoUrl(); + } + + }); // Ended + + Object.defineProperty(player.media, 'ended', { + get() { + return player.currentTime === player.duration; + } + + }); // Get available speeds + + const speeds = instance.getAvailablePlaybackRates(); // Filter based on config + + player.options.speed = speeds.filter(s => player.config.speed.options.includes(s)); // Set the tabindex to avoid focus entering iframe + + if (player.supported.ui && config.customControls) { + player.media.setAttribute('tabindex', -1); + } + + triggerEvent.call(player, player.media, 'timeupdate'); + triggerEvent.call(player, player.media, 'durationchange'); // Reset timer + + clearInterval(player.timers.buffering); // Setup buffering + + player.timers.buffering = setInterval(() => { + // Get loaded % from YouTube + player.media.buffered = instance.getVideoLoadedFraction(); // Trigger progress only when we actually buffer something + + if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) { + triggerEvent.call(player, player.media, 'progress'); + } // Set last buffer point + + + player.media.lastBuffered = player.media.buffered; // Bail if we're at 100% + + if (player.media.buffered === 1) { + clearInterval(player.timers.buffering); // Trigger event + + triggerEvent.call(player, player.media, 'canplaythrough'); + } + }, 200); // Rebuild UI + + if (config.customControls) { + setTimeout(() => ui.build.call(player), 50); + } + }, + + onStateChange(event) { + // Get the instance + const instance = event.target; // Reset timer + + clearInterval(player.timers.playing); + const seeked = player.media.seeking && [1, 2].includes(event.data); + + if (seeked) { + // Unset seeking and fire seeked event + player.media.seeking = false; + triggerEvent.call(player, player.media, 'seeked'); + } // Handle events + // -1 Unstarted + // 0 Ended + // 1 Playing + // 2 Paused + // 3 Buffering + // 5 Video cued + + + switch (event.data) { + case -1: + // Update scrubber + triggerEvent.call(player, player.media, 'timeupdate'); // Get loaded % from YouTube + + player.media.buffered = instance.getVideoLoadedFraction(); + triggerEvent.call(player, player.media, 'progress'); + break; + + case 0: + assurePlaybackState.call(player, false); // YouTube doesn't support loop for a single video, so mimick it. + + if (player.media.loop) { + // YouTube needs a call to `stopVideo` before playing again + instance.stopVideo(); + instance.playVideo(); + } else { + triggerEvent.call(player, player.media, 'ended'); + } + + break; + + case 1: + // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet) + if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) { + player.media.pause(); + } else { + assurePlaybackState.call(player, true); + triggerEvent.call(player, player.media, 'playing'); // Poll to get playback progress + + player.timers.playing = setInterval(() => { + triggerEvent.call(player, player.media, 'timeupdate'); + }, 50); // Check duration again due to YouTube bug + // https://github.com/sampotts/plyr/issues/374 + // https://code.google.com/p/gdata-issues/issues/detail?id=8690 + + if (player.media.duration !== instance.getDuration()) { + player.media.duration = instance.getDuration(); + triggerEvent.call(player, player.media, 'durationchange'); + } + } + + break; + + case 2: + // Restore audio (YouTube starts playing on seek if the video hasn't been played yet) + if (!player.muted) { + player.embed.unMute(); + } + + assurePlaybackState.call(player, false); + break; + + case 3: + // Trigger waiting event to add loading classes to container as the video buffers. + triggerEvent.call(player, player.media, 'waiting'); + break; + } + + triggerEvent.call(player, player.elements.container, 'statechange', false, { + code: event.data + }); + } + + } + }); + } + + }; + + // ========================================================================== + const media = { + // Setup media + setup() { + // If there's no media, bail + if (!this.media) { + this.debug.warn('No media element found!'); + return; + } // Add type class + + + toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true); // Add provider class + + toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true); // Add video class for embeds + // This will require changes if audio embeds are added + + if (this.isEmbed) { + toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true); + } // Inject the player wrapper + + + if (this.isVideo) { + // Create the wrapper div + this.elements.wrapper = createElement('div', { + class: this.config.classNames.video + }); // Wrap the video in a container + + wrap(this.media, this.elements.wrapper); // Poster image container + + this.elements.poster = createElement('div', { + class: this.config.classNames.poster + }); + this.elements.wrapper.appendChild(this.elements.poster); + } + + if (this.isHTML5) { + html5.setup.call(this); + } else if (this.isYouTube) { + youtube.setup.call(this); + } else if (this.isVimeo) { + vimeo.setup.call(this); + } + } + + }; + + const destroy = instance => { + // Destroy our adsManager + if (instance.manager) { + instance.manager.destroy(); + } // Destroy our adsManager + + + if (instance.elements.displayContainer) { + instance.elements.displayContainer.destroy(); + } + + instance.elements.container.remove(); + }; + + class Ads { + /** + * Ads constructor. + * @param {Object} player + * @return {Ads} + */ + constructor(player) { + _defineProperty$1(this, "load", () => { + if (!this.enabled) { + return; + } // Check if the Google IMA3 SDK is loaded or load it ourselves + + + if (!is.object(window.google) || !is.object(window.google.ima)) { + loadScript(this.player.config.urls.googleIMA.sdk).then(() => { + this.ready(); + }).catch(() => { + // Script failed to load or is blocked + this.trigger('error', new Error('Google IMA SDK failed to load')); + }); + } else { + this.ready(); + } + }); + + _defineProperty$1(this, "ready", () => { + // Double check we're enabled + if (!this.enabled) { + destroy(this); + } // Start ticking our safety timer. If the whole advertisement + // thing doesn't resolve within our set time; we bail + + + this.startSafetyTimer(12000, 'ready()'); // Clear the safety timer + + this.managerPromise.then(() => { + this.clearSafetyTimer('onAdsManagerLoaded()'); + }); // Set listeners on the Plyr instance + + this.listeners(); // Setup the IMA SDK + + this.setupIMA(); + }); + + _defineProperty$1(this, "setupIMA", () => { + // Create the container for our advertisements + this.elements.container = createElement('div', { + class: this.player.config.classNames.ads + }); + this.player.elements.container.appendChild(this.elements.container); // So we can run VPAID2 + + google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED); // Set language + + google.ima.settings.setLocale(this.player.config.ads.language); // 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); // Create ads loader + + this.loader = new google.ima.AdsLoader(this.elements.displayContainer); // Listen and respond to ads loaded and error events + + this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false); + this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false); // Request video ads to be pre-loaded + + this.requestAds(); + }); + + _defineProperty$1(this, "requestAds", () => { + const { + container + } = this.player.elements; + + try { + // Request video ads + const request = new google.ima.AdsRequest(); + request.adTagUrl = this.tagUrl; // Specify the linear and nonlinear slot sizes. This helps the SDK + // to select the correct creative if multiple are returned + + request.linearAdSlotWidth = container.offsetWidth; + request.linearAdSlotHeight = container.offsetHeight; + request.nonLinearAdSlotWidth = container.offsetWidth; + request.nonLinearAdSlotHeight = container.offsetHeight; // We only overlay ads as we only support video. + + request.forceNonLinearFullSlot = false; // Mute based on current state + + request.setAdWillPlayMuted(!this.player.muted); + this.loader.requestAds(request); + } catch (error) { + this.onAdError(error); + } + }); + + _defineProperty$1(this, "pollCountdown", (start = false) => { + if (!start) { + clearInterval(this.countdownTimer); + this.elements.container.removeAttribute('data-badge-text'); + return; + } + + const update = () => { + const time = formatTime(Math.max(this.manager.getRemainingTime(), 0)); + const label = `${i18n.get('advertisement', this.player.config)} - ${time}`; + this.elements.container.setAttribute('data-badge-text', label); + }; + + this.countdownTimer = setInterval(update, 100); + }); + + _defineProperty$1(this, "onAdsManagerLoaded", event => { + // Load could occur after a source change (race condition) + if (!this.enabled) { + return; + } // Get the ads manager + + + const settings = new google.ima.AdsRenderingSettings(); // Tell the SDK to save and restore content video state on our behalf + + settings.restoreCustomPlaybackStateOnAdBreakComplete = true; + settings.enablePreloading = true; // The SDK is polling currentTime on the contentPlayback. And needs a duration + // so it can determine when to start the mid- and post-roll + + this.manager = event.getAdsManager(this.player, settings); // Get the cue points for any mid-rolls by filtering out the pre- and post-roll + + this.cuePoints = this.manager.getCuePoints(); // Add listeners to the required events + // Advertisement error events + + this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error)); // Advertisement regular events + + Object.keys(google.ima.AdEvent.Type).forEach(type => { + this.manager.addEventListener(google.ima.AdEvent.Type[type], e => this.onAdEvent(e)); + }); // Resolve our adsManager + + this.trigger('loaded'); + }); + + _defineProperty$1(this, "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); + } + } + }); + } + }); + + _defineProperty$1(this, "onAdEvent", event => { + const { + container + } = this.player.elements; // 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 => { + triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`); + }; // Bubble the event + + + dispatchEvent(event.type); + + switch (event.type) { + case google.ima.AdEvent.Type.LOADED: + // This is the first event sent for an ad - it is possible to determine whether the + // ad is a video ad or an overlay + this.trigger('loaded'); // Start countdown + + this.pollCountdown(true); + + if (!ad.isLinear()) { + // Position AdDisplayContainer correctly for overlay + ad.width = container.offsetWidth; + ad.height = container.offsetHeight; + } // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex()); + // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset()); + + + break; + + case google.ima.AdEvent.Type.STARTED: + // Set volume to match player + this.manager.setVolume(this.player.volume); + break; + + case google.ima.AdEvent.Type.ALL_ADS_COMPLETED: + // All ads for the current videos are done. We can now request new advertisements + // in case the video is re-played + // TODO: Example for what happens when a next video in a playlist would be loaded. + // So here we load a new video when all ads are done. + // Then we load new ads within a new adsManager. When the video + // Is started - after - the ads are loaded, then we get ads. + // You can also easily test cancelling and reloading by running + // player.ads.cancel() and player.ads.play from the console I guess. + // this.player.source = { + // type: 'video', + // title: 'View From A Blue Moon', + // sources: [{ + // src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type: + // 'video/mp4', }], poster: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks: + // [ { kind: 'captions', label: 'English', srclang: 'en', src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt', + // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ], + // }; + // TODO: So there is still this thing where a video should only be allowed to start + // playing when the IMA SDK is ready or has failed + if (this.player.ended) { + this.loadAds(); + } else { + // The SDK won't allow new ads to be called without receiving a contentComplete() + this.loader.contentComplete(); + } + + break; + + case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED: + // This event indicates the ad has started - the video player can adjust the UI, + // for example display a pause button and remaining time. Fired when content should + // be paused. This usually happens right before an ad is about to cover the content + this.pauseContent(); + break; + + case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED: + // This event indicates the ad has finished - the video player can perform + // appropriate UI actions, such as removing the timer for remaining time detection. + // Fired when content should be resumed. This usually happens when an ad finishes + // or collapses + this.pollCountdown(); + this.resumeContent(); + break; + + case google.ima.AdEvent.Type.LOG: + if (adData.adError) { + this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`); + } + + break; + } + }); + + _defineProperty$1(this, "onAdError", event => { + this.cancel(); + this.player.debug.warn('Ads error', event); + }); + + _defineProperty$1(this, "listeners", () => { + const { + container + } = this.player.elements; + let time; + this.player.on('canplay', () => { + this.addCuePoints(); + }); + this.player.on('ended', () => { + this.loader.contentComplete(); + }); + this.player.on('timeupdate', () => { + time = this.player.currentTime; + }); + this.player.on('seeked', () => { + const seekedTime = this.player.currentTime; + + if (is.empty(this.cuePoints)) { + return; + } + + this.cuePoints.forEach((cuePoint, index) => { + if (time < cuePoint && cuePoint < seekedTime) { + this.manager.discardAdBreak(); + this.cuePoints.splice(index, 1); + } + }); + }); // Listen to the resizing of the window. And resize ad accordingly + // TODO: eventually implement ResizeObserver + + window.addEventListener('resize', () => { + if (this.manager) { + this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); + } + }); + }); + + _defineProperty$1(this, "play", () => { + const { + container + } = this.player.elements; + + if (!this.managerPromise) { + this.resumeContent(); + } // Play the requested advertisement whenever the adsManager is ready + + + this.managerPromise.then(() => { + // Set volume to match player + this.manager.setVolume(this.player.volume); // Initialize the container. Must be done via a user action on mobile devices + + this.elements.displayContainer.initialize(); + + try { + if (!this.initialized) { + // Initialize the ads manager. Ad rules playlist will start at this time + this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will + // start at this time; the call will be ignored for ad rules + + this.manager.start(); + } + + this.initialized = true; + } catch (adError) { + // An error may be thrown if there was a problem with the + // VAST response + this.onAdError(adError); + } + }).catch(() => {}); + }); + + _defineProperty$1(this, "resumeContent", () => { + // Hide the advertisement container + this.elements.container.style.zIndex = ''; // Ad is stopped + + this.playing = false; // Play video + + silencePromise(this.player.media.play()); + }); + + _defineProperty$1(this, "pauseContent", () => { + // Show the advertisement container + this.elements.container.style.zIndex = 3; // Ad is playing + + this.playing = true; // Pause our video. + + this.player.media.pause(); + }); + + _defineProperty$1(this, "cancel", () => { + // Pause our video + if (this.initialized) { + this.resumeContent(); + } // Tell our instance that we're done for now + + + this.trigger('error'); // Re-create our adsManager + + this.loadAds(); + }); + + _defineProperty$1(this, "loadAds", () => { + // Tell our adsManager to go bye bye + this.managerPromise.then(() => { + // Destroy our adsManager + if (this.manager) { + this.manager.destroy(); + } // Re-set our adsManager promises + + + this.managerPromise = new Promise(resolve => { + this.on('loaded', resolve); + this.player.debug.log(this.manager); + }); // Now that the manager has been destroyed set it to also be un-initialized + + this.initialized = false; // Now request some new advertisements + + this.requestAds(); + }).catch(() => {}); + }); + + _defineProperty$1(this, "trigger", (event, ...args) => { + const handlers = this.events[event]; + + if (is.array(handlers)) { + handlers.forEach(handler => { + if (is.function(handler)) { + handler.apply(this, args); + } + }); + } + }); + + _defineProperty$1(this, "on", (event, callback) => { + if (!is.array(this.events[event])) { + this.events[event] = []; + } + + this.events[event].push(callback); + return this; + }); + + _defineProperty$1(this, "startSafetyTimer", (time, from) => { + this.player.debug.log(`Safety timer invoked from: ${from}`); + this.safetyTimer = setTimeout(() => { + this.cancel(); + this.clearSafetyTimer('startSafetyTimer()'); + }, time); + }); + + _defineProperty$1(this, "clearSafetyTimer", from => { + if (!is.nullOrUndefined(this.safetyTimer)) { + this.player.debug.log(`Safety timer cleared from: ${from}`); + clearTimeout(this.safetyTimer); + this.safetyTimer = null; + } + }); + + this.player = player; + this.config = player.config.ads; + this.playing = false; + this.initialized = false; + this.elements = { + container: null, + displayContainer: null + }; + this.manager = null; + this.loader = null; + this.cuePoints = null; + this.events = {}; + this.safetyTimer = null; + this.countdownTimer = null; // Setup a promise to resolve when the IMA manager is ready + + this.managerPromise = new Promise((resolve, reject) => { + // The ad is loaded and ready + this.on('loaded', resolve); // Ads failed + + this.on('error', reject); + }); + this.load(); + } + + get enabled() { + const { + config + } = this; + return this.player.isHTML5 && this.player.isVideo && config.enabled && (!is.empty(config.publisherId) || is.url(config.tagUrl)); + } + /** + * Load the IMA SDK + */ + + + // 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', + AV_URL: window.location.hostname, + cb: Date.now(), + AV_WIDTH: 640, + AV_HEIGHT: 480, + AV_CDIM2: config.publisherId + }; + const base = 'https://go.aniview.com/api/adserver6/vast/'; + return `${base}?${buildUrlParams(params)}`; + } + /** + * In order for the SDK to display ads for our video, we need to tell it where to put them, + * so here we define our ad container. This div is set up to render on top of the video player. + * Using the code below, we tell the SDK to render ads within that div. We also provide a + * handle to the content video player - the SDK will poll the current time of our player to + * properly place mid-rolls. After we create the ad display container, we initialize it. On + * mobile devices, this initialization is done as the result of a user action. + */ + + + } + + 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] || 0) * 60 * 60 + Number(matchTimes[2]) * 60 + Number(matchTimes[3]) + Number(`0.${matchTimes[4]}`); + result.endTime = Number(matchTimes[6] || 0) * 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 + */ + + + const fitRatio = (ratio, outer) => { + const targetRatio = outer.width / outer.height; + const result = {}; + + if (ratio > targetRatio) { + result.width = outer.width; + result.height = 1 / ratio * outer.width; + } else { + result.height = outer.height; + result.width = ratio * outer.height; + } + + return result; + }; + + class PreviewThumbnails { + /** + * PreviewThumbnails constructor. + * @param {Plyr} player + * @return {PreviewThumbnails} + */ + constructor(player) { + _defineProperty$1(this, "load", () => { + // Toggle the regular seek tooltip + if (this.player.elements.display.seekTooltip) { + this.player.elements.display.seekTooltip.hidden = this.enabled; + } + + if (!this.enabled) { + return; + } + + this.getThumbnails().then(() => { + if (!this.enabled) { + return; + } // Render DOM elements + + + this.render(); // Check to see if thumb container size was specified manually in CSS + + this.determineContainerAutoSizing(); + this.loaded = true; + }); + }); + + _defineProperty$1(this, "getThumbnails", () => { + return new Promise(resolve => { + const { + src + } = this.player.config.previewThumbnails; + + if (is.empty(src)) { + throw new Error('Missing previewThumbnails.src config attribute'); + } // Resolve promise + + + const sortAndResolve = () => { + // 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(); + }; // Via callback() + + + if (is.function(src)) { + src(thumbnails => { + this.thumbnails = thumbnails; + sortAndResolve(); + }); + } // VTT urls + else { + // 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)); // Resolve + + Promise.all(promises).then(sortAndResolve); + } + }); + }); + + _defineProperty$1(this, "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 the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file + + if (!thumbnail.frames[0].text.startsWith('/') && !thumbnail.frames[0].text.startsWith('http://') && !thumbnail.frames[0].text.startsWith('https://')) { + 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; + }); + }); + }); + + _defineProperty$1(this, "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(); + }); + + _defineProperty$1(this, "endMove", () => { + this.toggleThumbContainer(false, true); + }); + + _defineProperty$1(this, "startScrubbing", event => { + // Only act on left mouse button (0), or touch device (event.button does not exist or is false) + if (is.nullOrUndefined(event.button) || 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(); + } + } + }); + + _defineProperty$1(this, "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); + } + }); + } + }); + + _defineProperty$1(this, "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; + }); + }); + + _defineProperty$1(this, "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 + + if (is.element(this.player.elements.progress)) { + 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); + }); + + _defineProperty$1(this, "destroy", () => { + if (this.elements.thumb.container) { + this.elements.thumb.container.remove(); + } + + if (this.elements.scrubbing.container) { + this.elements.scrubbing.container.remove(); + } + }); + + _defineProperty$1(this, "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); + } + }); + + _defineProperty$1(this, "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); + } + }); + + _defineProperty$1(this, "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)); + }); + + _defineProperty$1(this, "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 + // eslint-disable-next-line no-param-reassign + 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); + } + }); + }); + + _defineProperty$1(this, "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); + }); + }); + + _defineProperty$1(this, "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); + } + } + }); + + _defineProperty$1(this, "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; + } + }); + + _defineProperty$1(this, "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; + } + }); + + _defineProperty$1(this, "determineContainerAutoSizing", () => { + if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) { + // This will prevent auto sizing in this.setThumbContainerSizeAndPos() + this.sizeSpecifiedInCSS = true; + } + }); + + _defineProperty$1(this, "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`; + } else if (this.elements.thumb.imageContainer.clientHeight > 20 && this.elements.thumb.imageContainer.clientWidth < 20) { + const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio); + this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`; + } else if (this.elements.thumb.imageContainer.clientHeight < 20 && this.elements.thumb.imageContainer.clientWidth > 20) { + const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio); + this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`; + } + + this.setThumbContainerPos(); + }); + + _defineProperty$1(this, "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`; + }); + + _defineProperty$1(this, "setScrubbingContainerSize", () => { + const { + width, + height + } = fitRatio(this.thumbAspectRatio, { + width: this.player.media.clientWidth, + height: this.player.media.clientHeight + }); + this.elements.scrubbing.container.style.width = `${width}px`; + this.elements.scrubbing.container.style.height = `${height}px`; + }); + + _defineProperty$1(this, "setImageSizeAndOffset", (previewImage, frame) => { + if (!this.usingSprites) { + return; + } // Find difference between height and preview container height + + + const multiplier = this.thumbContainerHeight / frame.h; // eslint-disable-next-line no-param-reassign + + previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.left = `-${frame.x * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.top = `-${frame.y * multiplier}px`; + }); + + 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; + } + + 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) { + const { + height + } = fitRatio(this.thumbAspectRatio, { + width: this.player.media.clientWidth, + height: this.player.media.clientHeight + }); + return height; + } // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset) + + + if (this.sizeSpecifiedInCSS) { + return this.elements.thumb.imageContainer.clientHeight; + } + + 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; + } + } + + } + + // ========================================================================== + const source = { + // Add elements to HTML5 media (source, tracks, etc) + insertElements(type, attributes) { + if (is.string(attributes)) { + insertElement(type, this.media, { + src: attributes + }); + } else if (is.array(attributes)) { + attributes.forEach(attribute => { + insertElement(type, this.media, attribute); + }); + } + }, + + // Update source + // Sources are not checked for support so be careful + change(input) { + if (!getDeep(input, 'sources.length')) { + this.debug.warn('Invalid source format'); + return; + } // Cancel current network requests + + + html5.cancelRequests.call(this); // Destroy instance and re-setup + + this.destroy.call(this, () => { + // Reset quality options + this.options.quality = []; // Remove elements + + removeElement(this.media); + this.media = null; // Reset class name + + if (is.element(this.elements.container)) { + this.elements.container.removeAttribute('class'); + } // Set the type and provider + + + const { + sources, + type + } = input; + const [{ + provider = providers.html5, + src + }] = sources; + const tagName = provider === 'html5' ? type : 'div'; + const attributes = provider === 'html5' ? {} : { + src + }; + Object.assign(this, { + provider, + type, + // Check for support + supported: support.check(type, provider, this.config.playsinline), + // Create new element + media: createElement(tagName, attributes) + }); // Inject the new element + + this.elements.container.appendChild(this.media); // Autoplay the new source? + + if (is.boolean(input.autoplay)) { + this.config.autoplay = input.autoplay; + } // Set attributes for audio and video + + + if (this.isHTML5) { + if (this.config.crossorigin) { + this.media.setAttribute('crossorigin', ''); + } + + if (this.config.autoplay) { + this.media.setAttribute('autoplay', ''); + } + + if (!is.empty(input.poster)) { + this.poster = input.poster; + } + + if (this.config.loop.active) { + this.media.setAttribute('loop', ''); + } + + if (this.config.muted) { + this.media.setAttribute('muted', ''); + } + + if (this.config.playsinline) { + this.media.setAttribute('playsinline', ''); + } + } // Restore class hook + + + ui.addStyleHook.call(this); // Set new sources for html5 + + if (this.isHTML5) { + source.insertElements.call(this, 'source', sources); + } // Set video title + + + this.config.title = input.title; // Set up from scratch + + media.setup.call(this); // HTML5 stuff + + if (this.isHTML5) { + // Setup captions + if (Object.keys(input).includes('tracks')) { + source.insertElements.call(this, 'track', input.tracks); + } + } // If HTML5 or embed but not fully supported, setupInterface and call ready now + + + if (this.isHTML5 || this.isEmbed && !this.supported.ui) { + // Setup interface + ui.build.call(this); + } // Load HTML5 sources + + + if (this.isHTML5) { + this.media.load(); + } // Update previewThumbnails config & reload plugin + + + if (!is.empty(input.previewThumbnails)) { + Object.assign(this.config.previewThumbnails, input.previewThumbnails); // Cleanup previewThumbnails plugin if it was loaded + + if (this.previewThumbnails && this.previewThumbnails.loaded) { + this.previewThumbnails.destroy(); + this.previewThumbnails = null; + } // Create new instance if it is still enabled + + + if (this.config.previewThumbnails.enabled) { + this.previewThumbnails = new PreviewThumbnails(this); + } + } // Update the fullscreen support + + + this.fullscreen.update(); + }, true); + } + + }; + + /** + * Returns a number whose value is limited to the given range. + * + * Example: limit the output of this computation to between 0 and 255 + * (x * 255).clamp(0, 255) + * + * @param {Number} input + * @param {Number} min The lower boundary of the output range + * @param {Number} max The upper boundary of the output range + * @returns A number in the range [min, max] + * @type Number + */ + function clamp(input = 0, min = 0, max = 255) { + return Math.min(Math.max(input, min), max); + } + + // TODO: Use a WeakMap for private globals + // const globals = new WeakMap(); + // Plyr instance + + class Plyr { + constructor(target, options) { + _defineProperty$1(this, "play", () => { + if (!is.function(this.media.play)) { + return null; + } // Intecept play with ads + + + if (this.ads && this.ads.enabled) { + this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play())); + } // Return the promise (for HTML5) + + + return this.media.play(); + }); + + _defineProperty$1(this, "pause", () => { + if (!this.playing || !is.function(this.media.pause)) { + return null; + } + + return this.media.pause(); + }); + + _defineProperty$1(this, "togglePlay", input => { + // Toggle based on current state if nothing passed + const toggle = is.boolean(input) ? input : !this.playing; + + if (toggle) { + return this.play(); + } + + return this.pause(); + }); + + _defineProperty$1(this, "stop", () => { + if (this.isHTML5) { + this.pause(); + this.restart(); + } else if (is.function(this.media.stop)) { + this.media.stop(); + } + }); + + _defineProperty$1(this, "restart", () => { + this.currentTime = 0; + }); + + _defineProperty$1(this, "rewind", seekTime => { + this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime; + }); + + _defineProperty$1(this, "forward", seekTime => { + this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime; + }); + + _defineProperty$1(this, "increaseVolume", step => { + const volume = this.media.muted ? 0 : this.volume; + this.volume = volume + (is.number(step) ? step : 0); + }); + + _defineProperty$1(this, "decreaseVolume", step => { + this.increaseVolume(-step); + }); + + _defineProperty$1(this, "airplay", () => { + // Show dialog if supported + if (support.airplay) { + this.media.webkitShowPlaybackTargetPicker(); + } + }); + + _defineProperty$1(this, "toggleControls", toggle => { + // Don't toggle if missing UI support or if it's audio + if (this.supported.ui && !this.isAudio) { + // Get state before change + const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls); // Negate the argument if not undefined since adding the class to hides the controls + + const force = typeof toggle === 'undefined' ? undefined : !toggle; // Apply and get updated state + + const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force); // Close menu + + if (hiding && is.array(this.config.controls) && this.config.controls.includes('settings') && !is.empty(this.config.settings)) { + controls.toggleMenu.call(this, false); + } // Trigger event on change + + + if (hiding !== isHidden) { + const eventName = hiding ? 'controlshidden' : 'controlsshown'; + triggerEvent.call(this, this.media, eventName); + } + + return !hiding; + } + + return false; + }); + + _defineProperty$1(this, "on", (event, callback) => { + on.call(this, this.elements.container, event, callback); + }); + + _defineProperty$1(this, "once", (event, callback) => { + once.call(this, this.elements.container, event, callback); + }); + + _defineProperty$1(this, "off", (event, callback) => { + off(this.elements.container, event, callback); + }); + + _defineProperty$1(this, "destroy", (callback, soft = false) => { + if (!this.ready) { + return; + } + + const done = () => { + // Reset overflow (incase destroyed while in fullscreen) + document.body.style.overflow = ''; // GC for embed + + this.embed = null; // If it's a soft destroy, make minimal changes + + if (soft) { + if (Object.keys(this.elements).length) { + // Remove elements + removeElement(this.elements.buttons.play); + removeElement(this.elements.captions); + removeElement(this.elements.controls); + removeElement(this.elements.wrapper); // Clear for GC + + this.elements.buttons.play = null; + this.elements.captions = null; + this.elements.controls = null; + this.elements.wrapper = null; + } // Callback + + + if (is.function(callback)) { + callback(); + } + } else { + // Unbind listeners + unbindListeners.call(this); // Cancel current network requests + + html5.cancelRequests.call(this); // Replace the container with the original element provided + + replaceElement(this.elements.original, this.elements.container); // Event + + triggerEvent.call(this, this.elements.original, 'destroyed', true); // Callback + + if (is.function(callback)) { + callback.call(this.elements.original); + } // Reset state + + + this.ready = false; // Clear for garbage collection + + setTimeout(() => { + this.elements = null; + this.media = null; + }, 200); + } + }; // Stop playback + + + this.stop(); // Clear timeouts + + clearTimeout(this.timers.loading); + clearTimeout(this.timers.controls); + clearTimeout(this.timers.resized); // Provider specific stuff + + if (this.isHTML5) { + // Restore native video controls + ui.toggleNativeControls.call(this, true); // Clean up + + done(); + } else if (this.isYouTube) { + // Clear timers + clearInterval(this.timers.buffering); + clearInterval(this.timers.playing); // Destroy YouTube API + + if (this.embed !== null && is.function(this.embed.destroy)) { + this.embed.destroy(); + } // Clean up + + + done(); + } else if (this.isVimeo) { + // Destroy Vimeo API + // then clean up (wait, to prevent postmessage errors) + if (this.embed !== null) { + this.embed.unload().then(done); + } // Vimeo does not always return + + + setTimeout(done, 200); + } + }); + + _defineProperty$1(this, "supports", type => support.mime.call(this, type)); + + this.timers = {}; // State + + this.ready = false; + this.loading = false; + this.failed = false; // Touch device + + this.touch = support.touch; // Set the media element + + this.media = target; // String selector passed + + if (is.string(this.media)) { + this.media = document.querySelectorAll(this.media); + } // jQuery, NodeList or Array passed, use first element + + + if (window.jQuery && this.media instanceof jQuery || is.nodeList(this.media) || is.array(this.media)) { + // eslint-disable-next-line + this.media = this.media[0]; + } // Set config + + + this.config = extend({}, defaults, Plyr.defaults, options || {}, (() => { + try { + return JSON.parse(this.media.getAttribute('data-plyr-config')); + } catch (_) { + return {}; + } + })()); // Elements cache + + this.elements = { + container: null, + fullscreen: null, + captions: null, + buttons: {}, + display: {}, + progress: {}, + inputs: {}, + settings: { + popup: null, + menu: null, + panels: {}, + buttons: {} + } + }; // Captions + + this.captions = { + active: null, + currentTrack: -1, + meta: new WeakMap() + }; // Fullscreen + + this.fullscreen = { + active: false + }; // Options + + this.options = { + speed: [], + quality: [] + }; // Debugging + // TODO: move to globals + + this.debug = new Console(this.config.debug); // Log config options and support + + this.debug.log('Config', this.config); + this.debug.log('Support', support); // We need an element to setup + + if (is.nullOrUndefined(this.media) || !is.element(this.media)) { + this.debug.error('Setup failed: no suitable element passed'); + return; + } // Bail if the element is initialized + + + if (this.media.plyr) { + this.debug.warn('Target already setup'); + return; + } // Bail if not enabled + + + if (!this.config.enabled) { + this.debug.error('Setup failed: disabled by config'); + return; + } // Bail if disabled or no basic support + // You may want to disable certain UAs etc + + + if (!support.check().api) { + this.debug.error('Setup failed: no support'); + return; + } // Cache original element state for .destroy() + + + const clone = this.media.cloneNode(true); + clone.autoplay = false; + this.elements.original = clone; // Set media type based on tag or data attribute + // Supported: video, audio, vimeo, youtube + + const _type = this.media.tagName.toLowerCase(); // Embed properties + + + let iframe = null; + let url = null; // Different setup based on type + + switch (_type) { + case 'div': + // Find the frame + iframe = this.media.querySelector('iframe'); // <iframe> type + + if (is.element(iframe)) { + // Detect provider + url = parseUrl(iframe.getAttribute('src')); + this.provider = getProviderByUrl(url.toString()); // Rework elements + + this.elements.container = this.media; + this.media = iframe; // Reset classname + + this.elements.container.className = ''; // Get attributes from URL and set config + + if (url.search.length) { + const truthy = ['1', 'true']; + + if (truthy.includes(url.searchParams.get('autoplay'))) { + this.config.autoplay = true; + } + + if (truthy.includes(url.searchParams.get('loop'))) { + this.config.loop.active = true; + } // TODO: replace fullscreen.iosNative with this playsinline config option + // YouTube requires the playsinline in the URL + + + if (this.isYouTube) { + this.config.playsinline = truthy.includes(url.searchParams.get('playsinline')); + this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language? + } else { + this.config.playsinline = true; + } + } + } else { + // <div> with attributes + this.provider = this.media.getAttribute(this.config.attributes.embed.provider); // Remove attribute + + this.media.removeAttribute(this.config.attributes.embed.provider); + } // Unsupported or missing provider + + + if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) { + this.debug.error('Setup failed: Invalid provider'); + return; + } // Audio will come later for external providers + + + this.type = types.video; + break; + + case 'video': + case 'audio': + this.type = _type; + this.provider = providers.html5; // Get config from attributes + + if (this.media.hasAttribute('crossorigin')) { + this.config.crossorigin = true; + } + + if (this.media.hasAttribute('autoplay')) { + this.config.autoplay = true; + } + + if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) { + this.config.playsinline = true; + } + + if (this.media.hasAttribute('muted')) { + this.config.muted = true; + } + + if (this.media.hasAttribute('loop')) { + this.config.loop.active = true; + } + + break; + + default: + this.debug.error('Setup failed: unsupported type'); + return; + } // Check for support again but with type + + + this.supported = support.check(this.type, this.provider, this.config.playsinline); // If no support for even API, bail + + if (!this.supported.api) { + this.debug.error('Setup failed: no support'); + return; + } + + this.eventListeners = []; // Create listeners + + this.listeners = new Listeners(this); // Setup local storage for user settings + + this.storage = new Storage(this); // Store reference + + this.media.plyr = this; // Wrap media + + if (!is.element(this.elements.container)) { + this.elements.container = createElement('div', { + tabindex: 0 + }); + wrap(this.media, this.elements.container); + } // Migrate custom properties from media to container (so they work 😉) + + + ui.migrateStyles.call(this); // Add style hook + + ui.addStyleHook.call(this); // Setup media + + media.setup.call(this); // Listen for events if debugging + + if (this.config.debug) { + on.call(this, this.elements.container, this.config.events.join(' '), event => { + this.debug.log(`event: ${event.type}`); + }); + } // Setup fullscreen + + + this.fullscreen = new Fullscreen(this); // Setup interface + // If embed but not fully supported, build interface now to avoid flash of controls + + if (this.isHTML5 || this.isEmbed && !this.supported.ui) { + ui.build.call(this); + } // Container listeners + + + this.listeners.container(); // Global listeners + + this.listeners.global(); // Setup ads if provided + + if (this.config.ads.enabled) { + this.ads = new Ads(this); + } // Autoplay if required + + + if (this.isHTML5 && this.config.autoplay) { + this.once('canplay', () => silencePromise(this.play())); + } // 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); + } + } // --------------------------------------- + // API + // --------------------------------------- + + /** + * Types and provider helpers + */ + + + get isHTML5() { + return this.provider === providers.html5; + } + + get isEmbed() { + return this.isYouTube || this.isVimeo; + } + + get isYouTube() { + return this.provider === providers.youtube; + } + + get isVimeo() { + return this.provider === providers.vimeo; + } + + get isVideo() { + return this.type === types.video; + } + + get isAudio() { + return this.type === types.audio; + } + /** + * Play the media, or play the advertisement (if they are not blocked) + */ + + + /** + * Get playing state + */ + get playing() { + return Boolean(this.ready && !this.paused && !this.ended); + } + /** + * Get paused state + */ + + + get paused() { + return Boolean(this.media.paused); + } + /** + * Get stopped state + */ + + + get stopped() { + return Boolean(this.paused && this.currentTime === 0); + } + /** + * Get ended state + */ + + + get ended() { + return Boolean(this.media.ended); + } + /** + * Toggle playback based on current status + * @param {Boolean} input + */ + + + /** + * Seek to a time + * @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 + if (!this.duration) { + return; + } // Validate input + + + const inputIsValid = is.number(input) && input > 0; // Set + + this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0; // Logging + + this.debug.log(`Seeking to ${this.currentTime} seconds`); + } + /** + * Get current time + */ + + + get currentTime() { + return Number(this.media.currentTime); + } + /** + * Get buffered + */ + + + get buffered() { + const { + buffered + } = this.media; // YouTube / Vimeo return a float between 0-1 + + if (is.number(buffered)) { + return buffered; + } // HTML5 + // TODO: Handle buffered chunks of the media + // (i.e. seek to another section buffers only that section) + + + if (buffered && buffered.length && this.duration > 0) { + return buffered.end(0) / this.duration; + } + + return 0; + } + /** + * Get seeking status + */ + + + get seeking() { + return Boolean(this.media.seeking); + } + /** + * Get the duration of the current media + */ + + + get duration() { + // Faux duration set via config + const fauxDuration = parseFloat(this.config.duration); // Media duration can be NaN or Infinity before the media has loaded + + const realDuration = (this.media || {}).duration; + const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration; // If config duration is funky, use regular duration + + return fauxDuration || duration; + } + /** + * 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 + */ + + + set volume(value) { + let volume = value; + const max = 1; + const min = 0; + + if (is.string(volume)) { + volume = Number(volume); + } // Load volume from storage if no value specified + + + if (!is.number(volume)) { + volume = this.storage.get('volume'); + } // Use config if all else fails + + + if (!is.number(volume)) { + ({ + volume + } = this.config); + } // Maximum is volumeMax + + + if (volume > max) { + volume = max; + } // Minimum is volumeMin + + + if (volume < min) { + volume = min; + } // Update config + + + this.config.volume = volume; // Set the player volume + + this.media.volume = volume; // If muted, and we're increasing volume manually, reset muted state + + if (!is.empty(value) && this.muted && volume > 0) { + this.muted = false; + } + } + /** + * Get the current player volume + */ + + + get volume() { + return Number(this.media.volume); + } + /** + * Increase volume + * @param {Boolean} step - How much to decrease by (between 0 and 1) + */ + + + /** + * Set muted state + * @param {Boolean} mute + */ + set muted(mute) { + let toggle = mute; // Load muted state from storage + + if (!is.boolean(toggle)) { + toggle = this.storage.get('muted'); + } // Use config if all else fails + + + if (!is.boolean(toggle)) { + toggle = this.config.muted; + } // Update config + + + this.config.muted = toggle; // Set mute on the player + + this.media.muted = toggle; + } + /** + * Get current muted state + */ + + + get muted() { + return Boolean(this.media.muted); + } + /** + * Check if the media has audio + */ + + + get hasAudio() { + // Assume yes for all non HTML5 (as we can't tell...) + if (!this.isHTML5) { + return true; + } + + if (this.isAudio) { + return true; + } // Get audio tracks + + + return Boolean(this.media.mozHasAudio) || Boolean(this.media.webkitAudioDecodedByteCount) || Boolean(this.media.audioTracks && this.media.audioTracks.length); + } + /** + * Set playback speed + * @param {Number} speed - the speed of playback (0.5-2.0) + */ + + + set speed(input) { + let speed = null; + + if (is.number(input)) { + speed = input; + } + + if (!is.number(speed)) { + speed = this.storage.get('speed'); + } + + if (!is.number(speed)) { + speed = this.config.speed.selected; + } // Clamp to min/max + + + const { + minimumSpeed: min, + maximumSpeed: max + } = this; + speed = clamp(speed, min, max); // Update config + + this.config.speed.selected = speed; // Set media speed + + setTimeout(() => { + if (this.media) { + this.media.playbackRate = speed; + } + }, 0); + } + /** + * Get current playback speed + */ + + + get speed() { + return Number(this.media.playbackRate); + } + /** + * Get the minimum allowed speed + */ + + + get minimumSpeed() { + if (this.isYouTube) { + // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate + return Math.min(...this.options.speed); + } + + if (this.isVimeo) { + // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror + return 0.5; + } // https://stackoverflow.com/a/32320020/1191319 + + + return 0.0625; + } + /** + * Get the maximum allowed speed + */ + + + get maximumSpeed() { + if (this.isYouTube) { + // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate + return Math.max(...this.options.speed); + } + + if (this.isVimeo) { + // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror + return 2; + } // https://stackoverflow.com/a/32320020/1191319 + + + return 16; + } + /** + * Set playback quality + * Currently HTML5 & YouTube only + * @param {Number} input - Quality level + */ + + + set quality(input) { + const config = this.config.quality; + const options = this.options.quality; + + if (!options.length) { + return; + } + + let quality = [!is.empty(input) && Number(input), this.storage.get('quality'), config.selected, config.default].find(is.number); + let updateStorage = true; + + if (!options.includes(quality)) { + const value = closest(options, quality); + this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`); + quality = value; // Don't update storage if quality is not supported + + updateStorage = false; + } // Update config + + + config.selected = quality; // Set quality + + this.media.quality = quality; // Save to storage + + if (updateStorage) { + this.storage.set({ + quality + }); + } + } + /** + * Get current quality level + */ + + + get quality() { + return this.media.quality; + } + /** + * 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 + */ + + + set loop(input) { + const toggle = is.boolean(input) ? input : this.config.loop.active; + this.config.loop.active = toggle; + this.media.loop = toggle; // Set default to be a true toggle + + /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle'; + switch (type) { + case 'start': + if (this.config.loop.end && this.config.loop.end <= this.currentTime) { + this.config.loop.end = null; + } + this.config.loop.start = this.currentTime; + // this.config.loop.indicator.start = this.elements.display.played.value; + break; + case 'end': + if (this.config.loop.start >= this.currentTime) { + return this; + } + this.config.loop.end = this.currentTime; + // this.config.loop.indicator.end = this.elements.display.played.value; + break; + case 'all': + this.config.loop.start = 0; + this.config.loop.end = this.duration - 2; + this.config.loop.indicator.start = 0; + this.config.loop.indicator.end = 100; + break; + case 'toggle': + if (this.config.loop.active) { + this.config.loop.start = 0; + this.config.loop.end = null; + } else { + this.config.loop.start = 0; + this.config.loop.end = this.duration - 2; + } + break; + default: + this.config.loop.start = 0; + this.config.loop.end = null; + break; + } */ + } + /** + * Get current loop state + */ + + + get loop() { + return Boolean(this.media.loop); + } + /** + * Set new media source + * @param {Object} input - The new source object (see docs) + */ + + + set source(input) { + source.change.call(this, input); + } + /** + * Get current source + */ + + + get source() { + return this.media.currentSrc; + } + /** + * Get a download URL (either source or custom) + */ + + + get download() { + const { + download + } = this.config.urls; + return is.url(download) ? download : this.source; + } + /** + * Set the download URL + */ + + + set download(input) { + if (!is.url(input)) { + return; + } + + this.config.urls.download = input; + controls.setDownloadUrl.call(this); + } + /** + * Set the poster image for a video + * @param {String} input - the URL for the new poster image + */ + + + set poster(input) { + if (!this.isVideo) { + this.debug.warn('Poster can only be set for video'); + return; + } + + ui.setPoster.call(this, input, false).catch(() => {}); + } + /** + * Get the current poster image + */ + + + get poster() { + if (!this.isVideo) { + return null; + } + + return this.media.getAttribute('poster') || this.media.getAttribute('data-poster'); + } + /** + * Get the current aspect ratio in use + */ + + + get ratio() { + if (!this.isVideo) { + return null; + } + + const ratio = reduceAspectRatio(getAspectRatio.call(this)); + return is.array(ratio) ? ratio.join(':') : ratio; + } + /** + * Set video aspect ratio + */ + + + set ratio(input) { + if (!this.isVideo) { + this.debug.warn('Aspect ratio can only be set for video'); + return; + } + + if (!is.string(input) || !validateAspectRatio(input)) { + this.debug.error(`Invalid aspect ratio specified (${input})`); + return; + } + + this.config.ratio = reduceAspectRatio(input); + setAspectRatio.call(this); + } + /** + * Set the autoplay state + * @param {Boolean} input - Whether to autoplay or not + */ + + + set autoplay(input) { + const toggle = is.boolean(input) ? input : this.config.autoplay; + this.config.autoplay = toggle; + } + /** + * Get the current autoplay state + */ + + + get autoplay() { + return Boolean(this.config.autoplay); + } + /** + * Toggle captions + * @param {Boolean} input - Whether to enable captions + */ + + + toggleCaptions(input) { + captions.toggle.call(this, input, false); + } + /** + * Set the caption track by index + * @param {Number} - Caption index + */ + + + set currentTrack(input) { + captions.set.call(this, input, false); + captions.setup(); + } + /** + * Get the current caption track index (-1 if disabled) + */ + + + get currentTrack() { + const { + toggled, + currentTrack + } = this.captions; + return toggled ? currentTrack : -1; + } + /** + * 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) + */ + + + set language(input) { + captions.setLanguage.call(this, input, false); + } + /** + * Get the current track's language + */ + + + get language() { + return (captions.getCurrentTrack.call(this) || {}).language; + } + /** + * Toggle picture-in-picture playback on WebKit/MacOS + * TODO: update player with state, support, enabled + * TODO: detect outside changes + */ + + + set pip(input) { + // Bail if no support + if (!support.pip) { + return; + } // Toggle based on current state if not passed + + + const toggle = is.boolean(input) ? input : !this.pip; // Toggle based on current state + // Safari + + if (is.function(this.media.webkitSetPresentationMode)) { + this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive); + } // Chrome + + + if (is.function(this.media.requestPictureInPicture)) { + if (!this.pip && toggle) { + this.media.requestPictureInPicture(); + } else if (this.pip && !toggle) { + document.exitPictureInPicture(); + } + } + } + /** + * Get the current picture-in-picture state + */ + + + get pip() { + if (!support.pip) { + return null; + } // Safari + + + if (!is.empty(this.media.webkitPresentationMode)) { + return this.media.webkitPresentationMode === pip.active; + } // Chrome + + + return this.media === document.pictureInPictureElement; + } + /** + * Sets the preview thubmnails for the current source + */ + + + setPreviewThumbnails(thumbnailSource) { + if (this.previewThumbnails && this.previewThumbnails.loaded) { + this.previewThumbnails.destroy(); + this.previewThumbnails = null; + } + + Object.assign(this.config.previewThumbnails, thumbnailSource); // Create new instance if it is still enabled + + if (this.config.previewThumbnails.enabled) { + this.previewThumbnails = new PreviewThumbnails(this); + } + } + /** + * Trigger the airplay dialog + * TODO: update player with state, support, enabled + */ + + + /** + * Check for support + * @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); + } + /** + * Load an SVG sprite into the page + * @param {String} url - URL for the SVG sprite + * @param {String} [id] - Unique ID + */ + + + static loadSprite(url, id) { + return loadSprite(url, id); + } + /** + * Setup multiple instances + * @param {*} selector + * @param {Object} options + */ + + + static setup(selector, options = {}) { + let targets = null; + + if (is.string(selector)) { + targets = Array.from(document.querySelectorAll(selector)); + } else if (is.nodeList(selector)) { + targets = Array.from(selector); + } else if (is.array(selector)) { + targets = selector.filter(is.element); + } + + if (is.empty(targets)) { + return null; + } + + return targets.map(t => new Plyr(t, options)); + } + + } + + Plyr.defaults = cloneDeep(defaults); + + return Plyr; + +})); diff --git a/extlib/plyr/plyr.min.js b/extlib/plyr/plyr.min.js new file mode 100644 index 00000000..4c7f5a6a --- /dev/null +++ b/extlib/plyr/plyr.min.js @@ -0,0 +1,2 @@ +"object"==typeof navigator&&function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Plyr",t):(e="undefined"!=typeof globalThis?globalThis:e||self).Plyr=t()}(this,(function(){"use strict";function e(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function t(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}function i(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function s(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function n(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?s(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):s(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var a={addCSS:!0,thumbWidth:15,watch:!0};function l(e,t){return function(){return Array.from(document.querySelectorAll(t)).includes(this)}.call(e,t)}var o=function(e){return null!=e?e.constructor:null},r=function(e,t){return!!(e&&t&&e instanceof t)},c=function(e){return null==e},h=function(e){return o(e)===Object},u=function(e){return o(e)===String},d=function(e){return Array.isArray(e)},m=function(e){return r(e,NodeList)},p=u,g=d,f=m,b=function(e){return r(e,Element)},y=function(e){return r(e,Event)},v=function(e){return c(e)||(u(e)||d(e)||m(e))&&!e.length||h(e)&&!Object.keys(e).length};function w(e,t){if(1>t){var i=function(e){var t="".concat(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0}(t);return parseFloat(e.toFixed(i))}return Math.round(e/t)*t}var T=function(){function e(t,i){(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),b(t)?this.element=t:p(t)&&(this.element=document.querySelector(t)),b(this.element)&&v(this.element.rangeTouch)&&(this.config=n({},a,{},i),this.init())}return function(e,i,s){i&&t(e.prototype,i),s&&t(e,s)}(e,[{key:"init",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect="none",this.element.style.webKitUserSelect="none",this.element.style.touchAction="manipulation"),this.listeners(!0),this.element.rangeTouch=this)}},{key:"destroy",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect="",this.element.style.webKitUserSelect="",this.element.style.touchAction=""),this.listeners(!1),this.element.rangeTouch=null)}},{key:"listeners",value:function(e){var t=this,i=e?"addEventListener":"removeEventListener";["touchstart","touchmove","touchend"].forEach((function(e){t.element[i](e,(function(e){return t.set(e)}),!1)}))}},{key:"get",value:function(t){if(!e.enabled||!y(t))return null;var i,s=t.target,n=t.changedTouches[0],a=parseFloat(s.getAttribute("min"))||0,l=parseFloat(s.getAttribute("max"))||100,o=parseFloat(s.getAttribute("step"))||1,r=s.getBoundingClientRect(),c=100/r.width*(this.config.thumbWidth/2)/100;return 0>(i=100/r.width*(n.clientX-r.left))?i=0:100<i&&(i=100),50>i?i-=(100-2*i)*c:50<i&&(i+=2*(i-50)*c),a+w(i/100*(l-a),o)}},{key:"set",value:function(t){e.enabled&&y(t)&&!t.target.disabled&&(t.preventDefault(),t.target.value=this.get(t),function(e,t){if(e&&t){var i=new Event(t,{bubbles:!0});e.dispatchEvent(i)}}(t.target,"touchend"===t.type?"change":"input"))}}],[{key:"setup",value:function(t){var i=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},s=null;if(v(t)||p(t)?s=Array.from(document.querySelectorAll(p(t)?t:'input[type="range"]')):b(t)?s=[t]:f(t)?s=Array.from(t):g(t)&&(s=t.filter(b)),v(s))return null;var o=n({},a,{},i);if(p(t)&&o.watch){var r=new MutationObserver((function(i){Array.from(i).forEach((function(i){Array.from(i.addedNodes).forEach((function(i){b(i)&&l(i,t)&&new e(i,o)}))}))}));r.observe(document.body,{childList:!0,subtree:!0})}return s.map((function(t){return new e(t,i)}))}},{key:"enabled",get:function(){return"ontouchstart"in document.documentElement}}]),e}();const k=e=>null!=e?e.constructor:null,C=(e,t)=>Boolean(e&&t&&e instanceof t),A=e=>null==e,S=e=>k(e)===Object,E=e=>k(e)===String,P=e=>k(e)===Function,N=e=>Array.isArray(e),x=e=>C(e,NodeList),M=e=>A(e)||(E(e)||N(e)||x(e))&&!e.length||S(e)&&!Object.keys(e).length;var I=A,L=S,$=e=>k(e)===Number&&!Number.isNaN(e),_=E,O=e=>k(e)===Boolean,j=P,q=N,D=x,H=e=>null!==e&&"object"==typeof e&&1===e.nodeType&&"object"==typeof e.style&&"object"==typeof e.ownerDocument,F=e=>C(e,Event),R=e=>C(e,KeyboardEvent),V=e=>C(e,TextTrack)||!A(e)&&E(e.kind),B=e=>C(e,Promise)&&P(e.then),U=e=>{if(C(e,window.URL))return!0;if(!E(e))return!1;let t=e;e.startsWith("http://")&&e.startsWith("https://")||(t=`http://${e}`);try{return!M(new URL(t).hostname)}catch(e){return!1}},W=M;const z=(()=>{const e=document.createElement("span"),t={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},i=Object.keys(t).find((t=>void 0!==e.style[t]));return!!_(i)&&t[i]})();function K(e,t){setTimeout((()=>{try{e.hidden=!0,e.offsetHeight,e.hidden=!1}catch(e){}}),t)}const Y={isIE:Boolean(window.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:"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1||/(iPad|iPhone|iPod)/gi.test(navigator.platform)};function Q(e,t){return t.split(".").reduce(((e,t)=>e&&e[t]),e)}function X(e={},...t){if(!t.length)return e;const i=t.shift();return L(i)?(Object.keys(i).forEach((t=>{L(i[t])?(Object.keys(e).includes(t)||Object.assign(e,{[t]:{}}),X(e[t],i[t])):Object.assign(e,{[t]:i[t]})})),X(e,...t)):e}function J(e,t){const i=e.length?e:[e];Array.from(i).reverse().forEach(((e,i)=>{const s=i>0?t.cloneNode(!0):t,n=e.parentNode,a=e.nextSibling;s.appendChild(e),a?n.insertBefore(s,a):n.appendChild(s)}))}function G(e,t){H(e)&&!W(t)&&Object.entries(t).filter((([,e])=>!I(e))).forEach((([t,i])=>e.setAttribute(t,i)))}function Z(e,t,i){const s=document.createElement(e);return L(t)&&G(s,t),_(i)&&(s.innerText=i),s}function ee(e,t,i,s){H(t)&&t.appendChild(Z(e,i,s))}function te(e){D(e)||q(e)?Array.from(e).forEach(te):H(e)&&H(e.parentNode)&&e.parentNode.removeChild(e)}function ie(e){if(!H(e))return;let{length:t}=e.childNodes;for(;t>0;)e.removeChild(e.lastChild),t-=1}function se(e,t){return H(t)&&H(t.parentNode)&&H(e)?(t.parentNode.replaceChild(e,t),e):null}function ne(e,t){if(!_(e)||W(e))return{};const i={},s=X({},t);return e.split(",").forEach((e=>{const t=e.trim(),n=t.replace(".",""),a=t.replace(/[[\]]/g,"").split("="),[l]=a,o=a.length>1?a[1].replace(/["']/g,""):"";switch(t.charAt(0)){case".":_(s.class)?i.class=`${s.class} ${n}`:i.class=n;break;case"#":i.id=t.replace("#","");break;case"[":i[l]=o}})),X(s,i)}function ae(e,t){if(!H(e))return;let i=t;O(i)||(i=!e.hidden),e.hidden=i}function le(e,t,i){if(D(e))return Array.from(e).map((e=>le(e,t,i)));if(H(e)){let s="toggle";return void 0!==i&&(s=i?"add":"remove"),e.classList[s](t),e.classList.contains(t)}return!1}function oe(e,t){return H(e)&&e.classList.contains(t)}function re(e,t){const{prototype:i}=Element;return(i.matches||i.webkitMatchesSelector||i.mozMatchesSelector||i.msMatchesSelector||function(){return Array.from(document.querySelectorAll(t)).includes(this)}).call(e,t)}function ce(e){return this.elements.container.querySelectorAll(e)}function he(e){return this.elements.container.querySelector(e)}function ue(e=null,t=!1){H(e)&&(e.focus({preventScroll:!0}),t&&le(e,this.config.classNames.tabFocus))}const de={"audio/ogg":"vorbis","audio/wav":"1","video/webm":"vp8, vorbis","video/mp4":"avc1.42E01E, mp4a.40.2","video/ogg":"theora"},me={audio:"canPlayType"in document.createElement("audio"),video:"canPlayType"in document.createElement("video"),check(e,t,i){const s=Y.isIPhone&&i&&me.playsinline,n=me[e]||"html5"!==t;return{api:n,ui:n&&me.rangeInput&&("video"!==e||!Y.isIPhone||s)}},pip:!(Y.isIPhone||!j(Z("video").webkitSetPresentationMode)&&(!document.pictureInPictureEnabled||Z("video").disablePictureInPicture)),airplay:j(window.WebKitPlaybackTargetAvailabilityEvent),playsinline:"playsInline"in document.createElement("video"),mime(e){if(W(e))return!1;const[t]=e.split("/");let i=e;if(!this.isHTML5||t!==this.type)return!1;Object.keys(de).includes(i)&&(i+=`; codecs="${de[e]}"`);try{return Boolean(i&&this.media.canPlayType(i).replace(/no/,""))}catch(e){return!1}},textTracks:"textTracks"in document.createElement("video"),rangeInput:(()=>{const e=document.createElement("input");return e.type="range","range"===e.type})(),touch:"ontouchstart"in document.documentElement,transitions:!1!==z,reducedMotion:"matchMedia"in window&&window.matchMedia("(prefers-reduced-motion)").matches},pe=(()=>{let e=!1;try{const t=Object.defineProperty({},"passive",{get:()=>(e=!0,null)});window.addEventListener("test",null,t),window.removeEventListener("test",null,t)}catch(e){}return e})();function ge(e,t,i,s=!1,n=!0,a=!1){if(!e||!("addEventListener"in e)||W(t)||!j(i))return;const l=t.split(" ");let o=a;pe&&(o={passive:n,capture:a}),l.forEach((t=>{this&&this.eventListeners&&s&&this.eventListeners.push({element:e,type:t,callback:i,options:o}),e[s?"addEventListener":"removeEventListener"](t,i,o)}))}function fe(e,t="",i,s=!0,n=!1){ge.call(this,e,t,i,!0,s,n)}function be(e,t="",i,s=!0,n=!1){ge.call(this,e,t,i,!1,s,n)}function ye(e,t="",i,s=!0,n=!1){const a=(...l)=>{be(e,t,a,s,n),i.apply(this,l)};ge.call(this,e,t,a,!0,s,n)}function ve(e,t="",i=!1,s={}){if(!H(e)||W(t))return;const n=new CustomEvent(t,{bubbles:i,detail:{...s,plyr:this}});e.dispatchEvent(n)}function we(){this&&this.eventListeners&&(this.eventListeners.forEach((e=>{const{element:t,type:i,callback:s,options:n}=e;t.removeEventListener(i,s,n)})),this.eventListeners=[])}function Te(){return new Promise((e=>this.ready?setTimeout(e,0):fe.call(this,this.elements.container,"ready",e))).then((()=>{}))}function ke(e){B(e)&&e.then(null,(()=>{}))}function Ce(e){return q(e)?e.filter(((t,i)=>e.indexOf(t)===i)):e}function Ae(e,t){return q(e)&&e.length?e.reduce(((e,i)=>Math.abs(i-t)<Math.abs(e-t)?i:e)):null}function Se(e){return!(!window||!window.CSS)&&window.CSS.supports(e)}const Ee=[[1,1],[4,3],[3,4],[5,4],[4,5],[3,2],[2,3],[16,10],[10,16],[16,9],[9,16],[21,9],[9,21],[32,9],[9,32]].reduce(((e,[t,i])=>({...e,[t/i]:[t,i]})),{});function Pe(e){if(!(q(e)||_(e)&&e.includes(":")))return!1;return(q(e)?e:e.split(":")).map(Number).every($)}function Ne(e){if(!q(e)||!e.every($))return null;const[t,i]=e,s=(e,t)=>0===t?e:s(t,e%t),n=s(t,i);return[t/n,i/n]}function xe(e){const t=e=>Pe(e)?e.split(":").map(Number):null;let i=t(e);if(null===i&&(i=t(this.config.ratio)),null===i&&!W(this.embed)&&q(this.embed.ratio)&&({ratio:i}=this.embed),null===i&&this.isHTML5){const{videoWidth:e,videoHeight:t}=this.media;i=[e,t]}return Ne(i)}function Me(e){if(!this.isVideo)return{};const{wrapper:t}=this.elements,i=xe.call(this,e);if(!q(i))return{};const[s,n]=Ne(i),a=100/s*n;if(Se(`aspect-ratio: ${s}/${n}`)?t.style.aspectRatio=`${s}/${n}`:t.style.paddingBottom=`${a}%`,this.isVimeo&&!this.config.vimeo.premium&&this.supported.ui){const e=100/this.media.offsetWidth*parseInt(window.getComputedStyle(this.media).paddingBottom,10),i=(e-a)/(e/50);this.fullscreen.active?t.style.paddingBottom=null:this.media.style.transform=`translateY(-${i}%)`}else this.isHTML5&&t.classList.add(this.config.classNames.videoFixedRatio);return{padding:a,ratio:i}}function Ie(e,t,i=.05){const s=e/t,n=Ae(Object.keys(Ee),s);return Math.abs(n-s)<=i?Ee[n]:[e,t]}const Le={getSources(){if(!this.isHTML5)return[];return Array.from(this.media.querySelectorAll("source")).filter((e=>{const t=e.getAttribute("type");return!!W(t)||me.mime.call(this,t)}))},getQualityOptions(){return this.config.quality.forced?this.config.quality.options:Le.getSources.call(this).map((e=>Number(e.getAttribute("data-res")))).filter(Boolean)},setup(){if(!this.isHTML5)return;const e=this;e.options.speed=e.config.speed.options,W(this.config.ratio)||Me.call(e),Object.defineProperty(e.media,"quality",{get(){const t=Le.getSources.call(e).find((t=>t.getAttribute("src")===e.source));return t&&Number(t.getAttribute("data-res"))},set(t){if(e.quality!==t){if(e.config.quality.forced&&j(e.config.quality.onChange))e.config.quality.onChange(t);else{const i=Le.getSources.call(e).find((e=>Number(e.getAttribute("data-res"))===t));if(!i)return;const{currentTime:s,paused:n,preload:a,readyState:l,playbackRate:o}=e.media;e.media.src=i.getAttribute("src"),("none"!==a||l)&&(e.once("loadedmetadata",(()=>{e.speed=o,e.currentTime=s,n||ke(e.play())})),e.media.load())}ve.call(e,e.media,"qualitychange",!1,{quality:t})}}})},cancelRequests(){this.isHTML5&&(te(Le.getSources.call(this)),this.media.setAttribute("src",this.config.blankVideo),this.media.load(),this.debug.log("Cancelled network requests"))}};function $e(e,...t){return W(e)?e:e.toString().replace(/{(\d+)}/g,((e,i)=>t[i].toString()))}const _e=(e="",t="",i="")=>e.replace(new RegExp(t.toString().replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1"),"g"),i.toString()),Oe=(e="")=>e.toString().replace(/\w\S*/g,(e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()));function je(e=""){let t=e.toString();return t=function(e=""){let t=e.toString();return t=_e(t,"-"," "),t=_e(t,"_"," "),t=Oe(t),_e(t," ","")}(t),t.charAt(0).toLowerCase()+t.slice(1)}function qe(e){const t=document.createElement("div");return t.appendChild(e),t.innerHTML}const De={pip:"PIP",airplay:"AirPlay",html5:"HTML5",vimeo:"Vimeo",youtube:"YouTube"},He={get(e="",t={}){if(W(e)||W(t))return"";let i=Q(t.i18n,e);if(W(i))return Object.keys(De).includes(e)?De[e]:"";const s={"{seektime}":t.seekTime,"{title}":t.title};return Object.entries(s).forEach((([e,t])=>{i=_e(i,e,t)})),i}};class Fe{constructor(t){e(this,"get",(e=>{if(!Fe.supported||!this.enabled)return null;const t=window.localStorage.getItem(this.key);if(W(t))return null;const i=JSON.parse(t);return _(e)&&e.length?i[e]:i})),e(this,"set",(e=>{if(!Fe.supported||!this.enabled)return;if(!L(e))return;let t=this.get();W(t)&&(t={}),X(t,e);try{window.localStorage.setItem(this.key,JSON.stringify(t))}catch(e){}})),this.enabled=t.config.storage.enabled,this.key=t.config.storage.key}static get supported(){try{if(!("localStorage"in window))return!1;const e="___test";return window.localStorage.setItem(e,e),window.localStorage.removeItem(e),!0}catch(e){return!1}}}function Re(e,t="text"){return new Promise(((i,s)=>{try{const s=new XMLHttpRequest;if(!("withCredentials"in s))return;s.addEventListener("load",(()=>{if("text"===t)try{i(JSON.parse(s.responseText))}catch(e){i(s.responseText)}else i(s.response)})),s.addEventListener("error",(()=>{throw new Error(s.status)})),s.open("GET",e,!0),s.responseType=t,s.send()}catch(e){s(e)}}))}function Ve(e,t){if(!_(e))return;const i=_(t);let s=!1;const n=()=>null!==document.getElementById(t),a=(e,t)=>{e.innerHTML=t,i&&n()||document.body.insertAdjacentElement("afterbegin",e)};if(!i||!n()){const n=Fe.supported,l=document.createElement("div");if(l.setAttribute("hidden",""),i&&l.setAttribute("id",t),n){const e=window.localStorage.getItem(`cache-${t}`);if(s=null!==e,s){const t=JSON.parse(e);a(l,t.content)}}Re(e).then((e=>{if(!W(e)){if(n)try{window.localStorage.setItem(`cache-${t}`,JSON.stringify({content:e}))}catch(e){}a(l,e)}})).catch((()=>{}))}}const Be=e=>Math.trunc(e/60/60%60,10);function Ue(e=0,t=!1,i=!1){if(!$(e))return Ue(void 0,t,i);const s=e=>`0${e}`.slice(-2);let n=Be(e);const a=(l=e,Math.trunc(l/60%60,10));var l;const o=(e=>Math.trunc(e%60,10))(e);return n=t||n>0?`${n}:`:"",`${i&&e>0?"-":""}${n}${s(a)}:${s(o)}`}const We={getIconUrl(){const e=new URL(this.config.iconUrl,window.location),t=window.location.host?window.location.host:window.top.location.host,i=e.host!==t||Y.isIE&&!window.svg4everybody;return{url:this.config.iconUrl,cors:i}},findElements(){try{return this.elements.controls=he.call(this,this.config.selectors.controls.wrapper),this.elements.buttons={play:ce.call(this,this.config.selectors.buttons.play),pause:he.call(this,this.config.selectors.buttons.pause),restart:he.call(this,this.config.selectors.buttons.restart),rewind:he.call(this,this.config.selectors.buttons.rewind),fastForward:he.call(this,this.config.selectors.buttons.fastForward),mute:he.call(this,this.config.selectors.buttons.mute),pip:he.call(this,this.config.selectors.buttons.pip),airplay:he.call(this,this.config.selectors.buttons.airplay),settings:he.call(this,this.config.selectors.buttons.settings),captions:he.call(this,this.config.selectors.buttons.captions),fullscreen:he.call(this,this.config.selectors.buttons.fullscreen)},this.elements.progress=he.call(this,this.config.selectors.progress),this.elements.inputs={seek:he.call(this,this.config.selectors.inputs.seek),volume:he.call(this,this.config.selectors.inputs.volume)},this.elements.display={buffer:he.call(this,this.config.selectors.display.buffer),currentTime:he.call(this,this.config.selectors.display.currentTime),duration:he.call(this,this.config.selectors.display.duration)},H(this.elements.progress)&&(this.elements.display.seekTooltip=this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`)),!0}catch(e){return this.debug.warn("It looks like there is a problem with your custom controls HTML",e),this.toggleNativeControls(!0),!1}},createIcon(e,t){const i="http://www.w3.org/2000/svg",s=We.getIconUrl.call(this),n=`${s.cors?"":s.url}#${this.config.iconPrefix}`,a=document.createElementNS(i,"svg");G(a,X(t,{"aria-hidden":"true",focusable:"false"}));const l=document.createElementNS(i,"use"),o=`${n}-${e}`;return"href"in l&&l.setAttributeNS("http://www.w3.org/1999/xlink","href",o),l.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",o),a.appendChild(l),a},createLabel(e,t={}){const i=He.get(e,this.config);return Z("span",{...t,class:[t.class,this.config.classNames.hidden].filter(Boolean).join(" ")},i)},createBadge(e){if(W(e))return null;const t=Z("span",{class:this.config.classNames.menu.value});return t.appendChild(Z("span",{class:this.config.classNames.menu.badge},e)),t},createButton(e,t){const i=X({},t);let s=je(e);const n={element:"button",toggle:!1,label:null,icon:null,labelPressed:null,iconPressed:null};switch(["element","icon","label"].forEach((e=>{Object.keys(i).includes(e)&&(n[e]=i[e],delete i[e])})),"button"!==n.element||Object.keys(i).includes("type")||(i.type="button"),Object.keys(i).includes("class")?i.class.split(" ").some((e=>e===this.config.classNames.control))||X(i,{class:`${i.class} ${this.config.classNames.control}`}):i.class=this.config.classNames.control,e){case"play":n.toggle=!0,n.label="play",n.labelPressed="pause",n.icon="play",n.iconPressed="pause";break;case"mute":n.toggle=!0,n.label="mute",n.labelPressed="unmute",n.icon="volume",n.iconPressed="muted";break;case"captions":n.toggle=!0,n.label="enableCaptions",n.labelPressed="disableCaptions",n.icon="captions-off",n.iconPressed="captions-on";break;case"fullscreen":n.toggle=!0,n.label="enterFullscreen",n.labelPressed="exitFullscreen",n.icon="enter-fullscreen",n.iconPressed="exit-fullscreen";break;case"play-large":i.class+=` ${this.config.classNames.control}--overlaid`,s="play",n.label="play",n.icon="play";break;default:W(n.label)&&(n.label=s),W(n.icon)&&(n.icon=e)}const a=Z(n.element);return n.toggle?(a.appendChild(We.createIcon.call(this,n.iconPressed,{class:"icon--pressed"})),a.appendChild(We.createIcon.call(this,n.icon,{class:"icon--not-pressed"})),a.appendChild(We.createLabel.call(this,n.labelPressed,{class:"label--pressed"})),a.appendChild(We.createLabel.call(this,n.label,{class:"label--not-pressed"}))):(a.appendChild(We.createIcon.call(this,n.icon)),a.appendChild(We.createLabel.call(this,n.label))),X(i,ne(this.config.selectors.buttons[s],i)),G(a,i),"play"===s?(q(this.elements.buttons[s])||(this.elements.buttons[s]=[]),this.elements.buttons[s].push(a)):this.elements.buttons[s]=a,a},createRange(e,t){const i=Z("input",X(ne(this.config.selectors.inputs[e]),{type:"range",min:0,max:100,step:.01,value:0,autocomplete:"off",role:"slider","aria-label":He.get(e,this.config),"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":0},t));return this.elements.inputs[e]=i,We.updateRangeFill.call(this,i),T.setup(i),i},createProgress(e,t){const i=Z("progress",X(ne(this.config.selectors.display[e]),{min:0,max:100,value:0,role:"progressbar","aria-hidden":!0},t));if("volume"!==e){i.appendChild(Z("span",null,"0"));const t={played:"played",buffer:"buffered"}[e],s=t?He.get(t,this.config):"";i.innerText=`% ${s.toLowerCase()}`}return this.elements.display[e]=i,i},createTime(e,t){const i=ne(this.config.selectors.display[e],t),s=Z("div",X(i,{class:`${i.class?i.class:""} ${this.config.classNames.display.time} `.trim(),"aria-label":He.get(e,this.config)}),"00:00");return this.elements.display[e]=s,s},bindMenuItemShortcuts(e,t){fe.call(this,e,"keydown keyup",(i=>{if(![32,38,39,40].includes(i.which))return;if(i.preventDefault(),i.stopPropagation(),"keydown"===i.type)return;const s=re(e,'[role="menuitemradio"]');if(!s&&[32,39].includes(i.which))We.showMenuPanel.call(this,t,!0);else{let t;32!==i.which&&(40===i.which||s&&39===i.which?(t=e.nextElementSibling,H(t)||(t=e.parentNode.firstElementChild)):(t=e.previousElementSibling,H(t)||(t=e.parentNode.lastElementChild)),ue.call(this,t,!0))}}),!1),fe.call(this,e,"keyup",(e=>{13===e.which&&We.focusFirstMenuItem.call(this,null,!0)}))},createMenuItem({value:e,list:t,type:i,title:s,badge:n=null,checked:a=!1}){const l=ne(this.config.selectors.inputs[i]),o=Z("button",X(l,{type:"button",role:"menuitemradio",class:`${this.config.classNames.control} ${l.class?l.class:""}`.trim(),"aria-checked":a,value:e})),r=Z("span");r.innerHTML=s,H(n)&&r.appendChild(n),o.appendChild(r),Object.defineProperty(o,"checked",{enumerable:!0,get:()=>"true"===o.getAttribute("aria-checked"),set(e){e&&Array.from(o.parentNode.children).filter((e=>re(e,'[role="menuitemradio"]'))).forEach((e=>e.setAttribute("aria-checked","false"))),o.setAttribute("aria-checked",e?"true":"false")}}),this.listeners.bind(o,"click keyup",(t=>{if(!R(t)||32===t.which){switch(t.preventDefault(),t.stopPropagation(),o.checked=!0,i){case"language":this.currentTrack=Number(e);break;case"quality":this.quality=e;break;case"speed":this.speed=parseFloat(e)}We.showMenuPanel.call(this,"home",R(t))}}),i,!1),We.bindMenuItemShortcuts.call(this,o,i),t.appendChild(o)},formatTime(e=0,t=!1){if(!$(e))return e;return Ue(e,Be(this.duration)>0,t)},updateTimeDisplay(e=null,t=0,i=!1){H(e)&&$(t)&&(e.innerText=We.formatTime(t,i))},updateVolume(){this.supported.ui&&(H(this.elements.inputs.volume)&&We.setRange.call(this,this.elements.inputs.volume,this.muted?0:this.volume),H(this.elements.buttons.mute)&&(this.elements.buttons.mute.pressed=this.muted||0===this.volume))},setRange(e,t=0){H(e)&&(e.value=t,We.updateRangeFill.call(this,e))},updateProgress(e){if(!this.supported.ui||!F(e))return;let t=0;const i=(e,t)=>{const i=$(t)?t:0,s=H(e)?e:this.elements.display.buffer;if(H(s)){s.value=i;const e=s.getElementsByTagName("span")[0];H(e)&&(e.childNodes[0].nodeValue=i)}};if(e)switch(e.type){case"timeupdate":case"seeking":case"seeked":s=this.currentTime,n=this.duration,t=0===s||0===n||Number.isNaN(s)||Number.isNaN(n)?0:(s/n*100).toFixed(2),"timeupdate"===e.type&&We.setRange.call(this,this.elements.inputs.seek,t);break;case"playing":case"progress":i(this.elements.display.buffer,100*this.buffered)}var s,n},updateRangeFill(e){const t=F(e)?e.target:e;if(H(t)&&"range"===t.getAttribute("type")){if(re(t,this.config.selectors.inputs.seek)){t.setAttribute("aria-valuenow",this.currentTime);const e=We.formatTime(this.currentTime),i=We.formatTime(this.duration),s=He.get("seekLabel",this.config);t.setAttribute("aria-valuetext",s.replace("{currentTime}",e).replace("{duration}",i))}else if(re(t,this.config.selectors.inputs.volume)){const e=100*t.value;t.setAttribute("aria-valuenow",e),t.setAttribute("aria-valuetext",`${e.toFixed(1)}%`)}else t.setAttribute("aria-valuenow",t.value);Y.isWebkit&&t.style.setProperty("--value",t.value/t.max*100+"%")}},updateSeekTooltip(e){if(!this.config.tooltips.seek||!H(this.elements.inputs.seek)||!H(this.elements.display.seekTooltip)||0===this.duration)return;const t=`${this.config.classNames.tooltip}--visible`,i=e=>le(this.elements.display.seekTooltip,t,e);if(this.touch)return void i(!1);let s=0;const n=this.elements.progress.getBoundingClientRect();if(F(e))s=100/n.width*(e.pageX-n.left);else{if(!oe(this.elements.display.seekTooltip,t))return;s=parseFloat(this.elements.display.seekTooltip.style.left,10)}s<0?s=0:s>100&&(s=100),We.updateTimeDisplay.call(this,this.elements.display.seekTooltip,this.duration/100*s),this.elements.display.seekTooltip.style.left=`${s}%`,F(e)&&["mouseenter","mouseleave"].includes(e.type)&&i("mouseenter"===e.type)},timeUpdate(e){const t=!H(this.elements.display.duration)&&this.config.invertTime;We.updateTimeDisplay.call(this,this.elements.display.currentTime,t?this.duration-this.currentTime:this.currentTime,t),e&&"timeupdate"===e.type&&this.media.seeking||We.updateProgress.call(this,e)},durationUpdate(){if(!this.supported.ui||!this.config.invertTime&&this.currentTime)return;if(this.duration>=2**32)return ae(this.elements.display.currentTime,!0),void ae(this.elements.progress,!0);H(this.elements.inputs.seek)&&this.elements.inputs.seek.setAttribute("aria-valuemax",this.duration);const e=H(this.elements.display.duration);!e&&this.config.displayDuration&&this.paused&&We.updateTimeDisplay.call(this,this.elements.display.currentTime,this.duration),e&&We.updateTimeDisplay.call(this,this.elements.display.duration,this.duration),We.updateSeekTooltip.call(this)},toggleMenuButton(e,t){ae(this.elements.settings.buttons[e],!t)},updateSetting(e,t,i){const s=this.elements.settings.panels[e];let n=null,a=t;if("captions"===e)n=this.currentTrack;else{if(n=W(i)?this[e]:i,W(n)&&(n=this.config[e].default),!W(this.options[e])&&!this.options[e].includes(n))return void this.debug.warn(`Unsupported value of '${n}' for ${e}`);if(!this.config[e].options.includes(n))return void this.debug.warn(`Disabled value of '${n}' for ${e}`)}if(H(a)||(a=s&&s.querySelector('[role="menu"]')),!H(a))return;this.elements.settings.buttons[e].querySelector(`.${this.config.classNames.menu.value}`).innerHTML=We.getLabel.call(this,e,n);const l=a&&a.querySelector(`[value="${n}"]`);H(l)&&(l.checked=!0)},getLabel(e,t){switch(e){case"speed":return 1===t?He.get("normal",this.config):`${t}×`;case"quality":if($(t)){const e=He.get(`qualityLabel.${t}`,this.config);return e.length?e:`${t}p`}return Oe(t);case"captions":return Ye.getLabel.call(this);default:return null}},setQualityMenu(e){if(!H(this.elements.settings.panels.quality))return;const t="quality",i=this.elements.settings.panels.quality.querySelector('[role="menu"]');q(e)&&(this.options.quality=Ce(e).filter((e=>this.config.quality.options.includes(e))));const s=!W(this.options.quality)&&this.options.quality.length>1;if(We.toggleMenuButton.call(this,t,s),ie(i),We.checkMenu.call(this),!s)return;const n=e=>{const t=He.get(`qualityBadge.${e}`,this.config);return t.length?We.createBadge.call(this,t):null};this.options.quality.sort(((e,t)=>{const i=this.config.quality.options;return i.indexOf(e)>i.indexOf(t)?1:-1})).forEach((e=>{We.createMenuItem.call(this,{value:e,list:i,type:t,title:We.getLabel.call(this,"quality",e),badge:n(e)})})),We.updateSetting.call(this,t,i)},setCaptionsMenu(){if(!H(this.elements.settings.panels.captions))return;const e="captions",t=this.elements.settings.panels.captions.querySelector('[role="menu"]'),i=Ye.getTracks.call(this),s=Boolean(i.length);if(We.toggleMenuButton.call(this,e,s),ie(t),We.checkMenu.call(this),!s)return;const n=i.map(((e,i)=>({value:i,checked:this.captions.toggled&&this.currentTrack===i,title:Ye.getLabel.call(this,e),badge:e.language&&We.createBadge.call(this,e.language.toUpperCase()),list:t,type:"language"})));n.unshift({value:-1,checked:!this.captions.toggled,title:He.get("disabled",this.config),list:t,type:"language"}),n.forEach(We.createMenuItem.bind(this)),We.updateSetting.call(this,e,t)},setSpeedMenu(){if(!H(this.elements.settings.panels.speed))return;const e="speed",t=this.elements.settings.panels.speed.querySelector('[role="menu"]');this.options.speed=this.options.speed.filter((e=>e>=this.minimumSpeed&&e<=this.maximumSpeed));const i=!W(this.options.speed)&&this.options.speed.length>1;We.toggleMenuButton.call(this,e,i),ie(t),We.checkMenu.call(this),i&&(this.options.speed.forEach((i=>{We.createMenuItem.call(this,{value:i,list:t,type:e,title:We.getLabel.call(this,"speed",i)})})),We.updateSetting.call(this,e,t))},checkMenu(){const{buttons:e}=this.elements.settings,t=!W(e)&&Object.values(e).some((e=>!e.hidden));ae(this.elements.settings.menu,!t)},focusFirstMenuItem(e,t=!1){if(this.elements.settings.popup.hidden)return;let i=e;H(i)||(i=Object.values(this.elements.settings.panels).find((e=>!e.hidden)));const s=i.querySelector('[role^="menuitem"]');ue.call(this,s,t)},toggleMenu(e){const{popup:t}=this.elements.settings,i=this.elements.buttons.settings;if(!H(t)||!H(i))return;const{hidden:s}=t;let n=s;if(O(e))n=e;else if(R(e)&&27===e.which)n=!1;else if(F(e)){const s=j(e.composedPath)?e.composedPath()[0]:e.target,a=t.contains(s);if(a||!a&&e.target!==i&&n)return}i.setAttribute("aria-expanded",n),ae(t,!n),le(this.elements.container,this.config.classNames.menu.open,n),n&&R(e)?We.focusFirstMenuItem.call(this,null,!0):n||s||ue.call(this,i,R(e))},getMenuSize(e){const t=e.cloneNode(!0);t.style.position="absolute",t.style.opacity=0,t.removeAttribute("hidden"),e.parentNode.appendChild(t);const i=t.scrollWidth,s=t.scrollHeight;return te(t),{width:i,height:s}},showMenuPanel(e="",t=!1){const i=this.elements.container.querySelector(`#plyr-settings-${this.id}-${e}`);if(!H(i))return;const s=i.parentNode,n=Array.from(s.children).find((e=>!e.hidden));if(me.transitions&&!me.reducedMotion){s.style.width=`${n.scrollWidth}px`,s.style.height=`${n.scrollHeight}px`;const e=We.getMenuSize.call(this,i),t=e=>{e.target===s&&["width","height"].includes(e.propertyName)&&(s.style.width="",s.style.height="",be.call(this,s,z,t))};fe.call(this,s,z,t),s.style.width=`${e.width}px`,s.style.height=`${e.height}px`}ae(n,!0),ae(i,!1),We.focusFirstMenuItem.call(this,i,t)},setDownloadUrl(){const e=this.elements.buttons.download;H(e)&&e.setAttribute("href",this.download)},create(e){const{bindMenuItemShortcuts:t,createButton:i,createProgress:s,createRange:n,createTime:a,setQualityMenu:l,setSpeedMenu:o,showMenuPanel:r}=We;this.elements.controls=null,q(this.config.controls)&&this.config.controls.includes("play-large")&&this.elements.container.appendChild(i.call(this,"play-large"));const c=Z("div",ne(this.config.selectors.controls.wrapper));this.elements.controls=c;const h={class:"plyr__controls__item"};return Ce(q(this.config.controls)?this.config.controls:[]).forEach((l=>{if("restart"===l&&c.appendChild(i.call(this,"restart",h)),"rewind"===l&&c.appendChild(i.call(this,"rewind",h)),"play"===l&&c.appendChild(i.call(this,"play",h)),"fast-forward"===l&&c.appendChild(i.call(this,"fast-forward",h)),"progress"===l){const t=Z("div",{class:`${h.class} plyr__progress__container`}),i=Z("div",ne(this.config.selectors.progress));if(i.appendChild(n.call(this,"seek",{id:`plyr-seek-${e.id}`})),i.appendChild(s.call(this,"buffer")),this.config.tooltips.seek){const e=Z("span",{class:this.config.classNames.tooltip},"00:00");i.appendChild(e),this.elements.display.seekTooltip=e}this.elements.progress=i,t.appendChild(this.elements.progress),c.appendChild(t)}if("current-time"===l&&c.appendChild(a.call(this,"currentTime",h)),"duration"===l&&c.appendChild(a.call(this,"duration",h)),"mute"===l||"volume"===l){let{volume:t}=this.elements;if(H(t)&&c.contains(t)||(t=Z("div",X({},h,{class:`${h.class} plyr__volume`.trim()})),this.elements.volume=t,c.appendChild(t)),"mute"===l&&t.appendChild(i.call(this,"mute")),"volume"===l&&!Y.isIos){const i={max:1,step:.05,value:this.config.volume};t.appendChild(n.call(this,"volume",X(i,{id:`plyr-volume-${e.id}`})))}}if("captions"===l&&c.appendChild(i.call(this,"captions",h)),"settings"===l&&!W(this.config.settings)){const s=Z("div",X({},h,{class:`${h.class} plyr__menu`.trim(),hidden:""}));s.appendChild(i.call(this,"settings",{"aria-haspopup":!0,"aria-controls":`plyr-settings-${e.id}`,"aria-expanded":!1}));const n=Z("div",{class:"plyr__menu__container",id:`plyr-settings-${e.id}`,hidden:""}),a=Z("div"),l=Z("div",{id:`plyr-settings-${e.id}-home`}),o=Z("div",{role:"menu"});l.appendChild(o),a.appendChild(l),this.elements.settings.panels.home=l,this.config.settings.forEach((i=>{const s=Z("button",X(ne(this.config.selectors.buttons.settings),{type:"button",class:`${this.config.classNames.control} ${this.config.classNames.control}--forward`,role:"menuitem","aria-haspopup":!0,hidden:""}));t.call(this,s,i),fe.call(this,s,"click",(()=>{r.call(this,i,!1)}));const n=Z("span",null,He.get(i,this.config)),l=Z("span",{class:this.config.classNames.menu.value});l.innerHTML=e[i],n.appendChild(l),s.appendChild(n),o.appendChild(s);const c=Z("div",{id:`plyr-settings-${e.id}-${i}`,hidden:""}),h=Z("button",{type:"button",class:`${this.config.classNames.control} ${this.config.classNames.control}--back`});h.appendChild(Z("span",{"aria-hidden":!0},He.get(i,this.config))),h.appendChild(Z("span",{class:this.config.classNames.hidden},He.get("menuBack",this.config))),fe.call(this,c,"keydown",(e=>{37===e.which&&(e.preventDefault(),e.stopPropagation(),r.call(this,"home",!0))}),!1),fe.call(this,h,"click",(()=>{r.call(this,"home",!1)})),c.appendChild(h),c.appendChild(Z("div",{role:"menu"})),a.appendChild(c),this.elements.settings.buttons[i]=s,this.elements.settings.panels[i]=c})),n.appendChild(a),s.appendChild(n),c.appendChild(s),this.elements.settings.popup=n,this.elements.settings.menu=s}if("pip"===l&&me.pip&&c.appendChild(i.call(this,"pip",h)),"airplay"===l&&me.airplay&&c.appendChild(i.call(this,"airplay",h)),"download"===l){const e=X({},h,{element:"a",href:this.download,target:"_blank"});this.isHTML5&&(e.download="");const{download:t}=this.config.urls;!U(t)&&this.isEmbed&&X(e,{icon:`logo-${this.provider}`,label:this.provider}),c.appendChild(i.call(this,"download",e))}"fullscreen"===l&&c.appendChild(i.call(this,"fullscreen",h))})),this.isHTML5&&l.call(this,Le.getQualityOptions.call(this)),o.call(this),c},inject(){if(this.config.loadSprite){const e=We.getIconUrl.call(this);e.cors&&Ve(e.url,"sprite-plyr")}this.id=Math.floor(1e4*Math.random());let e=null;this.elements.controls=null;const t={id:this.id,seektime:this.config.seekTime,title:this.config.title};let i=!0;j(this.config.controls)&&(this.config.controls=this.config.controls.call(this,t)),this.config.controls||(this.config.controls=[]),H(this.config.controls)||_(this.config.controls)?e=this.config.controls:(e=We.create.call(this,{id:this.id,seektime:this.config.seekTime,speed:this.speed,quality:this.quality,captions:Ye.getLabel.call(this)}),i=!1);let s;i&&_(this.config.controls)&&(e=(e=>{let i=e;return Object.entries(t).forEach((([e,t])=>{i=_e(i,`{${e}}`,t)})),i})(e)),_(this.config.selectors.controls.container)&&(s=document.querySelector(this.config.selectors.controls.container)),H(s)||(s=this.elements.container);if(s[H(e)?"insertAdjacentElement":"insertAdjacentHTML"]("afterbegin",e),H(this.elements.controls)||We.findElements.call(this),!W(this.elements.buttons)){const e=e=>{const t=this.config.classNames.controlPressed;Object.defineProperty(e,"pressed",{enumerable:!0,get:()=>oe(e,t),set(i=!1){le(e,t,i)}})};Object.values(this.elements.buttons).filter(Boolean).forEach((t=>{q(t)||D(t)?Array.from(t).filter(Boolean).forEach(e):e(t)}))}if(Y.isEdge&&K(s),this.config.tooltips.controls){const{classNames:e,selectors:t}=this.config,i=`${t.controls.wrapper} ${t.labels} .${e.hidden}`,s=ce.call(this,i);Array.from(s).forEach((e=>{le(e,this.config.classNames.hidden,!1),le(e,this.config.classNames.tooltip,!0)}))}}};function ze(e,t=!0){let i=e;if(t){const e=document.createElement("a");e.href=i,i=e.href}try{return new URL(i)}catch(e){return null}}function Ke(e){const t=new URLSearchParams;return L(e)&&Object.entries(e).forEach((([e,i])=>{t.set(e,i)})),t}const Ye={setup(){if(!this.supported.ui)return;if(!this.isVideo||this.isYouTube||this.isHTML5&&!me.textTracks)return void(q(this.config.controls)&&this.config.controls.includes("settings")&&this.config.settings.includes("captions")&&We.setCaptionsMenu.call(this));var e,t;if(H(this.elements.captions)||(this.elements.captions=Z("div",ne(this.config.selectors.captions)),e=this.elements.captions,t=this.elements.wrapper,H(e)&&H(t)&&t.parentNode.insertBefore(e,t.nextSibling)),Y.isIE&&window.URL){const e=this.media.querySelectorAll("track");Array.from(e).forEach((e=>{const t=e.getAttribute("src"),i=ze(t);null!==i&&i.hostname!==window.location.href.hostname&&["http:","https:"].includes(i.protocol)&&Re(t,"blob").then((t=>{e.setAttribute("src",window.URL.createObjectURL(t))})).catch((()=>{te(e)}))}))}const i=Ce((navigator.languages||[navigator.language||navigator.userLanguage||"en"]).map((e=>e.split("-")[0])));let s=(this.storage.get("language")||this.config.captions.language||"auto").toLowerCase();"auto"===s&&([s]=i);let n=this.storage.get("captions");if(O(n)||({active:n}=this.config.captions),Object.assign(this.captions,{toggled:!1,active:n,language:s,languages:i}),this.isHTML5){const e=this.config.captions.update?"addtrack removetrack":"removetrack";fe.call(this,this.media.textTracks,e,Ye.update.bind(this))}setTimeout(Ye.update.bind(this),0)},update(){const e=Ye.getTracks.call(this,!0),{active:t,language:i,meta:s,currentTrackNode:n}=this.captions,a=Boolean(e.find((e=>e.language===i)));this.isHTML5&&this.isVideo&&e.filter((e=>!s.get(e))).forEach((e=>{this.debug.log("Track added",e),s.set(e,{default:"showing"===e.mode}),"showing"===e.mode&&(e.mode="hidden"),fe.call(this,e,"cuechange",(()=>Ye.updateCues.call(this)))})),(a&&this.language!==i||!e.includes(n))&&(Ye.setLanguage.call(this,i),Ye.toggle.call(this,t&&a)),this.elements&&le(this.elements.container,this.config.classNames.captions.enabled,!W(e)),q(this.config.controls)&&this.config.controls.includes("settings")&&this.config.settings.includes("captions")&&We.setCaptionsMenu.call(this)},toggle(e,t=!0){if(!this.supported.ui)return;const{toggled:i}=this.captions,s=this.config.classNames.captions.active,n=I(e)?!i:e;if(n!==i){if(t||(this.captions.active=n,this.storage.set({captions:n})),!this.language&&n&&!t){const e=Ye.getTracks.call(this),t=Ye.findTrack.call(this,[this.captions.language,...this.captions.languages],!0);return this.captions.language=t.language,void Ye.set.call(this,e.indexOf(t))}this.elements.buttons.captions&&(this.elements.buttons.captions.pressed=n),le(this.elements.container,s,n),this.captions.toggled=n,We.updateSetting.call(this,"captions"),ve.call(this,this.media,n?"captionsenabled":"captionsdisabled")}setTimeout((()=>{n&&this.captions.toggled&&(this.captions.currentTrackNode.mode="hidden")}))},set(e,t=!0){const i=Ye.getTracks.call(this);if(-1!==e)if($(e))if(e in i){if(this.captions.currentTrack!==e){this.captions.currentTrack=e;const s=i[e],{language:n}=s||{};this.captions.currentTrackNode=s,We.updateSetting.call(this,"captions"),t||(this.captions.language=n,this.storage.set({language:n})),this.isVimeo&&this.embed.enableTextTrack(n),ve.call(this,this.media,"languagechange")}Ye.toggle.call(this,!0,t),this.isHTML5&&this.isVideo&&Ye.updateCues.call(this)}else this.debug.warn("Track not found",e);else this.debug.warn("Invalid caption argument",e);else Ye.toggle.call(this,!1,t)},setLanguage(e,t=!0){if(!_(e))return void this.debug.warn("Invalid language argument",e);const i=e.toLowerCase();this.captions.language=i;const s=Ye.getTracks.call(this),n=Ye.findTrack.call(this,[i]);Ye.set.call(this,s.indexOf(n),t)},getTracks(e=!1){return Array.from((this.media||{}).textTracks||[]).filter((t=>!this.isHTML5||e||this.captions.meta.has(t))).filter((e=>["captions","subtitles"].includes(e.kind)))},findTrack(e,t=!1){const i=Ye.getTracks.call(this),s=e=>Number((this.captions.meta.get(e)||{}).default),n=Array.from(i).sort(((e,t)=>s(t)-s(e)));let a;return e.every((e=>(a=n.find((t=>t.language===e)),!a))),a||(t?n[0]:void 0)},getCurrentTrack(){return Ye.getTracks.call(this)[this.currentTrack]},getLabel(e){let t=e;return!V(t)&&me.textTracks&&this.captions.toggled&&(t=Ye.getCurrentTrack.call(this)),V(t)?W(t.label)?W(t.language)?He.get("enabled",this.config):e.language.toUpperCase():t.label:He.get("disabled",this.config)},updateCues(e){if(!this.supported.ui)return;if(!H(this.elements.captions))return void this.debug.warn("No captions element to render to");if(!I(e)&&!Array.isArray(e))return void this.debug.warn("updateCues: Invalid input",e);let t=e;if(!t){const e=Ye.getCurrentTrack.call(this);t=Array.from((e||{}).activeCues||[]).map((e=>e.getCueAsHTML())).map(qe)}const i=t.map((e=>e.trim())).join("\n");if(i!==this.elements.captions.innerHTML){ie(this.elements.captions);const e=Z("span",ne(this.config.selectors.caption));e.innerHTML=i,this.elements.captions.appendChild(e),ve.call(this,this.media,"cuechange")}}},Qe={enabled:!0,title:"",debug:!1,autoplay:!1,autopause:!0,playsinline:!0,seekTime:10,volume:1,muted:!1,duration:null,displayDuration:!0,invertTime:!0,toggleInvert:!0,ratio:null,clickToPlay:!0,hideControls:!0,resetOnEnd:!1,disableContextMenu:!0,loadSprite:!0,iconPrefix:"plyr",iconUrl:"https://cdn.plyr.io/3.6.12/plyr.svg",blankVideo:"https://cdn.plyr.io/static/blank.mp4",quality:{default:576,options:[4320,2880,2160,1440,1080,720,576,480,360,240],forced:!1,onChange:null},loop:{active:!1},speed:{selected:1,options:[.5,.75,1,1.25,1.5,1.75,2,4]},keyboard:{focused:!0,global:!1},tooltips:{controls:!1,seek:!0},captions:{active:!1,language:"auto",update:!1},fullscreen:{enabled:!0,fallback:!0,iosNative:!1},storage:{enabled:!0,key:"plyr"},controls:["play-large","play","progress","current-time","mute","volume","captions","settings","pip","airplay","fullscreen"],settings:["captions","quality","speed"],i18n:{restart:"Restart",rewind:"Rewind {seektime}s",play:"Play",pause:"Pause",fastForward:"Forward {seektime}s",seek:"Seek",seekLabel:"{currentTime} of {duration}",played:"Played",buffered:"Buffered",currentTime:"Current time",duration:"Duration",volume:"Volume",mute:"Mute",unmute:"Unmute",enableCaptions:"Enable captions",disableCaptions:"Disable captions",download:"Download",enterFullscreen:"Enter fullscreen",exitFullscreen:"Exit fullscreen",frameTitle:"Player for {title}",captions:"Captions",settings:"Settings",pip:"PIP",menuBack:"Go back to previous menu",speed:"Speed",normal:"Normal",quality:"Quality",loop:"Loop",start:"Start",end:"End",all:"All",reset:"Reset",disabled:"Disabled",enabled:"Enabled",advertisement:"Ad",qualityBadge:{2160:"4K",1440:"HD",1080:"HD",720:"HD",576:"SD",480:"SD"}},urls:{download:null,vimeo:{sdk:"https://player.vimeo.com/api/player.js",iframe:"https://player.vimeo.com/video/{0}?{1}",api:"https://vimeo.com/api/oembed.json?url={0}"},youtube:{sdk:"https://www.youtube.com/iframe_api",api:"https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}"},googleIMA:{sdk:"https://imasdk.googleapis.com/js/sdkloader/ima3.js"}},listeners:{seek:null,play:null,pause:null,restart:null,rewind:null,fastForward:null,mute:null,volume:null,captions:null,download:null,fullscreen:null,pip:null,airplay:null,speed:null,quality:null,loop:null,language:null},events:["ended","progress","stalled","playing","waiting","canplay","canplaythrough","loadstart","loadeddata","loadedmetadata","timeupdate","volumechange","play","pause","error","seeking","seeked","emptied","ratechange","cuechange","download","enterfullscreen","exitfullscreen","captionsenabled","captionsdisabled","languagechange","controlshidden","controlsshown","ready","statechange","qualitychange","adsloaded","adscontentpause","adscontentresume","adstarted","adsmidpoint","adscomplete","adsallcomplete","adsimpression","adsclick"],selectors:{editable:"input, textarea, select, [contenteditable]",container:".plyr",controls:{container:null,wrapper:".plyr__controls"},labels:"[data-plyr]",buttons:{play:'[data-plyr="play"]',pause:'[data-plyr="pause"]',restart:'[data-plyr="restart"]',rewind:'[data-plyr="rewind"]',fastForward:'[data-plyr="fast-forward"]',mute:'[data-plyr="mute"]',captions:'[data-plyr="captions"]',download:'[data-plyr="download"]',fullscreen:'[data-plyr="fullscreen"]',pip:'[data-plyr="pip"]',airplay:'[data-plyr="airplay"]',settings:'[data-plyr="settings"]',loop:'[data-plyr="loop"]'},inputs:{seek:'[data-plyr="seek"]',volume:'[data-plyr="volume"]',speed:'[data-plyr="speed"]',language:'[data-plyr="language"]',quality:'[data-plyr="quality"]'},display:{currentTime:".plyr__time--current",duration:".plyr__time--duration",buffer:".plyr__progress__buffer",loop:".plyr__progress__loop",volume:".plyr__volume--display"},progress:".plyr__progress",captions:".plyr__captions",caption:".plyr__caption"},classNames:{type:"plyr--{0}",provider:"plyr--{0}",video:"plyr__video-wrapper",embed:"plyr__video-embed",videoFixedRatio:"plyr__video-wrapper--fixed-ratio",embedContainer:"plyr__video-embed__container",poster:"plyr__poster",posterEnabled:"plyr__poster-enabled",ads:"plyr__ads",control:"plyr__control",controlPressed:"plyr__control--pressed",playing:"plyr--playing",paused:"plyr--paused",stopped:"plyr--stopped",loading:"plyr--loading",hover:"plyr--hover",tooltip:"plyr__tooltip",cues:"plyr__cues",hidden:"plyr__sr-only",hideControls:"plyr--hide-controls",isIos:"plyr--is-ios",isTouch:"plyr--is-touch",uiSupported:"plyr--full-ui",noTransition:"plyr--no-transition",display:{time:"plyr__time"},menu:{value:"plyr__menu__value",badge:"plyr__badge",open:"plyr--menu-open"},captions:{enabled:"plyr--captions-enabled",active:"plyr--captions-active"},fullscreen:{enabled:"plyr--fullscreen-enabled",fallback:"plyr--fullscreen-fallback"},pip:{supported:"plyr--pip-supported",active:"plyr--pip-active"},airplay:{supported:"plyr--airplay-supported",active:"plyr--airplay-active"},tabFocus:"plyr__tab-focus",previewThumbnails:{thumbContainer:"plyr__preview-thumb",thumbContainerShown:"plyr__preview-thumb--is-shown",imageContainer:"plyr__preview-thumb__image-container",timeContainer:"plyr__preview-thumb__time-container",scrubbingContainer:"plyr__preview-scrubbing",scrubbingContainerShown:"plyr__preview-scrubbing--is-shown"}},attributes:{embed:{provider:"data-plyr-provider",id:"data-plyr-embed-id",hash:"data-plyr-embed-hash"}},ads:{enabled:!1,publisherId:"",tagUrl:""},previewThumbnails:{enabled:!1,src:""},vimeo:{byline:!1,portrait:!1,title:!1,speed:!0,transparent:!1,customControls:!0,referrerPolicy:null,premium:!1},youtube:{rel:0,showinfo:0,iv_load_policy:3,modestbranding:1,customControls:!0,noCookie:!1}},Xe="picture-in-picture",Je="inline",Ge={html5:"html5",youtube:"youtube",vimeo:"vimeo"},Ze="audio",et="video";const tt=()=>{};class it{constructor(e=!1){this.enabled=window.console&&e,this.enabled&&this.log("Debugging enabled")}get log(){return this.enabled?Function.prototype.bind.call(console.log,console):tt}get warn(){return this.enabled?Function.prototype.bind.call(console.warn,console):tt}get error(){return this.enabled?Function.prototype.bind.call(console.error,console):tt}}class st{constructor(t){e(this,"onChange",(()=>{if(!this.enabled)return;const e=this.player.elements.buttons.fullscreen;H(e)&&(e.pressed=this.active);const t=this.target===this.player.media?this.target:this.player.elements.container;ve.call(this.player,t,this.active?"enterfullscreen":"exitfullscreen",!0)})),e(this,"toggleFallback",((e=!1)=>{if(e?this.scrollPosition={x:window.scrollX||0,y:window.scrollY||0}:window.scrollTo(this.scrollPosition.x,this.scrollPosition.y),document.body.style.overflow=e?"hidden":"",le(this.target,this.player.config.classNames.fullscreen.fallback,e),Y.isIos){let t=document.head.querySelector('meta[name="viewport"]');const i="viewport-fit=cover";t||(t=document.createElement("meta"),t.setAttribute("name","viewport"));const s=_(t.content)&&t.content.includes(i);e?(this.cleanupViewport=!s,s||(t.content+=`,${i}`)):this.cleanupViewport&&(t.content=t.content.split(",").filter((e=>e.trim()!==i)).join(","))}this.onChange()})),e(this,"trapFocus",(e=>{if(Y.isIos||!this.active||"Tab"!==e.key||9!==e.keyCode)return;const t=document.activeElement,i=ce.call(this.player,"a[href], button:not(:disabled), input:not(:disabled), [tabindex]"),[s]=i,n=i[i.length-1];t!==n||e.shiftKey?t===s&&e.shiftKey&&(n.focus(),e.preventDefault()):(s.focus(),e.preventDefault())})),e(this,"update",(()=>{if(this.enabled){let e;e=this.forceFallback?"Fallback (forced)":st.native?"Native":"Fallback",this.player.debug.log(`${e} fullscreen enabled`)}else this.player.debug.log("Fullscreen not supported and fallback disabled");le(this.player.elements.container,this.player.config.classNames.fullscreen.enabled,this.enabled)})),e(this,"enter",(()=>{this.enabled&&(Y.isIos&&this.player.config.fullscreen.iosNative?this.player.isVimeo?this.player.embed.requestFullscreen():this.target.webkitEnterFullscreen():!st.native||this.forceFallback?this.toggleFallback(!0):this.prefix?W(this.prefix)||this.target[`${this.prefix}Request${this.property}`]():this.target.requestFullscreen({navigationUI:"hide"}))})),e(this,"exit",(()=>{if(this.enabled)if(Y.isIos&&this.player.config.fullscreen.iosNative)this.target.webkitExitFullscreen(),ke(this.player.play());else if(!st.native||this.forceFallback)this.toggleFallback(!1);else if(this.prefix){if(!W(this.prefix)){const e="moz"===this.prefix?"Cancel":"Exit";document[`${this.prefix}${e}${this.property}`]()}}else(document.cancelFullScreen||document.exitFullscreen).call(document)})),e(this,"toggle",(()=>{this.active?this.exit():this.enter()})),this.player=t,this.prefix=st.prefix,this.property=st.property,this.scrollPosition={x:0,y:0},this.forceFallback="force"===t.config.fullscreen.fallback,this.player.elements.fullscreen=t.config.fullscreen.container&&function(e,t){const{prototype:i}=Element;return(i.closest||function(){let e=this;do{if(re.matches(e,t))return e;e=e.parentElement||e.parentNode}while(null!==e&&1===e.nodeType);return null}).call(e,t)}(this.player.elements.container,t.config.fullscreen.container),fe.call(this.player,document,"ms"===this.prefix?"MSFullscreenChange":`${this.prefix}fullscreenchange`,(()=>{this.onChange()})),fe.call(this.player,this.player.elements.container,"dblclick",(e=>{H(this.player.elements.controls)&&this.player.elements.controls.contains(e.target)||this.player.listeners.proxy(e,this.toggle,"fullscreen")})),fe.call(this,this.player.elements.container,"keydown",(e=>this.trapFocus(e))),this.update()}static get native(){return!!(document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled)}get usingNative(){return st.native&&!this.forceFallback}static get prefix(){if(j(document.exitFullscreen))return"";let e="";return["webkit","moz","ms"].some((t=>!(!j(document[`${t}ExitFullscreen`])&&!j(document[`${t}CancelFullScreen`]))&&(e=t,!0))),e}static get property(){return"moz"===this.prefix?"FullScreen":"Fullscreen"}get enabled(){return(st.native||this.player.config.fullscreen.fallback)&&this.player.config.fullscreen.enabled&&this.player.supported.ui&&this.player.isVideo}get active(){if(!this.enabled)return!1;if(!st.native||this.forceFallback)return oe(this.target,this.player.config.classNames.fullscreen.fallback);const e=this.prefix?this.target.getRootNode()[`${this.prefix}${this.property}Element`]:this.target.getRootNode().fullscreenElement;return e&&e.shadowRoot?e===this.target.getRootNode().host:e===this.target}get target(){return Y.isIos&&this.player.config.fullscreen.iosNative?this.player.media:this.player.elements.fullscreen||this.player.elements.container}}function nt(e,t=1){return new Promise(((i,s)=>{const n=new Image,a=()=>{delete n.onload,delete n.onerror,(n.naturalWidth>=t?i:s)(n)};Object.assign(n,{onload:a,onerror:a,src:e})}))}const at={addStyleHook(){le(this.elements.container,this.config.selectors.container.replace(".",""),!0),le(this.elements.container,this.config.classNames.uiSupported,this.supported.ui)},toggleNativeControls(e=!1){e&&this.isHTML5?this.media.setAttribute("controls",""):this.media.removeAttribute("controls")},build(){if(this.listeners.media(),!this.supported.ui)return this.debug.warn(`Basic support only for ${this.provider} ${this.type}`),void at.toggleNativeControls.call(this,!0);H(this.elements.controls)||(We.inject.call(this),this.listeners.controls()),at.toggleNativeControls.call(this),this.isHTML5&&Ye.setup.call(this),this.volume=null,this.muted=null,this.loop=null,this.quality=null,this.speed=null,We.updateVolume.call(this),We.timeUpdate.call(this),We.durationUpdate.call(this),at.checkPlaying.call(this),le(this.elements.container,this.config.classNames.pip.supported,me.pip&&this.isHTML5&&this.isVideo),le(this.elements.container,this.config.classNames.airplay.supported,me.airplay&&this.isHTML5),le(this.elements.container,this.config.classNames.isIos,Y.isIos),le(this.elements.container,this.config.classNames.isTouch,this.touch),this.ready=!0,setTimeout((()=>{ve.call(this,this.media,"ready")}),0),at.setTitle.call(this),this.poster&&at.setPoster.call(this,this.poster,!1).catch((()=>{})),this.config.duration&&We.durationUpdate.call(this)},setTitle(){let e=He.get("play",this.config);if(_(this.config.title)&&!W(this.config.title)&&(e+=`, ${this.config.title}`),Array.from(this.elements.buttons.play||[]).forEach((t=>{t.setAttribute("aria-label",e)})),this.isEmbed){const e=he.call(this,"iframe");if(!H(e))return;const t=W(this.config.title)?"video":this.config.title,i=He.get("frameTitle",this.config);e.setAttribute("title",i.replace("{title}",t))}},togglePoster(e){le(this.elements.container,this.config.classNames.posterEnabled,e)},setPoster(e,t=!0){return t&&this.poster?Promise.reject(new Error("Poster already set")):(this.media.setAttribute("data-poster",e),this.elements.poster.removeAttribute("hidden"),Te.call(this).then((()=>nt(e))).catch((t=>{throw e===this.poster&&at.togglePoster.call(this,!1),t})).then((()=>{if(e!==this.poster)throw new Error("setPoster cancelled by later call to setPoster")})).then((()=>(Object.assign(this.elements.poster.style,{backgroundImage:`url('${e}')`,backgroundSize:""}),at.togglePoster.call(this,!0),e))))},checkPlaying(e){le(this.elements.container,this.config.classNames.playing,this.playing),le(this.elements.container,this.config.classNames.paused,this.paused),le(this.elements.container,this.config.classNames.stopped,this.stopped),Array.from(this.elements.buttons.play||[]).forEach((e=>{Object.assign(e,{pressed:this.playing}),e.setAttribute("aria-label",He.get(this.playing?"pause":"play",this.config))})),F(e)&&"timeupdate"===e.type||at.toggleControls.call(this)},checkLoading(e){this.loading=["stalled","waiting"].includes(e.type),clearTimeout(this.timers.loading),this.timers.loading=setTimeout((()=>{le(this.elements.container,this.config.classNames.loading,this.loading),at.toggleControls.call(this)}),this.loading?250:0)},toggleControls(e){const{controls:t}=this.elements;if(t&&this.config.hideControls){const i=this.touch&&this.lastSeekTime+2e3>Date.now();this.toggleControls(Boolean(e||this.loading||this.paused||t.pressed||t.hover||i))}},migrateStyles(){Object.values({...this.media.style}).filter((e=>!W(e)&&_(e)&&e.startsWith("--plyr"))).forEach((e=>{this.elements.container.style.setProperty(e,this.media.style.getPropertyValue(e)),this.media.style.removeProperty(e)})),W(this.media.style)&&this.media.removeAttribute("style")}};class lt{constructor(t){e(this,"firstTouch",(()=>{const{player:e}=this,{elements:t}=e;e.touch=!0,le(t.container,e.config.classNames.isTouch,!0)})),e(this,"setTabFocus",(e=>{const{player:t}=this,{elements:i}=t;if(clearTimeout(this.focusTimer),"keydown"===e.type&&9!==e.which)return;"keydown"===e.type&&(this.lastKeyDown=e.timeStamp);const s=e.timeStamp-this.lastKeyDown<=20;("focus"!==e.type||s)&&((()=>{const e=t.config.classNames.tabFocus;le(ce.call(t,`.${e}`),e,!1)})(),"focusout"!==e.type&&(this.focusTimer=setTimeout((()=>{const e=document.activeElement;i.container.contains(e)&&le(document.activeElement,t.config.classNames.tabFocus,!0)}),10)))})),e(this,"global",((e=!0)=>{const{player:t}=this;t.config.keyboard.global&&ge.call(t,window,"keydown keyup",this.handleKey,e,!1),ge.call(t,document.body,"click",this.toggleMenu,e),ye.call(t,document.body,"touchstart",this.firstTouch),ge.call(t,document.body,"keydown focus blur focusout",this.setTabFocus,e,!1,!0)})),e(this,"container",(()=>{const{player:e}=this,{config:t,elements:i,timers:s}=e;!t.keyboard.global&&t.keyboard.focused&&fe.call(e,i.container,"keydown keyup",this.handleKey,!1),fe.call(e,i.container,"mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen",(t=>{const{controls:n}=i;n&&"enterfullscreen"===t.type&&(n.pressed=!1,n.hover=!1);let a=0;["touchstart","touchmove","mousemove"].includes(t.type)&&(at.toggleControls.call(e,!0),a=e.touch?3e3:2e3),clearTimeout(s.controls),s.controls=setTimeout((()=>at.toggleControls.call(e,!1)),a)}));const n=()=>{if(!e.isVimeo||e.config.vimeo.premium)return;const t=i.wrapper,{active:s}=e.fullscreen,[n,a]=xe.call(e),l=Se(`aspect-ratio: ${n} / ${a}`);if(!s)return void(l?(t.style.width=null,t.style.height=null):(t.style.maxWidth=null,t.style.margin=null));const[o,r]=[Math.max(document.documentElement.clientWidth||0,window.innerWidth||0),Math.max(document.documentElement.clientHeight||0,window.innerHeight||0)],c=o/r>n/a;l?(t.style.width=c?"auto":"100%",t.style.height=c?"100%":"auto"):(t.style.maxWidth=c?r/a*n+"px":null,t.style.margin=c?"0 auto":null)},a=()=>{clearTimeout(s.resized),s.resized=setTimeout(n,50)};fe.call(e,i.container,"enterfullscreen exitfullscreen",(t=>{const{target:s}=e.fullscreen;if(s!==i.container)return;if(!e.isEmbed&&W(e.config.ratio))return;n();("enterfullscreen"===t.type?fe:be).call(e,window,"resize",a)}))})),e(this,"media",(()=>{const{player:e}=this,{elements:t}=e;if(fe.call(e,e.media,"timeupdate seeking seeked",(t=>We.timeUpdate.call(e,t))),fe.call(e,e.media,"durationchange loadeddata loadedmetadata",(t=>We.durationUpdate.call(e,t))),fe.call(e,e.media,"ended",(()=>{e.isHTML5&&e.isVideo&&e.config.resetOnEnd&&(e.restart(),e.pause())})),fe.call(e,e.media,"progress playing seeking seeked",(t=>We.updateProgress.call(e,t))),fe.call(e,e.media,"volumechange",(t=>We.updateVolume.call(e,t))),fe.call(e,e.media,"playing play pause ended emptied timeupdate",(t=>at.checkPlaying.call(e,t))),fe.call(e,e.media,"waiting canplay seeked playing",(t=>at.checkLoading.call(e,t))),e.supported.ui&&e.config.clickToPlay&&!e.isAudio){const i=he.call(e,`.${e.config.classNames.video}`);if(!H(i))return;fe.call(e,t.container,"click",(s=>{([t.container,i].includes(s.target)||i.contains(s.target))&&(e.touch&&e.config.hideControls||(e.ended?(this.proxy(s,e.restart,"restart"),this.proxy(s,(()=>{ke(e.play())}),"play")):this.proxy(s,(()=>{ke(e.togglePlay())}),"play")))}))}e.supported.ui&&e.config.disableContextMenu&&fe.call(e,t.wrapper,"contextmenu",(e=>{e.preventDefault()}),!1),fe.call(e,e.media,"volumechange",(()=>{e.storage.set({volume:e.volume,muted:e.muted})})),fe.call(e,e.media,"ratechange",(()=>{We.updateSetting.call(e,"speed"),e.storage.set({speed:e.speed})})),fe.call(e,e.media,"qualitychange",(t=>{We.updateSetting.call(e,"quality",null,t.detail.quality)})),fe.call(e,e.media,"ready qualitychange",(()=>{We.setDownloadUrl.call(e)}));const i=e.config.events.concat(["keyup","keydown"]).join(" ");fe.call(e,e.media,i,(i=>{let{detail:s={}}=i;"error"===i.type&&(s=e.media.error),ve.call(e,t.container,i.type,!0,s)}))})),e(this,"proxy",((e,t,i)=>{const{player:s}=this,n=s.config.listeners[i];let a=!0;j(n)&&(a=n.call(s,e)),!1!==a&&j(t)&&t.call(s,e)})),e(this,"bind",((e,t,i,s,n=!0)=>{const{player:a}=this,l=a.config.listeners[s],o=j(l);fe.call(a,e,t,(e=>this.proxy(e,i,s)),n&&!o)})),e(this,"controls",(()=>{const{player:e}=this,{elements:t}=e,i=Y.isIE?"change":"input";if(t.buttons.play&&Array.from(t.buttons.play).forEach((t=>{this.bind(t,"click",(()=>{ke(e.togglePlay())}),"play")})),this.bind(t.buttons.restart,"click",e.restart,"restart"),this.bind(t.buttons.rewind,"click",(()=>{e.lastSeekTime=Date.now(),e.rewind()}),"rewind"),this.bind(t.buttons.fastForward,"click",(()=>{e.lastSeekTime=Date.now(),e.forward()}),"fastForward"),this.bind(t.buttons.mute,"click",(()=>{e.muted=!e.muted}),"mute"),this.bind(t.buttons.captions,"click",(()=>e.toggleCaptions())),this.bind(t.buttons.download,"click",(()=>{ve.call(e,e.media,"download")}),"download"),this.bind(t.buttons.fullscreen,"click",(()=>{e.fullscreen.toggle()}),"fullscreen"),this.bind(t.buttons.pip,"click",(()=>{e.pip="toggle"}),"pip"),this.bind(t.buttons.airplay,"click",e.airplay,"airplay"),this.bind(t.buttons.settings,"click",(t=>{t.stopPropagation(),t.preventDefault(),We.toggleMenu.call(e,t)}),null,!1),this.bind(t.buttons.settings,"keyup",(t=>{const i=t.which;[13,32].includes(i)&&(13!==i?(t.preventDefault(),t.stopPropagation(),We.toggleMenu.call(e,t)):We.focusFirstMenuItem.call(e,null,!0))}),null,!1),this.bind(t.settings.menu,"keydown",(t=>{27===t.which&&We.toggleMenu.call(e,t)})),this.bind(t.inputs.seek,"mousedown mousemove",(e=>{const i=t.progress.getBoundingClientRect(),s=100/i.width*(e.pageX-i.left);e.currentTarget.setAttribute("seek-value",s)})),this.bind(t.inputs.seek,"mousedown mouseup keydown keyup touchstart touchend",(t=>{const i=t.currentTarget,s=t.keyCode?t.keyCode:t.which,n="play-on-seeked";if(R(t)&&39!==s&&37!==s)return;e.lastSeekTime=Date.now();const a=i.hasAttribute(n),l=["mouseup","touchend","keyup"].includes(t.type);a&&l?(i.removeAttribute(n),ke(e.play())):!l&&e.playing&&(i.setAttribute(n,""),e.pause())})),Y.isIos){const t=ce.call(e,'input[type="range"]');Array.from(t).forEach((e=>this.bind(e,i,(e=>K(e.target)))))}this.bind(t.inputs.seek,i,(t=>{const i=t.currentTarget;let s=i.getAttribute("seek-value");W(s)&&(s=i.value),i.removeAttribute("seek-value"),e.currentTime=s/i.max*e.duration}),"seek"),this.bind(t.progress,"mouseenter mouseleave mousemove",(t=>We.updateSeekTooltip.call(e,t))),this.bind(t.progress,"mousemove touchmove",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.startMove(t)})),this.bind(t.progress,"mouseleave touchend click",(()=>{const{previewThumbnails:t}=e;t&&t.loaded&&t.endMove(!1,!0)})),this.bind(t.progress,"mousedown touchstart",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.startScrubbing(t)})),this.bind(t.progress,"mouseup touchend",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.endScrubbing(t)})),Y.isWebkit&&Array.from(ce.call(e,'input[type="range"]')).forEach((t=>{this.bind(t,"input",(t=>We.updateRangeFill.call(e,t.target)))})),e.config.toggleInvert&&!H(t.display.duration)&&this.bind(t.display.currentTime,"click",(()=>{0!==e.currentTime&&(e.config.invertTime=!e.config.invertTime,We.timeUpdate.call(e))})),this.bind(t.inputs.volume,i,(t=>{e.volume=t.target.value}),"volume"),this.bind(t.controls,"mouseenter mouseleave",(i=>{t.controls.hover=!e.touch&&"mouseenter"===i.type})),t.fullscreen&&Array.from(t.fullscreen.children).filter((e=>!e.contains(t.container))).forEach((i=>{this.bind(i,"mouseenter mouseleave",(i=>{t.controls&&(t.controls.hover=!e.touch&&"mouseenter"===i.type)}))})),this.bind(t.controls,"mousedown mouseup touchstart touchend touchcancel",(e=>{t.controls.pressed=["mousedown","touchstart"].includes(e.type)})),this.bind(t.controls,"focusin",(()=>{const{config:i,timers:s}=e;le(t.controls,i.classNames.noTransition,!0),at.toggleControls.call(e,!0),setTimeout((()=>{le(t.controls,i.classNames.noTransition,!1)}),0);const n=this.touch?3e3:4e3;clearTimeout(s.controls),s.controls=setTimeout((()=>at.toggleControls.call(e,!1)),n)})),this.bind(t.inputs.volume,"wheel",(t=>{const i=t.webkitDirectionInvertedFromDevice,[s,n]=[t.deltaX,-t.deltaY].map((e=>i?-e:e)),a=Math.sign(Math.abs(s)>Math.abs(n)?s:n);e.increaseVolume(a/50);const{volume:l}=e.media;(1===a&&l<1||-1===a&&l>0)&&t.preventDefault()}),"volume",!1)})),this.player=t,this.lastKey=null,this.focusTimer=null,this.lastKeyDown=null,this.handleKey=this.handleKey.bind(this),this.toggleMenu=this.toggleMenu.bind(this),this.setTabFocus=this.setTabFocus.bind(this),this.firstTouch=this.firstTouch.bind(this)}handleKey(e){const{player:t}=this,{elements:i}=t,s=e.keyCode?e.keyCode:e.which,n="keydown"===e.type,a=n&&s===this.lastKey;if(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;if(!$(s))return;if(n){const n=document.activeElement;if(H(n)){const{editable:s}=t.config.selectors,{seek:a}=i.inputs;if(n!==a&&re(n,s))return;if(32===e.which&&re(n,'button, [role^="menuitem"]'))return}switch([32,37,38,39,40,48,49,50,51,52,53,54,56,57,67,70,73,75,76,77,79].includes(s)&&(e.preventDefault(),e.stopPropagation()),s){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:a||(t.currentTime=t.duration/10*(s-48));break;case 32:case 75:a||ke(t.togglePlay());break;case 38:t.increaseVolume(.1);break;case 40:t.decreaseVolume(.1);break;case 77:a||(t.muted=!t.muted);break;case 39:t.forward();break;case 37:t.rewind();break;case 70:t.fullscreen.toggle();break;case 67:a||t.toggleCaptions();break;case 76:t.loop=!t.loop}27===s&&!t.fullscreen.usingNative&&t.fullscreen.active&&t.fullscreen.toggle(),this.lastKey=s}else this.lastKey=null}toggleMenu(e){We.toggleMenu.call(this.player,e)}}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var ot=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e,t){e.exports=function(){var e=function(){},t={},i={},s={};function n(e,t){e=e.push?e:[e];var n,a,l,o=[],r=e.length,c=r;for(n=function(e,i){i.length&&o.push(e),--c||t(o)};r--;)a=e[r],(l=i[a])?n(a,l):(s[a]=s[a]||[]).push(n)}function a(e,t){if(e){var n=s[e];if(i[e]=t,n)for(;n.length;)n[0](e,t),n.splice(0,1)}}function l(t,i){t.call&&(t={success:t}),i.length?(t.error||e)(i):(t.success||e)(t)}function o(t,i,s,n){var a,l,r=document,c=s.async,h=(s.numRetries||0)+1,u=s.before||e,d=t.replace(/[\?|#].*$/,""),m=t.replace(/^(css|img)!/,"");n=n||0,/(^css!|\.css$)/.test(d)?((l=r.createElement("link")).rel="stylesheet",l.href=m,(a="hideFocus"in l)&&l.relList&&(a=0,l.rel="preload",l.as="style")):/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(d)?(l=r.createElement("img")).src=m:((l=r.createElement("script")).src=t,l.async=void 0===c||c),l.onload=l.onerror=l.onbeforeload=function(e){var r=e.type[0];if(a)try{l.sheet.cssText.length||(r="e")}catch(e){18!=e.code&&(r="e")}if("e"==r){if((n+=1)<h)return o(t,i,s,n)}else if("preload"==l.rel&&"style"==l.as)return l.rel="stylesheet";i(t,r,e.defaultPrevented)},!1!==u(t,l)&&r.head.appendChild(l)}function r(e,t,i){var s,n,a=(e=e.push?e:[e]).length,l=a,r=[];for(s=function(e,i,s){if("e"==i&&r.push(e),"b"==i){if(!s)return;r.push(e)}--a||t(r)},n=0;n<l;n++)o(e[n],s,i)}function c(e,i,s){var n,o;if(i&&i.trim&&(n=i),o=(n?s:i)||{},n){if(n in t)throw"LoadJS";t[n]=!0}function c(t,i){r(e,(function(e){l(o,e),t&&l({success:t,error:i},e),a(n,e)}),o)}if(o.returnPromise)return new Promise(c);c()}return c.ready=function(e,t){return n(e,(function(e){l(t,e)})),c},c.done=function(e){a(e,[])},c.reset=function(){t={},i={},s={}},c.isDefined=function(e){return e in t},c}()}));function rt(e){return new Promise(((t,i)=>{ot(e,{success:t,error:i})}))}function ct(e){e&&!this.embed.hasPlayed&&(this.embed.hasPlayed=!0),this.media.paused===e&&(this.media.paused=!e,ve.call(this,this.media,e?"play":"pause"))}const ht={setup(){const e=this;le(e.elements.wrapper,e.config.classNames.embed,!0),e.options.speed=e.config.speed.options,Me.call(e),L(window.Vimeo)?ht.ready.call(e):rt(e.config.urls.vimeo.sdk).then((()=>{ht.ready.call(e)})).catch((t=>{e.debug.warn("Vimeo SDK (player.js) failed to load",t)}))},ready(){const e=this,t=e.config.vimeo,{premium:i,referrerPolicy:s,...n}=t;let a=e.media.getAttribute("src"),l="";W(a)?(a=e.media.getAttribute(e.config.attributes.embed.id),l=e.media.getAttribute(e.config.attributes.embed.hash)):l=function(e){const t=e.match(/^.*(?:vimeo.com\/|video\/)(?:\d+)(?:\?.*&*h=|\/)+(?<hash>[\d,a-f]+)/);return t?t.groups.hash:null}(a);const o=l?{h:l}:{};i&&Object.assign(n,{controls:!1,sidedock:!1});const r=Ke({loop:e.config.loop.active,autoplay:e.autoplay,muted:e.muted,gesture:"media",playsinline:!this.config.fullscreen.iosNative,...o,...n}),c=W(h=a)?null:$(Number(h))?h:h.match(/^.*(vimeo.com\/|video\/)(\d+).*/)?RegExp.$2:h;var h;const u=Z("iframe"),d=$e(e.config.urls.vimeo.iframe,c,r);if(u.setAttribute("src",d),u.setAttribute("allowfullscreen",""),u.setAttribute("allow",["autoplay","fullscreen","picture-in-picture","encrypted-media","accelerometer","gyroscope"].join("; ")),W(s)||u.setAttribute("referrerPolicy",s),i||!t.customControls)u.setAttribute("data-poster",e.poster),e.media=se(u,e.media);else{const t=Z("div",{class:e.config.classNames.embedContainer,"data-poster":e.poster});t.appendChild(u),e.media=se(t,e.media)}t.customControls||Re($e(e.config.urls.vimeo.api,d)).then((t=>{!W(t)&&t.thumbnail_url&&at.setPoster.call(e,t.thumbnail_url).catch((()=>{}))})),e.embed=new window.Vimeo.Player(u,{autopause:e.config.autopause,muted:e.muted}),e.media.paused=!0,e.media.currentTime=0,e.supported.ui&&e.embed.disableTextTrack(),e.media.play=()=>(ct.call(e,!0),e.embed.play()),e.media.pause=()=>(ct.call(e,!1),e.embed.pause()),e.media.stop=()=>{e.pause(),e.currentTime=0};let{currentTime:m}=e.media;Object.defineProperty(e.media,"currentTime",{get:()=>m,set(t){const{embed:i,media:s,paused:n,volume:a}=e,l=n&&!i.hasPlayed;s.seeking=!0,ve.call(e,s,"seeking"),Promise.resolve(l&&i.setVolume(0)).then((()=>i.setCurrentTime(t))).then((()=>l&&i.pause())).then((()=>l&&i.setVolume(a))).catch((()=>{}))}});let p=e.config.speed.selected;Object.defineProperty(e.media,"playbackRate",{get:()=>p,set(t){e.embed.setPlaybackRate(t).then((()=>{p=t,ve.call(e,e.media,"ratechange")})).catch((()=>{e.options.speed=[1]}))}});let{volume:g}=e.config;Object.defineProperty(e.media,"volume",{get:()=>g,set(t){e.embed.setVolume(t).then((()=>{g=t,ve.call(e,e.media,"volumechange")}))}});let{muted:f}=e.config;Object.defineProperty(e.media,"muted",{get:()=>f,set(t){const i=!!O(t)&&t;e.embed.setVolume(i?0:e.config.volume).then((()=>{f=i,ve.call(e,e.media,"volumechange")}))}});let b,{loop:y}=e.config;Object.defineProperty(e.media,"loop",{get:()=>y,set(t){const i=O(t)?t:e.config.loop.active;e.embed.setLoop(i).then((()=>{y=i}))}}),e.embed.getVideoUrl().then((t=>{b=t,We.setDownloadUrl.call(e)})).catch((e=>{this.debug.warn(e)})),Object.defineProperty(e.media,"currentSrc",{get:()=>b}),Object.defineProperty(e.media,"ended",{get:()=>e.currentTime===e.duration}),Promise.all([e.embed.getVideoWidth(),e.embed.getVideoHeight()]).then((t=>{const[i,s]=t;e.embed.ratio=Ie(i,s),Me.call(this)})),e.embed.setAutopause(e.config.autopause).then((t=>{e.config.autopause=t})),e.embed.getVideoTitle().then((t=>{e.config.title=t,at.setTitle.call(this)})),e.embed.getCurrentTime().then((t=>{m=t,ve.call(e,e.media,"timeupdate")})),e.embed.getDuration().then((t=>{e.media.duration=t,ve.call(e,e.media,"durationchange")})),e.embed.getTextTracks().then((t=>{e.media.textTracks=t,Ye.setup.call(e)})),e.embed.on("cuechange",(({cues:t=[]})=>{const i=t.map((e=>function(e){const t=document.createDocumentFragment(),i=document.createElement("div");return t.appendChild(i),i.innerHTML=e,t.firstChild.innerText}(e.text)));Ye.updateCues.call(e,i)})),e.embed.on("loaded",(()=>{if(e.embed.getPaused().then((t=>{ct.call(e,!t),t||ve.call(e,e.media,"playing")})),H(e.embed.element)&&e.supported.ui){e.embed.element.setAttribute("tabindex",-1)}})),e.embed.on("bufferstart",(()=>{ve.call(e,e.media,"waiting")})),e.embed.on("bufferend",(()=>{ve.call(e,e.media,"playing")})),e.embed.on("play",(()=>{ct.call(e,!0),ve.call(e,e.media,"playing")})),e.embed.on("pause",(()=>{ct.call(e,!1)})),e.embed.on("timeupdate",(t=>{e.media.seeking=!1,m=t.seconds,ve.call(e,e.media,"timeupdate")})),e.embed.on("progress",(t=>{e.media.buffered=t.percent,ve.call(e,e.media,"progress"),1===parseInt(t.percent,10)&&ve.call(e,e.media,"canplaythrough"),e.embed.getDuration().then((t=>{t!==e.media.duration&&(e.media.duration=t,ve.call(e,e.media,"durationchange"))}))})),e.embed.on("seeked",(()=>{e.media.seeking=!1,ve.call(e,e.media,"seeked")})),e.embed.on("ended",(()=>{e.media.paused=!0,ve.call(e,e.media,"ended")})),e.embed.on("error",(t=>{e.media.error=t,ve.call(e,e.media,"error")})),t.customControls&&setTimeout((()=>at.build.call(e)),0)}};function ut(e){e&&!this.embed.hasPlayed&&(this.embed.hasPlayed=!0),this.media.paused===e&&(this.media.paused=!e,ve.call(this,this.media,e?"play":"pause"))}function dt(e){return e.noCookie?"https://www.youtube-nocookie.com":"http:"===window.location.protocol?"http://www.youtube.com":void 0}const mt={setup(){if(le(this.elements.wrapper,this.config.classNames.embed,!0),L(window.YT)&&j(window.YT.Player))mt.ready.call(this);else{const e=window.onYouTubeIframeAPIReady;window.onYouTubeIframeAPIReady=()=>{j(e)&&e(),mt.ready.call(this)},rt(this.config.urls.youtube.sdk).catch((e=>{this.debug.warn("YouTube API failed to load",e)}))}},getTitle(e){Re($e(this.config.urls.youtube.api,e)).then((e=>{if(L(e)){const{title:t,height:i,width:s}=e;this.config.title=t,at.setTitle.call(this),this.embed.ratio=Ie(s,i)}Me.call(this)})).catch((()=>{Me.call(this)}))},ready(){const e=this,t=e.config.youtube,i=e.media&&e.media.getAttribute("id");if(!W(i)&&i.startsWith("youtube-"))return;let s=e.media.getAttribute("src");W(s)&&(s=e.media.getAttribute(this.config.attributes.embed.id));const n=W(a=s)?null:a.match(/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/)?RegExp.$2:a;var a;const l=Z("div",{id:`${e.provider}-${Math.floor(1e4*Math.random())}`,"data-poster":t.customControls?e.poster:void 0});if(e.media=se(l,e.media),t.customControls){const t=e=>`https://i.ytimg.com/vi/${n}/${e}default.jpg`;nt(t("maxres"),121).catch((()=>nt(t("sd"),121))).catch((()=>nt(t("hq")))).then((t=>at.setPoster.call(e,t.src))).then((t=>{t.includes("maxres")||(e.elements.poster.style.backgroundSize="cover")})).catch((()=>{}))}e.embed=new window.YT.Player(e.media,{videoId:n,host:dt(t),playerVars:X({},{autoplay:e.config.autoplay?1:0,hl:e.config.hl,controls:e.supported.ui&&t.customControls?0:1,disablekb:1,playsinline:e.config.fullscreen.iosNative?0:1,cc_load_policy:e.captions.active?1:0,cc_lang_pref:e.config.captions.language,widget_referrer:window?window.location.href:null},t),events:{onError(t){if(!e.media.error){const i=t.data,s={2:"The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.",5:"The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.",100:"The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.",101:"The owner of the requested video does not allow it to be played in embedded players.",150:"The owner of the requested video does not allow it to be played in embedded players."}[i]||"An unknown error occured";e.media.error={code:i,message:s},ve.call(e,e.media,"error")}},onPlaybackRateChange(t){const i=t.target;e.media.playbackRate=i.getPlaybackRate(),ve.call(e,e.media,"ratechange")},onReady(i){if(j(e.media.play))return;const s=i.target;mt.getTitle.call(e,n),e.media.play=()=>{ut.call(e,!0),s.playVideo()},e.media.pause=()=>{ut.call(e,!1),s.pauseVideo()},e.media.stop=()=>{s.stopVideo()},e.media.duration=s.getDuration(),e.media.paused=!0,e.media.currentTime=0,Object.defineProperty(e.media,"currentTime",{get:()=>Number(s.getCurrentTime()),set(t){e.paused&&!e.embed.hasPlayed&&e.embed.mute(),e.media.seeking=!0,ve.call(e,e.media,"seeking"),s.seekTo(t)}}),Object.defineProperty(e.media,"playbackRate",{get:()=>s.getPlaybackRate(),set(e){s.setPlaybackRate(e)}});let{volume:a}=e.config;Object.defineProperty(e.media,"volume",{get:()=>a,set(t){a=t,s.setVolume(100*a),ve.call(e,e.media,"volumechange")}});let{muted:l}=e.config;Object.defineProperty(e.media,"muted",{get:()=>l,set(t){const i=O(t)?t:l;l=i,s[i?"mute":"unMute"](),s.setVolume(100*a),ve.call(e,e.media,"volumechange")}}),Object.defineProperty(e.media,"currentSrc",{get:()=>s.getVideoUrl()}),Object.defineProperty(e.media,"ended",{get:()=>e.currentTime===e.duration});const o=s.getAvailablePlaybackRates();e.options.speed=o.filter((t=>e.config.speed.options.includes(t))),e.supported.ui&&t.customControls&&e.media.setAttribute("tabindex",-1),ve.call(e,e.media,"timeupdate"),ve.call(e,e.media,"durationchange"),clearInterval(e.timers.buffering),e.timers.buffering=setInterval((()=>{e.media.buffered=s.getVideoLoadedFraction(),(null===e.media.lastBuffered||e.media.lastBuffered<e.media.buffered)&&ve.call(e,e.media,"progress"),e.media.lastBuffered=e.media.buffered,1===e.media.buffered&&(clearInterval(e.timers.buffering),ve.call(e,e.media,"canplaythrough"))}),200),t.customControls&&setTimeout((()=>at.build.call(e)),50)},onStateChange(i){const s=i.target;clearInterval(e.timers.playing);switch(e.media.seeking&&[1,2].includes(i.data)&&(e.media.seeking=!1,ve.call(e,e.media,"seeked")),i.data){case-1:ve.call(e,e.media,"timeupdate"),e.media.buffered=s.getVideoLoadedFraction(),ve.call(e,e.media,"progress");break;case 0:ut.call(e,!1),e.media.loop?(s.stopVideo(),s.playVideo()):ve.call(e,e.media,"ended");break;case 1:t.customControls&&!e.config.autoplay&&e.media.paused&&!e.embed.hasPlayed?e.media.pause():(ut.call(e,!0),ve.call(e,e.media,"playing"),e.timers.playing=setInterval((()=>{ve.call(e,e.media,"timeupdate")}),50),e.media.duration!==s.getDuration()&&(e.media.duration=s.getDuration(),ve.call(e,e.media,"durationchange")));break;case 2:e.muted||e.embed.unMute(),ut.call(e,!1);break;case 3:ve.call(e,e.media,"waiting")}ve.call(e,e.elements.container,"statechange",!1,{code:i.data})}}})}},pt={setup(){this.media?(le(this.elements.container,this.config.classNames.type.replace("{0}",this.type),!0),le(this.elements.container,this.config.classNames.provider.replace("{0}",this.provider),!0),this.isEmbed&&le(this.elements.container,this.config.classNames.type.replace("{0}","video"),!0),this.isVideo&&(this.elements.wrapper=Z("div",{class:this.config.classNames.video}),J(this.media,this.elements.wrapper),this.elements.poster=Z("div",{class:this.config.classNames.poster}),this.elements.wrapper.appendChild(this.elements.poster)),this.isHTML5?Le.setup.call(this):this.isYouTube?mt.setup.call(this):this.isVimeo&&ht.setup.call(this)):this.debug.warn("No media element found!")}};class gt{constructor(t){e(this,"load",(()=>{this.enabled&&(L(window.google)&&L(window.google.ima)?this.ready():rt(this.player.config.urls.googleIMA.sdk).then((()=>{this.ready()})).catch((()=>{this.trigger("error",new Error("Google IMA SDK failed to load"))})))})),e(this,"ready",(()=>{var e;this.enabled||((e=this).manager&&e.manager.destroy(),e.elements.displayContainer&&e.elements.displayContainer.destroy(),e.elements.container.remove()),this.startSafetyTimer(12e3,"ready()"),this.managerPromise.then((()=>{this.clearSafetyTimer("onAdsManagerLoaded()")})),this.listeners(),this.setupIMA()})),e(this,"setupIMA",(()=>{this.elements.container=Z("div",{class:this.player.config.classNames.ads}),this.player.elements.container.appendChild(this.elements.container),google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED),google.ima.settings.setLocale(this.player.config.ads.language),google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline),this.elements.displayContainer=new google.ima.AdDisplayContainer(this.elements.container,this.player.media),this.loader=new google.ima.AdsLoader(this.elements.displayContainer),this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,(e=>this.onAdsManagerLoaded(e)),!1),this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,(e=>this.onAdError(e)),!1),this.requestAds()})),e(this,"requestAds",(()=>{const{container:e}=this.player.elements;try{const t=new google.ima.AdsRequest;t.adTagUrl=this.tagUrl,t.linearAdSlotWidth=e.offsetWidth,t.linearAdSlotHeight=e.offsetHeight,t.nonLinearAdSlotWidth=e.offsetWidth,t.nonLinearAdSlotHeight=e.offsetHeight,t.forceNonLinearFullSlot=!1,t.setAdWillPlayMuted(!this.player.muted),this.loader.requestAds(t)}catch(e){this.onAdError(e)}})),e(this,"pollCountdown",((e=!1)=>{if(!e)return clearInterval(this.countdownTimer),void this.elements.container.removeAttribute("data-badge-text");this.countdownTimer=setInterval((()=>{const e=Ue(Math.max(this.manager.getRemainingTime(),0)),t=`${He.get("advertisement",this.player.config)} - ${e}`;this.elements.container.setAttribute("data-badge-text",t)}),100)})),e(this,"onAdsManagerLoaded",(e=>{if(!this.enabled)return;const t=new google.ima.AdsRenderingSettings;t.restoreCustomPlaybackStateOnAdBreakComplete=!0,t.enablePreloading=!0,this.manager=e.getAdsManager(this.player,t),this.cuePoints=this.manager.getCuePoints(),this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,(e=>this.onAdError(e))),Object.keys(google.ima.AdEvent.Type).forEach((e=>{this.manager.addEventListener(google.ima.AdEvent.Type[e],(e=>this.onAdEvent(e)))})),this.trigger("loaded")})),e(this,"addCuePoints",(()=>{W(this.cuePoints)||this.cuePoints.forEach((e=>{if(0!==e&&-1!==e&&e<this.player.duration){const t=this.player.elements.progress;if(H(t)){const i=100/this.player.duration*e,s=Z("span",{class:this.player.config.classNames.cues});s.style.left=`${i.toString()}%`,t.appendChild(s)}}}))})),e(this,"onAdEvent",(e=>{const{container:t}=this.player.elements,i=e.getAd(),s=e.getAdData();switch((e=>{ve.call(this.player,this.player.media,`ads${e.replace(/_/g,"").toLowerCase()}`)})(e.type),e.type){case google.ima.AdEvent.Type.LOADED:this.trigger("loaded"),this.pollCountdown(!0),i.isLinear()||(i.width=t.offsetWidth,i.height=t.offsetHeight);break;case google.ima.AdEvent.Type.STARTED:this.manager.setVolume(this.player.volume);break;case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:this.player.ended?this.loadAds():this.loader.contentComplete();break;case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:this.pauseContent();break;case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:this.pollCountdown(),this.resumeContent();break;case google.ima.AdEvent.Type.LOG:s.adError&&this.player.debug.warn(`Non-fatal ad error: ${s.adError.getMessage()}`)}})),e(this,"onAdError",(e=>{this.cancel(),this.player.debug.warn("Ads error",e)})),e(this,"listeners",(()=>{const{container:e}=this.player.elements;let t;this.player.on("canplay",(()=>{this.addCuePoints()})),this.player.on("ended",(()=>{this.loader.contentComplete()})),this.player.on("timeupdate",(()=>{t=this.player.currentTime})),this.player.on("seeked",(()=>{const e=this.player.currentTime;W(this.cuePoints)||this.cuePoints.forEach(((i,s)=>{t<i&&i<e&&(this.manager.discardAdBreak(),this.cuePoints.splice(s,1))}))})),window.addEventListener("resize",(()=>{this.manager&&this.manager.resize(e.offsetWidth,e.offsetHeight,google.ima.ViewMode.NORMAL)}))})),e(this,"play",(()=>{const{container:e}=this.player.elements;this.managerPromise||this.resumeContent(),this.managerPromise.then((()=>{this.manager.setVolume(this.player.volume),this.elements.displayContainer.initialize();try{this.initialized||(this.manager.init(e.offsetWidth,e.offsetHeight,google.ima.ViewMode.NORMAL),this.manager.start()),this.initialized=!0}catch(e){this.onAdError(e)}})).catch((()=>{}))})),e(this,"resumeContent",(()=>{this.elements.container.style.zIndex="",this.playing=!1,ke(this.player.media.play())})),e(this,"pauseContent",(()=>{this.elements.container.style.zIndex=3,this.playing=!0,this.player.media.pause()})),e(this,"cancel",(()=>{this.initialized&&this.resumeContent(),this.trigger("error"),this.loadAds()})),e(this,"loadAds",(()=>{this.managerPromise.then((()=>{this.manager&&this.manager.destroy(),this.managerPromise=new Promise((e=>{this.on("loaded",e),this.player.debug.log(this.manager)})),this.initialized=!1,this.requestAds()})).catch((()=>{}))})),e(this,"trigger",((e,...t)=>{const i=this.events[e];q(i)&&i.forEach((e=>{j(e)&&e.apply(this,t)}))})),e(this,"on",((e,t)=>(q(this.events[e])||(this.events[e]=[]),this.events[e].push(t),this))),e(this,"startSafetyTimer",((e,t)=>{this.player.debug.log(`Safety timer invoked from: ${t}`),this.safetyTimer=setTimeout((()=>{this.cancel(),this.clearSafetyTimer("startSafetyTimer()")}),e)})),e(this,"clearSafetyTimer",(e=>{I(this.safetyTimer)||(this.player.debug.log(`Safety timer cleared from: ${e}`),clearTimeout(this.safetyTimer),this.safetyTimer=null)})),this.player=t,this.config=t.config.ads,this.playing=!1,this.initialized=!1,this.elements={container:null,displayContainer:null},this.manager=null,this.loader=null,this.cuePoints=null,this.events={},this.safetyTimer=null,this.countdownTimer=null,this.managerPromise=new Promise(((e,t)=>{this.on("loaded",e),this.on("error",t)})),this.load()}get enabled(){const{config:e}=this;return this.player.isHTML5&&this.player.isVideo&&e.enabled&&(!W(e.publisherId)||U(e.tagUrl))}get tagUrl(){const{config:e}=this;if(U(e.tagUrl))return e.tagUrl;return`https://go.aniview.com/api/adserver6/vast/?${Ke({AV_PUBLISHERID:"58c25bb0073ef448b1087ad6",AV_CHANNELID:"5a0458dc28a06145e4519d21",AV_URL:window.location.hostname,cb:Date.now(),AV_WIDTH:640,AV_HEIGHT:480,AV_CDIM2:e.publisherId})}`}}const ft=e=>{const t=[];return e.split(/\r\n\r\n|\n\n|\r\r/).forEach((e=>{const i={};e.split(/\r\n|\n|\r/).forEach((e=>{if($(i.startTime)){if(!W(e.trim())&&W(i.text)){const t=e.trim().split("#xywh=");[i.text]=t,t[1]&&([i.x,i.y,i.w,i.h]=t[1].split(","))}}else{const t=e.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})/);t&&(i.startTime=60*Number(t[1]||0)*60+60*Number(t[2])+Number(t[3])+Number(`0.${t[4]}`),i.endTime=60*Number(t[6]||0)*60+60*Number(t[7])+Number(t[8])+Number(`0.${t[9]}`))}})),i.text&&t.push(i)})),t},bt=(e,t)=>{const i={};return e>t.width/t.height?(i.width=t.width,i.height=1/e*t.width):(i.height=t.height,i.width=e*t.height),i};class yt{constructor(t){e(this,"load",(()=>{this.player.elements.display.seekTooltip&&(this.player.elements.display.seekTooltip.hidden=this.enabled),this.enabled&&this.getThumbnails().then((()=>{this.enabled&&(this.render(),this.determineContainerAutoSizing(),this.loaded=!0)}))})),e(this,"getThumbnails",(()=>new Promise((e=>{const{src:t}=this.player.config.previewThumbnails;if(W(t))throw new Error("Missing previewThumbnails.src config attribute");const i=()=>{this.thumbnails.sort(((e,t)=>e.height-t.height)),this.player.debug.log("Preview thumbnails",this.thumbnails),e()};if(j(t))t((e=>{this.thumbnails=e,i()}));else{const e=(_(t)?[t]:t).map((e=>this.getThumbnail(e)));Promise.all(e).then(i)}})))),e(this,"getThumbnail",(e=>new Promise((t=>{Re(e).then((i=>{const s={frames:ft(i),height:null,urlPrefix:""};s.frames[0].text.startsWith("/")||s.frames[0].text.startsWith("http://")||s.frames[0].text.startsWith("https://")||(s.urlPrefix=e.substring(0,e.lastIndexOf("/")+1));const n=new Image;n.onload=()=>{s.height=n.naturalHeight,s.width=n.naturalWidth,this.thumbnails.push(s),t()},n.src=s.urlPrefix+s.frames[0].text}))})))),e(this,"startMove",(e=>{if(this.loaded&&F(e)&&["touchmove","mousemove"].includes(e.type)&&this.player.media.duration){if("touchmove"===e.type)this.seekTime=this.player.media.duration*(this.player.elements.inputs.seek.value/100);else{const t=this.player.elements.progress.getBoundingClientRect(),i=100/t.width*(e.pageX-t.left);this.seekTime=this.player.media.duration*(i/100),this.seekTime<0&&(this.seekTime=0),this.seekTime>this.player.media.duration-1&&(this.seekTime=this.player.media.duration-1),this.mousePosX=e.pageX,this.elements.thumb.time.innerText=Ue(this.seekTime)}this.showImageAtCurrentTime()}})),e(this,"endMove",(()=>{this.toggleThumbContainer(!1,!0)})),e(this,"startScrubbing",(e=>{(I(e.button)||!1===e.button||0===e.button)&&(this.mouseDown=!0,this.player.media.duration&&(this.toggleScrubbingContainer(!0),this.toggleThumbContainer(!1,!0),this.showImageAtCurrentTime()))})),e(this,"endScrubbing",(()=>{this.mouseDown=!1,Math.ceil(this.lastTime)===Math.ceil(this.player.media.currentTime)?this.toggleScrubbingContainer(!1):ye.call(this.player,this.player.media,"timeupdate",(()=>{this.mouseDown||this.toggleScrubbingContainer(!1)}))})),e(this,"listeners",(()=>{this.player.on("play",(()=>{this.toggleThumbContainer(!1,!0)})),this.player.on("seeked",(()=>{this.toggleThumbContainer(!1)})),this.player.on("timeupdate",(()=>{this.lastTime=this.player.media.currentTime}))})),e(this,"render",(()=>{this.elements.thumb.container=Z("div",{class:this.player.config.classNames.previewThumbnails.thumbContainer}),this.elements.thumb.imageContainer=Z("div",{class:this.player.config.classNames.previewThumbnails.imageContainer}),this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer);const e=Z("div",{class:this.player.config.classNames.previewThumbnails.timeContainer});this.elements.thumb.time=Z("span",{},"00:00"),e.appendChild(this.elements.thumb.time),this.elements.thumb.container.appendChild(e),H(this.player.elements.progress)&&this.player.elements.progress.appendChild(this.elements.thumb.container),this.elements.scrubbing.container=Z("div",{class:this.player.config.classNames.previewThumbnails.scrubbingContainer}),this.player.elements.wrapper.appendChild(this.elements.scrubbing.container)})),e(this,"destroy",(()=>{this.elements.thumb.container&&this.elements.thumb.container.remove(),this.elements.scrubbing.container&&this.elements.scrubbing.container.remove()})),e(this,"showImageAtCurrentTime",(()=>{this.mouseDown?this.setScrubbingContainerSize():this.setThumbContainerSizeAndPos();const e=this.thumbnails[0].frames.findIndex((e=>this.seekTime>=e.startTime&&this.seekTime<=e.endTime)),t=e>=0;let i=0;this.mouseDown||this.toggleThumbContainer(t),t&&(this.thumbnails.forEach(((t,s)=>{this.loadedImages.includes(t.frames[e].text)&&(i=s)})),e!==this.showingThumb&&(this.showingThumb=e,this.loadImage(i)))})),e(this,"loadImage",((e=0)=>{const t=this.showingThumb,i=this.thumbnails[e],{urlPrefix:s}=i,n=i.frames[t],a=i.frames[t].text,l=s+a;if(this.currentImageElement&&this.currentImageElement.dataset.filename===a)this.showImage(this.currentImageElement,n,e,t,a,!1),this.currentImageElement.dataset.index=t,this.removeOldImages(this.currentImageElement);else{this.loadingImage&&this.usingSprites&&(this.loadingImage.onload=null);const i=new Image;i.src=l,i.dataset.index=t,i.dataset.filename=a,this.showingThumbFilename=a,this.player.debug.log(`Loading image: ${l}`),i.onload=()=>this.showImage(i,n,e,t,a,!0),this.loadingImage=i,this.removeOldImages(i)}})),e(this,"showImage",((e,t,i,s,n,a=!0)=>{this.player.debug.log(`Showing thumb: ${n}. num: ${s}. qual: ${i}. newimg: ${a}`),this.setImageSizeAndOffset(e,t),a&&(this.currentImageContainer.appendChild(e),this.currentImageElement=e,this.loadedImages.includes(n)||this.loadedImages.push(n)),this.preloadNearby(s,!0).then(this.preloadNearby(s,!1)).then(this.getHigherQuality(i,e,t,n))})),e(this,"removeOldImages",(e=>{Array.from(this.currentImageContainer.children).forEach((t=>{if("img"!==t.tagName.toLowerCase())return;const i=this.usingSprites?500:1e3;if(t.dataset.index!==e.dataset.index&&!t.dataset.deleting){t.dataset.deleting=!0;const{currentImageContainer:e}=this;setTimeout((()=>{e.removeChild(t),this.player.debug.log(`Removing thumb: ${t.dataset.filename}`)}),i)}}))})),e(this,"preloadNearby",((e,t=!0)=>new Promise((i=>{setTimeout((()=>{const s=this.thumbnails[0].frames[e].text;if(this.showingThumbFilename===s){let n;n=t?this.thumbnails[0].frames.slice(e):this.thumbnails[0].frames.slice(0,e).reverse();let a=!1;n.forEach((e=>{const t=e.text;if(t!==s&&!this.loadedImages.includes(t)){a=!0,this.player.debug.log(`Preloading thumb filename: ${t}`);const{urlPrefix:e}=this.thumbnails[0],s=e+t,n=new Image;n.src=s,n.onload=()=>{this.player.debug.log(`Preloaded thumb filename: ${t}`),this.loadedImages.includes(t)||this.loadedImages.push(t),i()}}})),a||i()}}),300)})))),e(this,"getHigherQuality",((e,t,i,s)=>{if(e<this.thumbnails.length-1){let n=t.naturalHeight;this.usingSprites&&(n=i.h),n<this.thumbContainerHeight&&setTimeout((()=>{this.showingThumbFilename===s&&(this.player.debug.log(`Showing higher quality thumb for: ${s}`),this.loadImage(e+1))}),300)}})),e(this,"toggleThumbContainer",((e=!1,t=!1)=>{const i=this.player.config.classNames.previewThumbnails.thumbContainerShown;this.elements.thumb.container.classList.toggle(i,e),!e&&t&&(this.showingThumb=null,this.showingThumbFilename=null)})),e(this,"toggleScrubbingContainer",((e=!1)=>{const t=this.player.config.classNames.previewThumbnails.scrubbingContainerShown;this.elements.scrubbing.container.classList.toggle(t,e),e||(this.showingThumb=null,this.showingThumbFilename=null)})),e(this,"determineContainerAutoSizing",(()=>{(this.elements.thumb.imageContainer.clientHeight>20||this.elements.thumb.imageContainer.clientWidth>20)&&(this.sizeSpecifiedInCSS=!0)})),e(this,"setThumbContainerSizeAndPos",(()=>{if(this.sizeSpecifiedInCSS){if(this.elements.thumb.imageContainer.clientHeight>20&&this.elements.thumb.imageContainer.clientWidth<20){const e=Math.floor(this.elements.thumb.imageContainer.clientHeight*this.thumbAspectRatio);this.elements.thumb.imageContainer.style.width=`${e}px`}else if(this.elements.thumb.imageContainer.clientHeight<20&&this.elements.thumb.imageContainer.clientWidth>20){const e=Math.floor(this.elements.thumb.imageContainer.clientWidth/this.thumbAspectRatio);this.elements.thumb.imageContainer.style.height=`${e}px`}}else{const e=Math.floor(this.thumbContainerHeight*this.thumbAspectRatio);this.elements.thumb.imageContainer.style.height=`${this.thumbContainerHeight}px`,this.elements.thumb.imageContainer.style.width=`${e}px`}this.setThumbContainerPos()})),e(this,"setThumbContainerPos",(()=>{const e=this.player.elements.progress.getBoundingClientRect(),t=this.player.elements.container.getBoundingClientRect(),{container:i}=this.elements.thumb,s=t.left-e.left+10,n=t.right-e.left-i.clientWidth-10;let a=this.mousePosX-e.left-i.clientWidth/2;a<s&&(a=s),a>n&&(a=n),i.style.left=`${a}px`})),e(this,"setScrubbingContainerSize",(()=>{const{width:e,height:t}=bt(this.thumbAspectRatio,{width:this.player.media.clientWidth,height:this.player.media.clientHeight});this.elements.scrubbing.container.style.width=`${e}px`,this.elements.scrubbing.container.style.height=`${t}px`})),e(this,"setImageSizeAndOffset",((e,t)=>{if(!this.usingSprites)return;const i=this.thumbContainerHeight/t.h;e.style.height=e.naturalHeight*i+"px",e.style.width=e.naturalWidth*i+"px",e.style.left=`-${t.x*i}px`,e.style.top=`-${t.y*i}px`})),this.player=t,this.thumbnails=[],this.loaded=!1,this.lastMouseMoveTime=Date.now(),this.mouseDown=!1,this.loadedImages=[],this.elements={thumb:{},scrubbing:{}},this.load()}get enabled(){return this.player.isHTML5&&this.player.isVideo&&this.player.config.previewThumbnails.enabled}get currentImageContainer(){return this.mouseDown?this.elements.scrubbing.container:this.elements.thumb.imageContainer}get usingSprites(){return Object.keys(this.thumbnails[0].frames[0]).includes("w")}get thumbAspectRatio(){return this.usingSprites?this.thumbnails[0].frames[0].w/this.thumbnails[0].frames[0].h:this.thumbnails[0].width/this.thumbnails[0].height}get thumbContainerHeight(){if(this.mouseDown){const{height:e}=bt(this.thumbAspectRatio,{width:this.player.media.clientWidth,height:this.player.media.clientHeight});return e}return this.sizeSpecifiedInCSS?this.elements.thumb.imageContainer.clientHeight:Math.floor(this.player.media.clientWidth/this.thumbAspectRatio/4)}get currentImageElement(){return this.mouseDown?this.currentScrubbingImageElement:this.currentThumbnailImageElement}set currentImageElement(e){this.mouseDown?this.currentScrubbingImageElement=e:this.currentThumbnailImageElement=e}}const vt={insertElements(e,t){_(t)?ee(e,this.media,{src:t}):q(t)&&t.forEach((t=>{ee(e,this.media,t)}))},change(e){Q(e,"sources.length")?(Le.cancelRequests.call(this),this.destroy.call(this,(()=>{this.options.quality=[],te(this.media),this.media=null,H(this.elements.container)&&this.elements.container.removeAttribute("class");const{sources:t,type:i}=e,[{provider:s=Ge.html5,src:n}]=t,a="html5"===s?i:"div",l="html5"===s?{}:{src:n};Object.assign(this,{provider:s,type:i,supported:me.check(i,s,this.config.playsinline),media:Z(a,l)}),this.elements.container.appendChild(this.media),O(e.autoplay)&&(this.config.autoplay=e.autoplay),this.isHTML5&&(this.config.crossorigin&&this.media.setAttribute("crossorigin",""),this.config.autoplay&&this.media.setAttribute("autoplay",""),W(e.poster)||(this.poster=e.poster),this.config.loop.active&&this.media.setAttribute("loop",""),this.config.muted&&this.media.setAttribute("muted",""),this.config.playsinline&&this.media.setAttribute("playsinline","")),at.addStyleHook.call(this),this.isHTML5&&vt.insertElements.call(this,"source",t),this.config.title=e.title,pt.setup.call(this),this.isHTML5&&Object.keys(e).includes("tracks")&&vt.insertElements.call(this,"track",e.tracks),(this.isHTML5||this.isEmbed&&!this.supported.ui)&&at.build.call(this),this.isHTML5&&this.media.load(),W(e.previewThumbnails)||(Object.assign(this.config.previewThumbnails,e.previewThumbnails),this.previewThumbnails&&this.previewThumbnails.loaded&&(this.previewThumbnails.destroy(),this.previewThumbnails=null),this.config.previewThumbnails.enabled&&(this.previewThumbnails=new yt(this))),this.fullscreen.update()}),!0)):this.debug.warn("Invalid source format")}};class wt{constructor(t,i){if(e(this,"play",(()=>j(this.media.play)?(this.ads&&this.ads.enabled&&this.ads.managerPromise.then((()=>this.ads.play())).catch((()=>ke(this.media.play()))),this.media.play()):null)),e(this,"pause",(()=>this.playing&&j(this.media.pause)?this.media.pause():null)),e(this,"togglePlay",(e=>(O(e)?e:!this.playing)?this.play():this.pause())),e(this,"stop",(()=>{this.isHTML5?(this.pause(),this.restart()):j(this.media.stop)&&this.media.stop()})),e(this,"restart",(()=>{this.currentTime=0})),e(this,"rewind",(e=>{this.currentTime-=$(e)?e:this.config.seekTime})),e(this,"forward",(e=>{this.currentTime+=$(e)?e:this.config.seekTime})),e(this,"increaseVolume",(e=>{const t=this.media.muted?0:this.volume;this.volume=t+($(e)?e:0)})),e(this,"decreaseVolume",(e=>{this.increaseVolume(-e)})),e(this,"airplay",(()=>{me.airplay&&this.media.webkitShowPlaybackTargetPicker()})),e(this,"toggleControls",(e=>{if(this.supported.ui&&!this.isAudio){const t=oe(this.elements.container,this.config.classNames.hideControls),i=void 0===e?void 0:!e,s=le(this.elements.container,this.config.classNames.hideControls,i);if(s&&q(this.config.controls)&&this.config.controls.includes("settings")&&!W(this.config.settings)&&We.toggleMenu.call(this,!1),s!==t){const e=s?"controlshidden":"controlsshown";ve.call(this,this.media,e)}return!s}return!1})),e(this,"on",((e,t)=>{fe.call(this,this.elements.container,e,t)})),e(this,"once",((e,t)=>{ye.call(this,this.elements.container,e,t)})),e(this,"off",((e,t)=>{be(this.elements.container,e,t)})),e(this,"destroy",((e,t=!1)=>{if(!this.ready)return;const i=()=>{document.body.style.overflow="",this.embed=null,t?(Object.keys(this.elements).length&&(te(this.elements.buttons.play),te(this.elements.captions),te(this.elements.controls),te(this.elements.wrapper),this.elements.buttons.play=null,this.elements.captions=null,this.elements.controls=null,this.elements.wrapper=null),j(e)&&e()):(we.call(this),Le.cancelRequests.call(this),se(this.elements.original,this.elements.container),ve.call(this,this.elements.original,"destroyed",!0),j(e)&&e.call(this.elements.original),this.ready=!1,setTimeout((()=>{this.elements=null,this.media=null}),200))};this.stop(),clearTimeout(this.timers.loading),clearTimeout(this.timers.controls),clearTimeout(this.timers.resized),this.isHTML5?(at.toggleNativeControls.call(this,!0),i()):this.isYouTube?(clearInterval(this.timers.buffering),clearInterval(this.timers.playing),null!==this.embed&&j(this.embed.destroy)&&this.embed.destroy(),i()):this.isVimeo&&(null!==this.embed&&this.embed.unload().then(i),setTimeout(i,200))})),e(this,"supports",(e=>me.mime.call(this,e))),this.timers={},this.ready=!1,this.loading=!1,this.failed=!1,this.touch=me.touch,this.media=t,_(this.media)&&(this.media=document.querySelectorAll(this.media)),(window.jQuery&&this.media instanceof jQuery||D(this.media)||q(this.media))&&(this.media=this.media[0]),this.config=X({},Qe,wt.defaults,i||{},(()=>{try{return JSON.parse(this.media.getAttribute("data-plyr-config"))}catch(e){return{}}})()),this.elements={container:null,fullscreen:null,captions:null,buttons:{},display:{},progress:{},inputs:{},settings:{popup:null,menu:null,panels:{},buttons:{}}},this.captions={active:null,currentTrack:-1,meta:new WeakMap},this.fullscreen={active:!1},this.options={speed:[],quality:[]},this.debug=new it(this.config.debug),this.debug.log("Config",this.config),this.debug.log("Support",me),I(this.media)||!H(this.media))return void this.debug.error("Setup failed: no suitable element passed");if(this.media.plyr)return void this.debug.warn("Target already setup");if(!this.config.enabled)return void this.debug.error("Setup failed: disabled by config");if(!me.check().api)return void this.debug.error("Setup failed: no support");const s=this.media.cloneNode(!0);s.autoplay=!1,this.elements.original=s;const n=this.media.tagName.toLowerCase();let a=null,l=null;switch(n){case"div":if(a=this.media.querySelector("iframe"),H(a)){if(l=ze(a.getAttribute("src")),this.provider=function(e){return/^(https?:\/\/)?(www\.)?(youtube\.com|youtube-nocookie\.com|youtu\.?be)\/.+$/.test(e)?Ge.youtube:/^https?:\/\/player.vimeo.com\/video\/\d{0,9}(?=\b|\/)/.test(e)?Ge.vimeo:null}(l.toString()),this.elements.container=this.media,this.media=a,this.elements.container.className="",l.search.length){const e=["1","true"];e.includes(l.searchParams.get("autoplay"))&&(this.config.autoplay=!0),e.includes(l.searchParams.get("loop"))&&(this.config.loop.active=!0),this.isYouTube?(this.config.playsinline=e.includes(l.searchParams.get("playsinline")),this.config.youtube.hl=l.searchParams.get("hl")):this.config.playsinline=!0}}else this.provider=this.media.getAttribute(this.config.attributes.embed.provider),this.media.removeAttribute(this.config.attributes.embed.provider);if(W(this.provider)||!Object.values(Ge).includes(this.provider))return void this.debug.error("Setup failed: Invalid provider");this.type=et;break;case"video":case"audio":this.type=n,this.provider=Ge.html5,this.media.hasAttribute("crossorigin")&&(this.config.crossorigin=!0),this.media.hasAttribute("autoplay")&&(this.config.autoplay=!0),(this.media.hasAttribute("playsinline")||this.media.hasAttribute("webkit-playsinline"))&&(this.config.playsinline=!0),this.media.hasAttribute("muted")&&(this.config.muted=!0),this.media.hasAttribute("loop")&&(this.config.loop.active=!0);break;default:return void this.debug.error("Setup failed: unsupported type")}this.supported=me.check(this.type,this.provider,this.config.playsinline),this.supported.api?(this.eventListeners=[],this.listeners=new lt(this),this.storage=new Fe(this),this.media.plyr=this,H(this.elements.container)||(this.elements.container=Z("div",{tabindex:0}),J(this.media,this.elements.container)),at.migrateStyles.call(this),at.addStyleHook.call(this),pt.setup.call(this),this.config.debug&&fe.call(this,this.elements.container,this.config.events.join(" "),(e=>{this.debug.log(`event: ${e.type}`)})),this.fullscreen=new st(this),(this.isHTML5||this.isEmbed&&!this.supported.ui)&&at.build.call(this),this.listeners.container(),this.listeners.global(),this.config.ads.enabled&&(this.ads=new gt(this)),this.isHTML5&&this.config.autoplay&&this.once("canplay",(()=>ke(this.play()))),this.lastSeekTime=0,this.config.previewThumbnails.enabled&&(this.previewThumbnails=new yt(this))):this.debug.error("Setup failed: no support")}get isHTML5(){return this.provider===Ge.html5}get isEmbed(){return this.isYouTube||this.isVimeo}get isYouTube(){return this.provider===Ge.youtube}get isVimeo(){return this.provider===Ge.vimeo}get isVideo(){return this.type===et}get isAudio(){return this.type===Ze}get playing(){return Boolean(this.ready&&!this.paused&&!this.ended)}get paused(){return Boolean(this.media.paused)}get stopped(){return Boolean(this.paused&&0===this.currentTime)}get ended(){return Boolean(this.media.ended)}set currentTime(e){if(!this.duration)return;const t=$(e)&&e>0;this.media.currentTime=t?Math.min(e,this.duration):0,this.debug.log(`Seeking to ${this.currentTime} seconds`)}get currentTime(){return Number(this.media.currentTime)}get buffered(){const{buffered:e}=this.media;return $(e)?e:e&&e.length&&this.duration>0?e.end(0)/this.duration:0}get seeking(){return Boolean(this.media.seeking)}get duration(){const e=parseFloat(this.config.duration),t=(this.media||{}).duration,i=$(t)&&t!==1/0?t:0;return e||i}set volume(e){let t=e;_(t)&&(t=Number(t)),$(t)||(t=this.storage.get("volume")),$(t)||({volume:t}=this.config),t>1&&(t=1),t<0&&(t=0),this.config.volume=t,this.media.volume=t,!W(e)&&this.muted&&t>0&&(this.muted=!1)}get volume(){return Number(this.media.volume)}set muted(e){let t=e;O(t)||(t=this.storage.get("muted")),O(t)||(t=this.config.muted),this.config.muted=t,this.media.muted=t}get muted(){return Boolean(this.media.muted)}get hasAudio(){return!this.isHTML5||(!!this.isAudio||(Boolean(this.media.mozHasAudio)||Boolean(this.media.webkitAudioDecodedByteCount)||Boolean(this.media.audioTracks&&this.media.audioTracks.length)))}set speed(e){let t=null;$(e)&&(t=e),$(t)||(t=this.storage.get("speed")),$(t)||(t=this.config.speed.selected);const{minimumSpeed:i,maximumSpeed:s}=this;t=function(e=0,t=0,i=255){return Math.min(Math.max(e,t),i)}(t,i,s),this.config.speed.selected=t,setTimeout((()=>{this.media&&(this.media.playbackRate=t)}),0)}get speed(){return Number(this.media.playbackRate)}get minimumSpeed(){return this.isYouTube?Math.min(...this.options.speed):this.isVimeo?.5:.0625}get maximumSpeed(){return this.isYouTube?Math.max(...this.options.speed):this.isVimeo?2:16}set quality(e){const t=this.config.quality,i=this.options.quality;if(!i.length)return;let s=[!W(e)&&Number(e),this.storage.get("quality"),t.selected,t.default].find($),n=!0;if(!i.includes(s)){const e=Ae(i,s);this.debug.warn(`Unsupported quality option: ${s}, using ${e} instead`),s=e,n=!1}t.selected=s,this.media.quality=s,n&&this.storage.set({quality:s})}get quality(){return this.media.quality}set loop(e){const t=O(e)?e:this.config.loop.active;this.config.loop.active=t,this.media.loop=t}get loop(){return Boolean(this.media.loop)}set source(e){vt.change.call(this,e)}get source(){return this.media.currentSrc}get download(){const{download:e}=this.config.urls;return U(e)?e:this.source}set download(e){U(e)&&(this.config.urls.download=e,We.setDownloadUrl.call(this))}set poster(e){this.isVideo?at.setPoster.call(this,e,!1).catch((()=>{})):this.debug.warn("Poster can only be set for video")}get poster(){return this.isVideo?this.media.getAttribute("poster")||this.media.getAttribute("data-poster"):null}get ratio(){if(!this.isVideo)return null;const e=Ne(xe.call(this));return q(e)?e.join(":"):e}set ratio(e){this.isVideo?_(e)&&Pe(e)?(this.config.ratio=Ne(e),Me.call(this)):this.debug.error(`Invalid aspect ratio specified (${e})`):this.debug.warn("Aspect ratio can only be set for video")}set autoplay(e){const t=O(e)?e:this.config.autoplay;this.config.autoplay=t}get autoplay(){return Boolean(this.config.autoplay)}toggleCaptions(e){Ye.toggle.call(this,e,!1)}set currentTrack(e){Ye.set.call(this,e,!1),Ye.setup()}get currentTrack(){const{toggled:e,currentTrack:t}=this.captions;return e?t:-1}set language(e){Ye.setLanguage.call(this,e,!1)}get language(){return(Ye.getCurrentTrack.call(this)||{}).language}set pip(e){if(!me.pip)return;const t=O(e)?e:!this.pip;j(this.media.webkitSetPresentationMode)&&this.media.webkitSetPresentationMode(t?Xe:Je),j(this.media.requestPictureInPicture)&&(!this.pip&&t?this.media.requestPictureInPicture():this.pip&&!t&&document.exitPictureInPicture())}get pip(){return me.pip?W(this.media.webkitPresentationMode)?this.media===document.pictureInPictureElement:this.media.webkitPresentationMode===Xe:null}setPreviewThumbnails(e){this.previewThumbnails&&this.previewThumbnails.loaded&&(this.previewThumbnails.destroy(),this.previewThumbnails=null),Object.assign(this.config.previewThumbnails,e),this.config.previewThumbnails.enabled&&(this.previewThumbnails=new yt(this))}static supported(e,t,i){return me.check(e,t,i)}static loadSprite(e,t){return Ve(e,t)}static setup(e,t={}){let i=null;return _(e)?i=Array.from(document.querySelectorAll(e)):D(e)?i=Array.from(e):q(e)&&(i=e.filter(H)),W(i)?null:i.map((e=>new wt(e,t)))}}var Tt;return wt.defaults=(Tt=Qe,JSON.parse(JSON.stringify(Tt))),wt})); +//# sourceMappingURL=plyr.min.js.map diff --git a/extlib/plyr/plyr.min.js.map b/extlib/plyr/plyr.min.js.map new file mode 100644 index 00000000..664c3a0d --- /dev/null +++ b/extlib/plyr/plyr.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["plyr.js","node_modules/rangetouch/dist/rangetouch.mjs","src/js/utils/is.js","src/js/utils/animation.js","src/js/utils/browser.js","src/js/utils/objects.js","src/js/utils/elements.js","src/js/support.js","src/js/utils/events.js","src/js/utils/promise.js","src/js/utils/arrays.js","src/js/utils/style.js","src/js/html5.js","src/js/utils/strings.js","src/js/utils/i18n.js","src/js/storage.js","src/js/utils/fetch.js","src/js/utils/load-sprite.js","src/js/utils/time.js","src/js/controls.js","src/js/utils/urls.js","src/js/captions.js","src/js/config/defaults.js","src/js/config/states.js","src/js/config/types.js","src/js/console.js","src/js/fullscreen.js","src/js/utils/load-image.js","src/js/ui.js","src/js/listeners.js","node_modules/loadjs/dist/loadjs.umd.js","src/js/utils/load-script.js","src/js/plugins/vimeo.js","src/js/plugins/youtube.js","src/js/media.js","src/js/plugins/ads.js","src/js/plugins/preview-thumbnails.js","src/js/source.js","src/js/plyr.js","src/js/utils/numbers.js"],"names":["navigator","global","factory","exports","module","define","amd","globalThis","self","Plyr","this","_defineProperty$1","obj","key","value","Object","defineProperty","enumerable","configurable","writable","_defineProperties","e","t","n","length","r","_defineProperty","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","push","apply","_objectSpread2","arguments","forEach","getOwnPropertyDescriptors","defineProperties","defaults","addCSS","thumbWidth","watch","matches","Array","from","document","querySelectorAll","includes","call","getConstructor","constructor","instanceOf","isNullOrUndefined","isObject","isString","String","isArray","isNodeList","NodeList","is","Element","Event","round","concat","match","Math","max","getDecimalPlaces","parseFloat","toFixed","RangeTouch","TypeError","_classCallCheck","element","querySelector","rangeTouch","config","init","prototype","_createClass","enabled","style","userSelect","webKitUserSelect","touchAction","listeners","set","target","i","changedTouches","o","getAttribute","s","u","c","getBoundingClientRect","a","width","clientX","left","disabled","preventDefault","get","bubbles","dispatchEvent","trigger","type","MutationObserver","addedNodes","observe","body","childList","subtree","map","documentElement","input","Boolean","isFunction","Function","isEmpty","Number","isNaN","nodeType","ownerDocument","KeyboardEvent","TextTrack","kind","Promise","then","window","URL","string","startsWith","hostname","_","transitionEndEvent","createElement","events","WebkitTransition","MozTransition","OTransition","transition","find","event","undefined","repaint","delay","setTimeout","hidden","offsetHeight","browser","isIE","documentMode","isEdge","userAgent","isWebkit","test","isIPhone","platform","isIos","maxTouchPoints","getDeep","object","path","split","reduce","extend","sources","source","shift","assign","wrap","elements","wrapper","targets","reverse","index","child","cloneNode","parent","parentNode","sibling","nextSibling","appendChild","insertBefore","setAttributes","attributes","entries","setAttribute","text","innerText","insertElement","removeElement","removeChild","emptyElement","childNodes","lastChild","replaceElement","newChild","oldChild","replaceChild","getAttributesFromSelector","sel","existingAttributes","existing","selector","trim","className","replace","parts","charAt","class","id","toggleHidden","hide","toggleClass","force","method","classList","contains","hasClass","webkitMatchesSelector","mozMatchesSelector","msMatchesSelector","getElements","container","getElement","setFocus","tabFocus","focus","preventScroll","classNames","defaultCodecs","support","audio","video","check","provider","playsinline","canPlayInline","api","ui","rangeInput","pip","webkitSetPresentationMode","pictureInPictureEnabled","disablePictureInPicture","airplay","WebKitPlaybackTargetAvailabilityEvent","mime","mediaType","isHTML5","media","canPlayType","textTracks","range","touch","transitions","reducedMotion","matchMedia","supportsPassiveListeners","supported","options","addEventListener","removeEventListener","toggleListener","callback","toggle","passive","capture","eventListeners","on","off","once","onceCallback","args","triggerEvent","detail","CustomEvent","plyr","unbindListeners","item","ready","resolve","silencePromise","dedupe","array","indexOf","closest","prev","curr","abs","supportsCSS","declaration","CSS","supports","standardRatios","out","x","y","validateAspectRatio","every","reduceAspectRatio","ratio","height","getDivider","w","h","divider","getAspectRatio","parse","embed","videoWidth","videoHeight","setAspectRatio","isVideo","padding","aspectRatio","paddingBottom","isVimeo","vimeo","premium","offsetWidth","parseInt","getComputedStyle","offset","fullscreen","active","transform","add","videoFixedRatio","roundAspectRatio","tolerance","closestRatio","html5","getSources","getQualityOptions","quality","forced","setup","player","speed","onChange","currentTime","paused","preload","readyState","playbackRate","src","play","load","cancelRequests","blankVideo","debug","log","format","toString","replaceAll","RegExp","toTitleCase","toUpperCase","substr","toLowerCase","toCamelCase","toPascalCase","slice","getHTML","innerHTML","resources","youtube","i18n","seekTime","title","k","v","Storage","store","localStorage","getItem","json","JSON","storage","setItem","stringify","removeItem","fetch","url","responseType","reject","request","XMLHttpRequest","responseText","response","Error","status","open","send","error","loadSprite","hasId","isCached","exists","getElementById","update","data","insertAdjacentElement","useStorage","cached","content","result","catch","getHours","trunc","formatTime","time","displayHours","inverted","hours","mins","secs","getSeconds","controls","getIconUrl","iconUrl","location","host","top","cors","svg4everybody","findElements","selectors","buttons","pause","restart","rewind","fastForward","mute","settings","captions","progress","inputs","seek","volume","display","buffer","duration","seekTooltip","tooltip","warn","toggleNativeControls","createIcon","namespace","iconPath","iconPrefix","icon","createElementNS","focusable","use","setAttributeNS","createLabel","attr","join","createBadge","badge","menu","createButton","buttonType","props","label","labelPressed","iconPressed","some","control","button","createRange","min","step","autocomplete","role","updateRangeFill","createProgress","suffixKey","played","suffix","createTime","attrs","bindMenuItemShortcuts","menuItem","which","stopPropagation","isRadioButton","showMenuPanel","nextElementSibling","firstElementChild","previousElementSibling","lastElementChild","focusFirstMenuItem","createMenuItem","list","checked","flex","children","node","bind","currentTrack","updateTimeDisplay","updateVolume","setRange","muted","pressed","updateProgress","setProgress","val","getElementsByTagName","nodeValue","current","buffered","percent","setProperty","updateSeekTooltip","tooltips","visible","show","clientRect","pageX","timeUpdate","invert","invertTime","seeking","durationUpdate","hasDuration","displayDuration","toggleMenuButton","setting","updateSetting","pane","panels","default","getLabel","setQualityMenu","checkMenu","getBadge","sort","b","sorting","setCaptionsMenu","tracks","getTracks","track","toggled","language","unshift","setSpeedMenu","minimumSpeed","maximumSpeed","values","popup","p","firstItem","toggleMenu","composedPath","isMenuItem","getMenuSize","tab","clone","position","opacity","removeAttribute","scrollWidth","scrollHeight","size","restore","propertyName","setDownloadUrl","download","create","defaultAttributes","progressContainer","inner","home","backButton","href","urls","isEmbed","inject","floor","random","seektime","addProperty","controlPressed","labels","parseUrl","safe","parser","buildUrlParams","params","URLSearchParams","isYouTube","protocol","blob","createObjectURL","languages","userLanguage","trackEvents","meta","currentTrackNode","languageExists","mode","updateCues","setLanguage","activeClass","findTrack","enableTextTrack","has","sortIsDefault","sorted","getCurrentTrack","cues","activeCues","cue","getCueAsHTML","cueText","caption","autoplay","autopause","toggleInvert","clickToPlay","hideControls","resetOnEnd","disableContextMenu","loop","selected","keyboard","focused","fallback","iosNative","seekLabel","unmute","enableCaptions","disableCaptions","enterFullscreen","exitFullscreen","frameTitle","menuBack","normal","start","end","all","reset","advertisement","qualityBadge","sdk","iframe","googleIMA","editable","embedContainer","poster","posterEnabled","ads","playing","stopped","loading","hover","isTouch","uiSupported","noTransition","previewThumbnails","thumbContainer","thumbContainerShown","imageContainer","timeContainer","scrubbingContainer","scrubbingContainerShown","hash","publisherId","tagUrl","byline","portrait","transparent","customControls","referrerPolicy","rel","showinfo","iv_load_policy","modestbranding","noCookie","providers","types","noop","Console","console","Fullscreen","scrollPosition","scrollX","scrollY","scrollTo","overflow","viewport","head","property","hasProperty","cleanupViewport","part","keyCode","activeElement","first","last","shiftKey","forceFallback","native","requestFullscreen","webkitEnterFullscreen","toggleFallback","prefix","navigationUI","webkitExitFullscreen","action","cancelFullScreen","exit","enter","el","parentElement","proxy","trapFocus","fullscreenEnabled","webkitFullscreenEnabled","mozFullScreenEnabled","msFullscreenEnabled","usingNative","pre","getRootNode","fullscreenElement","shadowRoot","loadImage","minWidth","image","Image","handler","onload","onerror","naturalWidth","addStyleHook","build","checkPlaying","setTitle","setPoster","togglePoster","enable","backgroundImage","backgroundSize","toggleControls","checkLoading","clearTimeout","timers","controlsElement","recentTouchSeek","lastSeekTime","Date","now","migrateStyles","getPropertyValue","removeProperty","Listeners","focusTimer","lastKeyDown","timeStamp","wasKeyDown","removeCurrent","handleKey","firstTouch","setTabFocus","setGutter","useNativeAspectRatio","maxWidth","margin","viewportWidth","viewportHeight","clientWidth","innerWidth","clientHeight","innerHeight","resized","isAudio","ended","togglePlay","proxyEvents","defaultHandler","customHandlerKey","customHandler","returned","hasCustomHandler","inputEvent","forward","toggleCaptions","code","rect","currentTarget","attribute","hasAttribute","done","seekTo","loaded","startMove","endMove","startScrubbing","endScrubbing","webkitDirectionInvertedFromDevice","deltaX","deltaY","direction","sign","increaseVolume","lastKey","repeat","altKey","ctrlKey","metaKey","decreaseVolume","loadjs_umd","fn","createCommonjsModule","devnull","bundleIdCache","bundleResultCache","bundleCallbackQueue","subscribe","bundleIds","callbackFn","bundleId","depsNotFound","numWaiting","pathsNotFound","publish","q","splice","executeCallbacks","success","loadFile","numTries","isLegacyIECss","doc","async","maxTries","numRetries","beforeCallbackFn","before","pathname","pathStripped","relList","as","onbeforeload","ev","sheet","cssText","defaultPrevented","loadFiles","paths","loadjs","arg1","arg2","loadFn","returnPromise","deps","isDefined","loadScript","assurePlaybackState","hasPlayed","Vimeo","frameParams","found","groups","parseHash","hashParam","sidedock","gesture","$2","thumbnail_url","Player","disableTextTrack","stop","restorePause","setVolume","setCurrentTime","setPlaybackRate","currentSrc","setLoop","getVideoUrl","getVideoWidth","getVideoHeight","dimensions","setAutopause","state","getVideoTitle","getCurrentTime","getDuration","getTextTracks","strippedCues","fragment","createDocumentFragment","firstChild","stripHTML","getPaused","seconds","getHost","YT","onYouTubeIframeAPIReady","getTitle","videoId","currentId","posterSrc","playerVars","hl","disablekb","cc_load_policy","cc_lang_pref","widget_referrer","onError","message","onPlaybackRateChange","instance","getPlaybackRate","onReady","playVideo","pauseVideo","stopVideo","speeds","getAvailablePlaybackRates","clearInterval","buffering","setInterval","getVideoLoadedFraction","lastBuffered","onStateChange","unMute","Ads","google","ima","manager","destroy","displayContainer","remove","startSafetyTimer","managerPromise","clearSafetyTimer","setupIMA","setVpaidMode","ImaSdkSettings","VpaidMode","ENABLED","setLocale","setDisableCustomPlaybackForIOS10Plus","AdDisplayContainer","loader","AdsLoader","AdsManagerLoadedEvent","Type","ADS_MANAGER_LOADED","onAdsManagerLoaded","AdErrorEvent","AD_ERROR","onAdError","requestAds","AdsRequest","adTagUrl","linearAdSlotWidth","linearAdSlotHeight","nonLinearAdSlotWidth","nonLinearAdSlotHeight","forceNonLinearFullSlot","setAdWillPlayMuted","countdownTimer","getRemainingTime","AdsRenderingSettings","restoreCustomPlaybackStateOnAdBreakComplete","enablePreloading","getAdsManager","cuePoints","getCuePoints","AdEvent","onAdEvent","cuePoint","seekElement","cuePercentage","ad","getAd","adData","getAdData","LOADED","pollCountdown","isLinear","STARTED","ALL_ADS_COMPLETED","loadAds","contentComplete","CONTENT_PAUSE_REQUESTED","pauseContent","CONTENT_RESUME_REQUESTED","resumeContent","LOG","adError","getMessage","cancel","addCuePoints","seekedTime","discardAdBreak","resize","ViewMode","NORMAL","initialize","initialized","zIndex","handlers","safetyTimer","AV_PUBLISHERID","AV_CHANNELID","AV_URL","cb","AV_WIDTH","AV_HEIGHT","AV_CDIM2","parseVtt","vttDataString","processedList","frame","line","startTime","lineSplit","matchTimes","endTime","fitRatio","outer","PreviewThumbnails","getThumbnails","render","determineContainerAutoSizing","sortAndResolve","thumbnails","promises","getThumbnail","thumbnail","frames","urlPrefix","substring","lastIndexOf","tempImage","naturalHeight","percentage","mousePosX","thumb","showImageAtCurrentTime","toggleThumbContainer","mouseDown","toggleScrubbingContainer","ceil","lastTime","scrubbing","setScrubbingContainerSize","setThumbContainerSizeAndPos","thumbNum","findIndex","hasThumb","qualityIndex","loadedImages","showingThumb","thumbFilename","thumbUrl","currentImageElement","dataset","filename","showImage","removeOldImages","loadingImage","usingSprites","previewImage","showingThumbFilename","newImage","setImageSizeAndOffset","currentImageContainer","preloadNearby","getHigherQuality","currentImage","tagName","removeDelay","deleting","oldThumbFilename","thumbnailsClone","foundOne","newThumbFilename","thumbURL","currentQualityIndex","previewImageHeight","thumbContainerHeight","clearShowing","sizeSpecifiedInCSS","thumbAspectRatio","thumbHeight","setThumbContainerPos","seekbarRect","plyrRect","minVal","maxVal","right","previewPos","multiplier","lastMouseMoveTime","currentScrubbingImageElement","currentThumbnailImageElement","insertElements","change","crossorigin","webkitShowPlaybackTargetPicker","isHidden","hiding","eventName","soft","original","unload","failed","jQuery","WeakMap","getProviderByUrl","search","truthy","searchParams","tabindex","inputIsValid","fauxDuration","realDuration","Infinity","hasAudio","mozHasAudio","webkitAudioDecodedByteCount","audioTracks","clamp","updateStorage","requestPictureInPicture","exitPictureInPicture","webkitPresentationMode","pictureInPictureElement","setPreviewThumbnails","thumbnailSource","static","inline"],"mappings":"AAAqB,iBAAdA,WAA0B,SAAWC,EAAQC,GAC/B,iBAAZC,SAA0C,oBAAXC,OAAyBA,OAAOD,QAAUD,IAC9D,mBAAXG,QAAyBA,OAAOC,IAAMD,OAAO,OAAQH,IAC3DD,EAA+B,oBAAfM,WAA6BA,WAAaN,GAAUO,MAAaC,KAAOP,IAH1D,CAI9BQ,MAAM,WAAe,aAEtB,SAASC,EAAkBC,EAAKC,EAAKC,GAYnC,OAXID,KAAOD,EACTG,OAAOC,eAAeJ,EAAKC,EAAK,CAC9BC,MAAOA,EACPG,YAAY,EACZC,cAAc,EACdC,UAAU,IAGZP,EAAIC,GAAOC,EAGNF,EClBiG,SAASQ,EAAkBC,EAAEC,GAAG,IAAI,IAAIC,EAAE,EAAEA,EAAED,EAAEE,OAAOD,IAAI,CAAC,IAAIE,EAAEH,EAAEC,GAAGE,EAAER,WAAWQ,EAAER,aAAY,EAAGQ,EAAEP,cAAa,EAAG,UAAUO,IAAIA,EAAEN,UAAS,GAAIJ,OAAOC,eAAeK,EAAEI,EAAEZ,IAAIY,IAAwG,SAASC,EAAgBL,EAAEC,EAAEC,GAAG,OAAOD,KAAKD,EAAEN,OAAOC,eAAeK,EAAEC,EAAE,CAACR,MAAMS,EAAEN,YAAW,EAAGC,cAAa,EAAG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mP,MAAMq3B,wBAKlBxmC,KAAKmP,QAAU/M,SAASqkC,wBAJtBzmC,KAAKmP,MAAMq3B,yBAA2B93B,GALtC,KAeXg4B,qBAAqBC,GACf3mC,KAAKipB,mBAAqBjpB,KAAKipB,kBAAkBuI,SACnDxxB,KAAKipB,kBAAkBgR,UACvBj6B,KAAKipB,kBAAoB,MAG3B5oB,OAAO4J,OAAOjK,KAAKmE,OAAO8kB,kBAAmB0d,GAGzC3mC,KAAKmE,OAAO8kB,kBAAkB1kB,UAChCvE,KAAKipB,kBAAoB,IAAI6W,GAAkB9/B,OAqMnC4mC,iBAAC3gC,EAAMmI,EAAUy4B,GAC/B,OAAO74B,GAAQG,MAAMlI,EAAMmI,EAAUy4B,GAQtBD,kBAACnvB,EAAK9K,GACrB,OAAO0L,GAAWZ,EAAK9K,GAQbi6B,aAACx6B,EAAUyD,EAAU,IAC/B,IAAIxF,EAAU,KAUd,OARInH,EAAUkJ,GACZ/B,EAAUnI,MAAMC,KAAKC,SAASC,iBAAiB+J,IACtClJ,EAAYkJ,GACrB/B,EAAUnI,MAAMC,KAAKiK,GACZlJ,EAASkJ,KAClB/B,EAAU+B,EAAShL,OAAO8B,IAGxBA,EAASmH,GACJ,KAGFA,EAAQ7D,KAAK5F,GAAM,IAAIb,GAAKa,EAAGiP,MjCtvCnC,IAAmBpG,GL49QxB,OsCluOF1J,GAAK8B,UjC1vCqB4H,GiC0vCA5H,GjCzvCjBsV,KAAKtE,MAAMsE,KAAKG,UAAU7N,ML29Q1B1J","file":"plyr.min.js","sourcesContent":["typeof navigator === \"object\" && (function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define('Plyr', factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Plyr = factory());\n})(this, (function () { 'use strict';\n\n function _defineProperty$1(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n }\n\n function _classCallCheck(e, t) {\n if (!(e instanceof t)) throw new TypeError(\"Cannot call a class as a function\");\n }\n\n function _defineProperties(e, t) {\n for (var n = 0; n < t.length; n++) {\n var r = t[n];\n r.enumerable = r.enumerable || !1, r.configurable = !0, \"value\" in r && (r.writable = !0), Object.defineProperty(e, r.key, r);\n }\n }\n\n function _createClass(e, t, n) {\n return t && _defineProperties(e.prototype, t), n && _defineProperties(e, n), e;\n }\n\n function _defineProperty(e, t, n) {\n return t in e ? Object.defineProperty(e, t, {\n value: n,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[t] = n, e;\n }\n\n function ownKeys(e, t) {\n var n = Object.keys(e);\n\n if (Object.getOwnPropertySymbols) {\n var r = Object.getOwnPropertySymbols(e);\n t && (r = r.filter(function (t) {\n return Object.getOwnPropertyDescriptor(e, t).enumerable;\n })), n.push.apply(n, r);\n }\n\n return n;\n }\n\n function _objectSpread2(e) {\n for (var t = 1; t < arguments.length; t++) {\n var n = null != arguments[t] ? arguments[t] : {};\n t % 2 ? ownKeys(Object(n), !0).forEach(function (t) {\n _defineProperty(e, t, n[t]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : ownKeys(Object(n)).forEach(function (t) {\n Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));\n });\n }\n\n return e;\n }\n\n var defaults$1 = {\n addCSS: !0,\n thumbWidth: 15,\n watch: !0\n };\n\n function matches$1(e, t) {\n return function () {\n return Array.from(document.querySelectorAll(t)).includes(this);\n }.call(e, t);\n }\n\n function trigger(e, t) {\n if (e && t) {\n var n = new Event(t, {\n bubbles: !0\n });\n e.dispatchEvent(n);\n }\n }\n\n var getConstructor$1 = function (e) {\n return null != e ? e.constructor : null;\n },\n instanceOf$1 = function (e, t) {\n return !!(e && t && e instanceof t);\n },\n isNullOrUndefined$1 = function (e) {\n return null == e;\n },\n isObject$1 = function (e) {\n return getConstructor$1(e) === Object;\n },\n isNumber$1 = function (e) {\n return getConstructor$1(e) === Number && !Number.isNaN(e);\n },\n isString$1 = function (e) {\n return getConstructor$1(e) === String;\n },\n isBoolean$1 = function (e) {\n return getConstructor$1(e) === Boolean;\n },\n isFunction$1 = function (e) {\n return getConstructor$1(e) === Function;\n },\n isArray$1 = function (e) {\n return Array.isArray(e);\n },\n isNodeList$1 = function (e) {\n return instanceOf$1(e, NodeList);\n },\n isElement$1 = function (e) {\n return instanceOf$1(e, Element);\n },\n isEvent$1 = function (e) {\n return instanceOf$1(e, Event);\n },\n isEmpty$1 = function (e) {\n return isNullOrUndefined$1(e) || (isString$1(e) || isArray$1(e) || isNodeList$1(e)) && !e.length || isObject$1(e) && !Object.keys(e).length;\n },\n is$1 = {\n nullOrUndefined: isNullOrUndefined$1,\n object: isObject$1,\n number: isNumber$1,\n string: isString$1,\n boolean: isBoolean$1,\n function: isFunction$1,\n array: isArray$1,\n nodeList: isNodeList$1,\n element: isElement$1,\n event: isEvent$1,\n empty: isEmpty$1\n };\n\n function getDecimalPlaces(e) {\n var t = \"\".concat(e).match(/(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/);\n return t ? Math.max(0, (t[1] ? t[1].length : 0) - (t[2] ? +t[2] : 0)) : 0;\n }\n\n function round(e, t) {\n if (1 > t) {\n var n = getDecimalPlaces(t);\n return parseFloat(e.toFixed(n));\n }\n\n return Math.round(e / t) * t;\n }\n\n var RangeTouch = function () {\n function e(t, n) {\n _classCallCheck(this, e), is$1.element(t) ? this.element = t : is$1.string(t) && (this.element = document.querySelector(t)), is$1.element(this.element) && is$1.empty(this.element.rangeTouch) && (this.config = _objectSpread2({}, defaults$1, {}, n), this.init());\n }\n\n return _createClass(e, [{\n key: \"init\",\n value: function () {\n e.enabled && (this.config.addCSS && (this.element.style.userSelect = \"none\", this.element.style.webKitUserSelect = \"none\", this.element.style.touchAction = \"manipulation\"), this.listeners(!0), this.element.rangeTouch = this);\n }\n }, {\n key: \"destroy\",\n value: function () {\n e.enabled && (this.config.addCSS && (this.element.style.userSelect = \"\", this.element.style.webKitUserSelect = \"\", this.element.style.touchAction = \"\"), this.listeners(!1), this.element.rangeTouch = null);\n }\n }, {\n key: \"listeners\",\n value: function (e) {\n var t = this,\n n = e ? \"addEventListener\" : \"removeEventListener\";\n [\"touchstart\", \"touchmove\", \"touchend\"].forEach(function (e) {\n t.element[n](e, function (e) {\n return t.set(e);\n }, !1);\n });\n }\n }, {\n key: \"get\",\n value: function (t) {\n if (!e.enabled || !is$1.event(t)) return null;\n var n,\n r = t.target,\n i = t.changedTouches[0],\n o = parseFloat(r.getAttribute(\"min\")) || 0,\n s = parseFloat(r.getAttribute(\"max\")) || 100,\n u = parseFloat(r.getAttribute(\"step\")) || 1,\n c = r.getBoundingClientRect(),\n a = 100 / c.width * (this.config.thumbWidth / 2) / 100;\n return 0 > (n = 100 / c.width * (i.clientX - c.left)) ? n = 0 : 100 < n && (n = 100), 50 > n ? n -= (100 - 2 * n) * a : 50 < n && (n += 2 * (n - 50) * a), o + round(n / 100 * (s - o), u);\n }\n }, {\n key: \"set\",\n value: function (t) {\n e.enabled && is$1.event(t) && !t.target.disabled && (t.preventDefault(), t.target.value = this.get(t), trigger(t.target, \"touchend\" === t.type ? \"change\" : \"input\"));\n }\n }], [{\n key: \"setup\",\n value: function (t) {\n var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {},\n r = null;\n if (is$1.empty(t) || is$1.string(t) ? r = Array.from(document.querySelectorAll(is$1.string(t) ? t : 'input[type=\"range\"]')) : is$1.element(t) ? r = [t] : is$1.nodeList(t) ? r = Array.from(t) : is$1.array(t) && (r = t.filter(is$1.element)), is$1.empty(r)) return null;\n\n var i = _objectSpread2({}, defaults$1, {}, n);\n\n if (is$1.string(t) && i.watch) {\n var o = new MutationObserver(function (n) {\n Array.from(n).forEach(function (n) {\n Array.from(n.addedNodes).forEach(function (n) {\n is$1.element(n) && matches$1(n, t) && new e(n, i);\n });\n });\n });\n o.observe(document.body, {\n childList: !0,\n subtree: !0\n });\n }\n\n return r.map(function (t) {\n return new e(t, n);\n });\n }\n }, {\n key: \"enabled\",\n get: function () {\n return \"ontouchstart\" in document.documentElement;\n }\n }]), e;\n }();\n\n // ==========================================================================\n // Type checking utils\n // ==========================================================================\n const getConstructor = input => input !== null && typeof input !== 'undefined' ? input.constructor : null;\n\n const instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor);\n\n const isNullOrUndefined = input => input === null || typeof input === 'undefined';\n\n const isObject = input => getConstructor(input) === Object;\n\n const isNumber = input => getConstructor(input) === Number && !Number.isNaN(input);\n\n const isString = input => getConstructor(input) === String;\n\n const isBoolean = input => getConstructor(input) === Boolean;\n\n const isFunction = input => getConstructor(input) === Function;\n\n const isArray = input => Array.isArray(input);\n\n const isWeakMap = input => instanceOf(input, WeakMap);\n\n const isNodeList = input => instanceOf(input, NodeList);\n\n const isTextNode = input => getConstructor(input) === Text;\n\n const isEvent = input => instanceOf(input, Event);\n\n const isKeyboardEvent = input => instanceOf(input, KeyboardEvent);\n\n const isCue = input => instanceOf(input, window.TextTrackCue) || instanceOf(input, window.VTTCue);\n\n const isTrack = input => instanceOf(input, TextTrack) || !isNullOrUndefined(input) && isString(input.kind);\n\n const isPromise = input => instanceOf(input, Promise) && isFunction(input.then);\n\n const isElement = input => input !== null && typeof input === 'object' && input.nodeType === 1 && typeof input.style === 'object' && typeof input.ownerDocument === 'object';\n\n const isEmpty = input => isNullOrUndefined(input) || (isString(input) || isArray(input) || isNodeList(input)) && !input.length || isObject(input) && !Object.keys(input).length;\n\n const isUrl = input => {\n // Accept a URL object\n if (instanceOf(input, window.URL)) {\n return true;\n } // Must be string from here\n\n\n if (!isString(input)) {\n return false;\n } // Add the protocol if required\n\n\n let string = input;\n\n if (!input.startsWith('http://') || !input.startsWith('https://')) {\n string = `http://${input}`;\n }\n\n try {\n return !isEmpty(new URL(string).hostname);\n } catch (_) {\n return false;\n }\n };\n\n var is = {\n nullOrUndefined: isNullOrUndefined,\n object: isObject,\n number: isNumber,\n string: isString,\n boolean: isBoolean,\n function: isFunction,\n array: isArray,\n weakMap: isWeakMap,\n nodeList: isNodeList,\n element: isElement,\n textNode: isTextNode,\n event: isEvent,\n keyboardEvent: isKeyboardEvent,\n cue: isCue,\n track: isTrack,\n promise: isPromise,\n url: isUrl,\n empty: isEmpty\n };\n\n // ==========================================================================\n const transitionEndEvent = (() => {\n const element = document.createElement('span');\n const events = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend'\n };\n const type = Object.keys(events).find(event => element.style[event] !== undefined);\n return is.string(type) ? events[type] : false;\n })(); // Force repaint of element\n\n function repaint(element, delay) {\n setTimeout(() => {\n try {\n // eslint-disable-next-line no-param-reassign\n element.hidden = true; // eslint-disable-next-line no-unused-expressions\n\n element.offsetHeight; // eslint-disable-next-line no-param-reassign\n\n element.hidden = false;\n } catch (_) {// Do nothing\n }\n }, delay);\n }\n\n // ==========================================================================\n // Browser sniffing\n // Unfortunately, due to mixed support, UA sniffing is required\n // ==========================================================================\n const browser = {\n isIE: Boolean(window.document.documentMode),\n isEdge: window.navigator.userAgent.includes('Edge'),\n isWebkit: 'WebkitAppearance' in document.documentElement.style && !/Edge/.test(navigator.userAgent),\n isIPhone: /(iPhone|iPod)/gi.test(navigator.platform),\n isIos: navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 || /(iPad|iPhone|iPod)/gi.test(navigator.platform)\n };\n\n // ==========================================================================\n\n function cloneDeep(object) {\n return JSON.parse(JSON.stringify(object));\n } // Get a nested value in an object\n\n function getDeep(object, path) {\n return path.split('.').reduce((obj, key) => obj && obj[key], object);\n } // Deep extend destination object with N more objects\n\n function extend(target = {}, ...sources) {\n if (!sources.length) {\n return target;\n }\n\n const source = sources.shift();\n\n if (!is.object(source)) {\n return target;\n }\n\n Object.keys(source).forEach(key => {\n if (is.object(source[key])) {\n if (!Object.keys(target).includes(key)) {\n Object.assign(target, {\n [key]: {}\n });\n }\n\n extend(target[key], source[key]);\n } else {\n Object.assign(target, {\n [key]: source[key]\n });\n }\n });\n return extend(target, ...sources);\n }\n\n // ==========================================================================\n\n function wrap(elements, wrapper) {\n // Convert `elements` to an array, if necessary.\n const targets = elements.length ? elements : [elements]; // Loops backwards to prevent having to clone the wrapper on the\n // first element (see `child` below).\n\n Array.from(targets).reverse().forEach((element, index) => {\n const child = index > 0 ? wrapper.cloneNode(true) : wrapper; // Cache the current parent and sibling.\n\n const parent = element.parentNode;\n const sibling = element.nextSibling; // Wrap the element (is automatically removed from its current\n // parent).\n\n child.appendChild(element); // If the element had a sibling, insert the wrapper before\n // the sibling to maintain the HTML structure; otherwise, just\n // append it to the parent.\n\n if (sibling) {\n parent.insertBefore(child, sibling);\n } else {\n parent.appendChild(child);\n }\n });\n } // Set attributes\n\n function setAttributes(element, attributes) {\n if (!is.element(element) || is.empty(attributes)) {\n return;\n } // Assume null and undefined attributes should be left out,\n // Setting them would otherwise convert them to \"null\" and \"undefined\"\n\n\n Object.entries(attributes).filter(([, value]) => !is.nullOrUndefined(value)).forEach(([key, value]) => element.setAttribute(key, value));\n } // Create a DocumentFragment\n\n function createElement(type, attributes, text) {\n // Create a new <element>\n const element = document.createElement(type); // Set all passed attributes\n\n if (is.object(attributes)) {\n setAttributes(element, attributes);\n } // Add text node\n\n\n if (is.string(text)) {\n element.innerText = text;\n } // Return built element\n\n\n return element;\n } // Inaert an element after another\n\n function insertAfter(element, target) {\n if (!is.element(element) || !is.element(target)) {\n return;\n }\n\n target.parentNode.insertBefore(element, target.nextSibling);\n } // Insert a DocumentFragment\n\n function insertElement(type, parent, attributes, text) {\n if (!is.element(parent)) {\n return;\n }\n\n parent.appendChild(createElement(type, attributes, text));\n } // Remove element(s)\n\n function removeElement(element) {\n if (is.nodeList(element) || is.array(element)) {\n Array.from(element).forEach(removeElement);\n return;\n }\n\n if (!is.element(element) || !is.element(element.parentNode)) {\n return;\n }\n\n element.parentNode.removeChild(element);\n } // Remove all child elements\n\n function emptyElement(element) {\n if (!is.element(element)) {\n return;\n }\n\n let {\n length\n } = element.childNodes;\n\n while (length > 0) {\n element.removeChild(element.lastChild);\n length -= 1;\n }\n } // Replace element\n\n function replaceElement(newChild, oldChild) {\n if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) {\n return null;\n }\n\n oldChild.parentNode.replaceChild(newChild, oldChild);\n return newChild;\n } // Get an attribute object from a string selector\n\n function getAttributesFromSelector(sel, existingAttributes) {\n // For example:\n // '.test' to { class: 'test' }\n // '#test' to { id: 'test' }\n // '[data-test=\"test\"]' to { 'data-test': 'test' }\n if (!is.string(sel) || is.empty(sel)) {\n return {};\n }\n\n const attributes = {};\n const existing = extend({}, existingAttributes);\n sel.split(',').forEach(s => {\n // Remove whitespace\n const selector = s.trim();\n const className = selector.replace('.', '');\n const stripped = selector.replace(/[[\\]]/g, ''); // Get the parts and value\n\n const parts = stripped.split('=');\n const [key] = parts;\n const value = parts.length > 1 ? parts[1].replace(/[\"']/g, '') : ''; // Get the first character\n\n const start = selector.charAt(0);\n\n switch (start) {\n case '.':\n // Add to existing classname\n if (is.string(existing.class)) {\n attributes.class = `${existing.class} ${className}`;\n } else {\n attributes.class = className;\n }\n\n break;\n\n case '#':\n // ID selector\n attributes.id = selector.replace('#', '');\n break;\n\n case '[':\n // Attribute selector\n attributes[key] = value;\n break;\n }\n });\n return extend(existing, attributes);\n } // Toggle hidden\n\n function toggleHidden(element, hidden) {\n if (!is.element(element)) {\n return;\n }\n\n let hide = hidden;\n\n if (!is.boolean(hide)) {\n hide = !element.hidden;\n } // eslint-disable-next-line no-param-reassign\n\n\n element.hidden = hide;\n } // Mirror Element.classList.toggle, with IE compatibility for \"force\" argument\n\n function toggleClass(element, className, force) {\n if (is.nodeList(element)) {\n return Array.from(element).map(e => toggleClass(e, className, force));\n }\n\n if (is.element(element)) {\n let method = 'toggle';\n\n if (typeof force !== 'undefined') {\n method = force ? 'add' : 'remove';\n }\n\n element.classList[method](className);\n return element.classList.contains(className);\n }\n\n return false;\n } // Has class name\n\n function hasClass(element, className) {\n return is.element(element) && element.classList.contains(className);\n } // Element matches selector\n\n function matches(element, selector) {\n const {\n prototype\n } = Element;\n\n function match() {\n return Array.from(document.querySelectorAll(selector)).includes(this);\n }\n\n const method = prototype.matches || prototype.webkitMatchesSelector || prototype.mozMatchesSelector || prototype.msMatchesSelector || match;\n return method.call(element, selector);\n } // Closest ancestor element matching selector (also tests element itself)\n\n function closest$1(element, selector) {\n const {\n prototype\n } = Element; // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill\n\n function closestElement() {\n let el = this;\n\n do {\n if (matches.matches(el, selector)) return el;\n el = el.parentElement || el.parentNode;\n } while (el !== null && el.nodeType === 1);\n\n return null;\n }\n\n const method = prototype.closest || closestElement;\n return method.call(element, selector);\n } // Find all elements\n\n function getElements(selector) {\n return this.elements.container.querySelectorAll(selector);\n } // Find a single element\n\n function getElement(selector) {\n return this.elements.container.querySelector(selector);\n } // Set focus and tab focus class\n\n function setFocus(element = null, tabFocus = false) {\n if (!is.element(element)) {\n return;\n } // Set regular focus\n\n\n element.focus({\n preventScroll: true\n }); // If we want to mimic keyboard focus via tab\n\n if (tabFocus) {\n toggleClass(element, this.config.classNames.tabFocus);\n }\n }\n\n // ==========================================================================\n\n const defaultCodecs = {\n 'audio/ogg': 'vorbis',\n 'audio/wav': '1',\n 'video/webm': 'vp8, vorbis',\n 'video/mp4': 'avc1.42E01E, mp4a.40.2',\n 'video/ogg': 'theora'\n }; // Check for feature support\n\n const support = {\n // Basic support\n audio: 'canPlayType' in document.createElement('audio'),\n video: 'canPlayType' in document.createElement('video'),\n\n // Check for support\n // Basic functionality vs full UI\n check(type, provider, playsinline) {\n const canPlayInline = browser.isIPhone && playsinline && support.playsinline;\n const api = support[type] || provider !== 'html5';\n const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline);\n return {\n api,\n ui\n };\n },\n\n // Picture-in-picture support\n // Safari & Chrome only currently\n pip: (() => {\n if (browser.isIPhone) {\n return false;\n } // Safari\n // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls\n\n\n if (is.function(createElement('video').webkitSetPresentationMode)) {\n return true;\n } // Chrome\n // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture\n\n\n if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) {\n return true;\n }\n\n return false;\n })(),\n // Airplay support\n // Safari only currently\n airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent),\n // Inline playback support\n // https://webkit.org/blog/6784/new-video-policies-for-ios/\n playsinline: 'playsInline' in document.createElement('video'),\n\n // Check for mime type support against a player instance\n // Credits: http://diveintohtml5.info/everything.html\n // Related: http://www.leanbackplayer.com/test/h5mt.html\n mime(input) {\n if (is.empty(input)) {\n return false;\n }\n\n const [mediaType] = input.split('/');\n let type = input; // Verify we're using HTML5 and there's no media type mismatch\n\n if (!this.isHTML5 || mediaType !== this.type) {\n return false;\n } // Add codec if required\n\n\n if (Object.keys(defaultCodecs).includes(type)) {\n type += `; codecs=\"${defaultCodecs[input]}\"`;\n }\n\n try {\n return Boolean(type && this.media.canPlayType(type).replace(/no/, ''));\n } catch (_) {\n return false;\n }\n },\n\n // Check for textTracks support\n textTracks: 'textTracks' in document.createElement('video'),\n // <input type=\"range\"> Sliders\n rangeInput: (() => {\n const range = document.createElement('input');\n range.type = 'range';\n return range.type === 'range';\n })(),\n // Touch\n // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event\n touch: 'ontouchstart' in document.documentElement,\n // Detect transitions support\n transitions: transitionEndEvent !== false,\n // Reduced motion iOS & MacOS setting\n // https://webkit.org/blog/7551/responsive-design-for-motion/\n reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches\n };\n\n // ==========================================================================\n // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md\n // https://www.youtube.com/watch?v=NPM6172J22g\n\n const supportsPassiveListeners = (() => {\n // Test via a getter in the options object to see if the passive property is accessed\n let supported = false;\n\n try {\n const options = Object.defineProperty({}, 'passive', {\n get() {\n supported = true;\n return null;\n }\n\n });\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n } catch (_) {// Do nothing\n }\n\n return supported;\n })(); // Toggle event listener\n\n\n function toggleListener(element, event, callback, toggle = false, passive = true, capture = false) {\n // Bail if no element, event, or callback\n if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) {\n return;\n } // Allow multiple events\n\n\n const events = event.split(' '); // Build options\n // Default to just the capture boolean for browsers with no passive listener support\n\n let options = capture; // If passive events listeners are supported\n\n if (supportsPassiveListeners) {\n options = {\n // Whether the listener can be passive (i.e. default never prevented)\n passive,\n // Whether the listener is a capturing listener or not\n capture\n };\n } // If a single node is passed, bind the event listener\n\n\n events.forEach(type => {\n if (this && this.eventListeners && toggle) {\n // Cache event listener\n this.eventListeners.push({\n element,\n type,\n callback,\n options\n });\n }\n\n element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options);\n });\n } // Bind event handler\n\n function on(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, true, passive, capture);\n } // Unbind event handler\n\n function off(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, false, passive, capture);\n } // Bind once-only event handler\n\n function once(element, events = '', callback, passive = true, capture = false) {\n const onceCallback = (...args) => {\n off(element, events, onceCallback, passive, capture);\n callback.apply(this, args);\n };\n\n toggleListener.call(this, element, events, onceCallback, true, passive, capture);\n } // Trigger event\n\n function triggerEvent(element, type = '', bubbles = false, detail = {}) {\n // Bail if no element\n if (!is.element(element) || is.empty(type)) {\n return;\n } // Create and dispatch the event\n\n\n const event = new CustomEvent(type, {\n bubbles,\n detail: { ...detail,\n plyr: this\n }\n }); // Dispatch the event\n\n element.dispatchEvent(event);\n } // Unbind all cached event listeners\n\n function unbindListeners() {\n if (this && this.eventListeners) {\n this.eventListeners.forEach(item => {\n const {\n element,\n type,\n callback,\n options\n } = item;\n element.removeEventListener(type, callback, options);\n });\n this.eventListeners = [];\n }\n } // Run method when / if player is ready\n\n function ready() {\n return new Promise(resolve => this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve)).then(() => {});\n }\n\n /**\n * Silence a Promise-like object.\n * This is useful for avoiding non-harmful, but potentially confusing \"uncaught\n * play promise\" rejection error messages.\n * @param {Object} value An object that may or may not be `Promise`-like.\n */\n\n function silencePromise(value) {\n if (is.promise(value)) {\n value.then(null, () => {});\n }\n }\n\n // ==========================================================================\n\n function dedupe(array) {\n if (!is.array(array)) {\n return array;\n }\n\n return array.filter((item, index) => array.indexOf(item) === index);\n } // Get the closest value in an array\n\n function closest(array, value) {\n if (!is.array(array) || !array.length) {\n return null;\n }\n\n return array.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev);\n }\n\n // ==========================================================================\n\n function supportsCSS(declaration) {\n if (!window || !window.CSS) {\n return false;\n }\n\n return window.CSS.supports(declaration);\n } // Standard/common aspect ratios\n\n const standardRatios = [[1, 1], [4, 3], [3, 4], [5, 4], [4, 5], [3, 2], [2, 3], [16, 10], [10, 16], [16, 9], [9, 16], [21, 9], [9, 21], [32, 9], [9, 32]].reduce((out, [x, y]) => ({ ...out,\n [x / y]: [x, y]\n }), {}); // Validate an aspect ratio\n\n function validateAspectRatio(input) {\n if (!is.array(input) && (!is.string(input) || !input.includes(':'))) {\n return false;\n }\n\n const ratio = is.array(input) ? input : input.split(':');\n return ratio.map(Number).every(is.number);\n } // Reduce an aspect ratio to it's lowest form\n\n function reduceAspectRatio(ratio) {\n if (!is.array(ratio) || !ratio.every(is.number)) {\n return null;\n }\n\n const [width, height] = ratio;\n\n const getDivider = (w, h) => h === 0 ? w : getDivider(h, w % h);\n\n const divider = getDivider(width, height);\n return [width / divider, height / divider];\n } // Calculate an aspect ratio\n\n function getAspectRatio(input) {\n const parse = ratio => validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null; // Try provided ratio\n\n\n let ratio = parse(input); // Get from config\n\n if (ratio === null) {\n ratio = parse(this.config.ratio);\n } // Get from embed\n\n\n if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) {\n ({\n ratio\n } = this.embed);\n } // Get from HTML5 video\n\n\n if (ratio === null && this.isHTML5) {\n const {\n videoWidth,\n videoHeight\n } = this.media;\n ratio = [videoWidth, videoHeight];\n }\n\n return reduceAspectRatio(ratio);\n } // Set aspect ratio for responsive container\n\n function setAspectRatio(input) {\n if (!this.isVideo) {\n return {};\n }\n\n const {\n wrapper\n } = this.elements;\n const ratio = getAspectRatio.call(this, input);\n\n if (!is.array(ratio)) {\n return {};\n }\n\n const [x, y] = reduceAspectRatio(ratio);\n const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`);\n const padding = 100 / x * y;\n\n if (useNative) {\n wrapper.style.aspectRatio = `${x}/${y}`;\n } else {\n wrapper.style.paddingBottom = `${padding}%`;\n } // For Vimeo we have an extra <div> to hide the standard controls and UI\n\n\n if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) {\n const height = 100 / this.media.offsetWidth * parseInt(window.getComputedStyle(this.media).paddingBottom, 10);\n const offset = (height - padding) / (height / 50);\n\n if (this.fullscreen.active) {\n wrapper.style.paddingBottom = null;\n } else {\n this.media.style.transform = `translateY(-${offset}%)`;\n }\n } else if (this.isHTML5) {\n wrapper.classList.add(this.config.classNames.videoFixedRatio);\n }\n\n return {\n padding,\n ratio\n };\n } // Round an aspect ratio to closest standard ratio\n\n function roundAspectRatio(x, y, tolerance = 0.05) {\n const ratio = x / y;\n const closestRatio = closest(Object.keys(standardRatios), ratio); // Check match is within tolerance\n\n if (Math.abs(closestRatio - ratio) <= tolerance) {\n return standardRatios[closestRatio];\n } // No match\n\n\n return [x, y];\n } // Get the size of the viewport\n // https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions\n\n function getViewportSize() {\n const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);\n const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);\n return [width, height];\n }\n\n // ==========================================================================\n const html5 = {\n getSources() {\n if (!this.isHTML5) {\n return [];\n }\n\n const sources = Array.from(this.media.querySelectorAll('source')); // Filter out unsupported sources (if type is specified)\n\n return sources.filter(source => {\n const type = source.getAttribute('type');\n\n if (is.empty(type)) {\n return true;\n }\n\n return support.mime.call(this, type);\n });\n },\n\n // Get quality levels\n getQualityOptions() {\n // Whether we're forcing all options (e.g. for streaming)\n if (this.config.quality.forced) {\n return this.config.quality.options;\n } // Get sizes from <source> elements\n\n\n return html5.getSources.call(this).map(source => Number(source.getAttribute('data-res'))).filter(Boolean);\n },\n\n setup() {\n if (!this.isHTML5) {\n return;\n }\n\n const player = this; // Set speed options from config\n\n player.options.speed = player.config.speed.options; // Set aspect ratio if fixed\n\n if (!is.empty(this.config.ratio)) {\n setAspectRatio.call(player);\n } // Quality\n\n\n Object.defineProperty(player.media, 'quality', {\n get() {\n // Get sources\n const sources = html5.getSources.call(player);\n const source = sources.find(s => s.getAttribute('src') === player.source); // Return size, if match is found\n\n return source && Number(source.getAttribute('data-res'));\n },\n\n set(input) {\n if (player.quality === input) {\n return;\n } // If we're using an external handler...\n\n\n if (player.config.quality.forced && is.function(player.config.quality.onChange)) {\n player.config.quality.onChange(input);\n } else {\n // Get sources\n const sources = html5.getSources.call(player); // Get first match for requested size\n\n const source = sources.find(s => Number(s.getAttribute('data-res')) === input); // No matching source found\n\n if (!source) {\n return;\n } // Get current state\n\n\n const {\n currentTime,\n paused,\n preload,\n readyState,\n playbackRate\n } = player.media; // Set new source\n\n player.media.src = source.getAttribute('src'); // Prevent loading if preload=\"none\" and the current source isn't loaded (#1044)\n\n if (preload !== 'none' || readyState) {\n // Restore time\n player.once('loadedmetadata', () => {\n player.speed = playbackRate;\n player.currentTime = currentTime; // Resume playing\n\n if (!paused) {\n silencePromise(player.play());\n }\n }); // Load new source\n\n player.media.load();\n }\n } // Trigger change event\n\n\n triggerEvent.call(player, player.media, 'qualitychange', false, {\n quality: input\n });\n }\n\n });\n },\n\n // Cancel current network requests\n // See https://github.com/sampotts/plyr/issues/174\n cancelRequests() {\n if (!this.isHTML5) {\n return;\n } // Remove child sources\n\n\n removeElement(html5.getSources.call(this)); // Set blank video src attribute\n // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error\n // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection\n\n this.media.setAttribute('src', this.config.blankVideo); // Load the new empty source\n // This will cancel existing requests\n // See https://github.com/sampotts/plyr/issues/174\n\n this.media.load(); // Debugging\n\n this.debug.log('Cancelled network requests');\n }\n\n };\n\n // ==========================================================================\n\n function generateId(prefix) {\n return `${prefix}-${Math.floor(Math.random() * 10000)}`;\n } // Format string\n\n function format(input, ...args) {\n if (is.empty(input)) {\n return input;\n }\n\n return input.toString().replace(/{(\\d+)}/g, (match, i) => args[i].toString());\n } // Get percentage\n\n function getPercentage(current, max) {\n if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) {\n return 0;\n }\n\n return (current / max * 100).toFixed(2);\n } // Replace all occurances of a string in a string\n\n const replaceAll = (input = '', find = '', replace = '') => input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\\]/\\\\])/g, '\\\\$1'), 'g'), replace.toString()); // Convert to title case\n\n const toTitleCase = (input = '') => input.toString().replace(/\\w\\S*/g, text => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()); // Convert string to pascalCase\n\n function toPascalCase(input = '') {\n let string = input.toString(); // Convert kebab case\n\n string = replaceAll(string, '-', ' '); // Convert snake case\n\n string = replaceAll(string, '_', ' '); // Convert to title case\n\n string = toTitleCase(string); // Convert to pascal case\n\n return replaceAll(string, ' ', '');\n } // Convert string to pascalCase\n\n function toCamelCase(input = '') {\n let string = input.toString(); // Convert to pascal case\n\n string = toPascalCase(string); // Convert first character to lowercase\n\n return string.charAt(0).toLowerCase() + string.slice(1);\n } // Remove HTML from a string\n\n function stripHTML(source) {\n const fragment = document.createDocumentFragment();\n const element = document.createElement('div');\n fragment.appendChild(element);\n element.innerHTML = source;\n return fragment.firstChild.innerText;\n } // Like outerHTML, but also works for DocumentFragment\n\n function getHTML(element) {\n const wrapper = document.createElement('div');\n wrapper.appendChild(element);\n return wrapper.innerHTML;\n }\n\n // ==========================================================================\n\n const resources = {\n pip: 'PIP',\n airplay: 'AirPlay',\n html5: 'HTML5',\n vimeo: 'Vimeo',\n youtube: 'YouTube'\n };\n const i18n = {\n get(key = '', config = {}) {\n if (is.empty(key) || is.empty(config)) {\n return '';\n }\n\n let string = getDeep(config.i18n, key);\n\n if (is.empty(string)) {\n if (Object.keys(resources).includes(key)) {\n return resources[key];\n }\n\n return '';\n }\n\n const replace = {\n '{seektime}': config.seekTime,\n '{title}': config.title\n };\n Object.entries(replace).forEach(([k, v]) => {\n string = replaceAll(string, k, v);\n });\n return string;\n }\n\n };\n\n class Storage {\n constructor(player) {\n _defineProperty$1(this, \"get\", key => {\n if (!Storage.supported || !this.enabled) {\n return null;\n }\n\n const store = window.localStorage.getItem(this.key);\n\n if (is.empty(store)) {\n return null;\n }\n\n const json = JSON.parse(store);\n return is.string(key) && key.length ? json[key] : json;\n });\n\n _defineProperty$1(this, \"set\", object => {\n // Bail if we don't have localStorage support or it's disabled\n if (!Storage.supported || !this.enabled) {\n return;\n } // Can only store objectst\n\n\n if (!is.object(object)) {\n return;\n } // Get current storage\n\n\n let storage = this.get(); // Default to empty object\n\n if (is.empty(storage)) {\n storage = {};\n } // Update the working copy of the values\n\n\n extend(storage, object); // Update storage\n\n try {\n window.localStorage.setItem(this.key, JSON.stringify(storage));\n } catch (_) {// Do nothing\n }\n });\n\n this.enabled = player.config.storage.enabled;\n this.key = player.config.storage.key;\n } // Check for actual support (see if we can use it)\n\n\n static get supported() {\n try {\n if (!('localStorage' in window)) {\n return false;\n }\n\n const test = '___test'; // Try to use it (it might be disabled, e.g. user is in private mode)\n // see: https://github.com/sampotts/plyr/issues/131\n\n window.localStorage.setItem(test, test);\n window.localStorage.removeItem(test);\n return true;\n } catch (_) {\n return false;\n }\n }\n\n }\n\n // ==========================================================================\n // Fetch wrapper\n // Using XHR to avoid issues with older browsers\n // ==========================================================================\n function fetch(url, responseType = 'text') {\n return new Promise((resolve, reject) => {\n try {\n const request = new XMLHttpRequest(); // Check for CORS support\n\n if (!('withCredentials' in request)) {\n return;\n }\n\n request.addEventListener('load', () => {\n if (responseType === 'text') {\n try {\n resolve(JSON.parse(request.responseText));\n } catch (_) {\n resolve(request.responseText);\n }\n } else {\n resolve(request.response);\n }\n });\n request.addEventListener('error', () => {\n throw new Error(request.status);\n });\n request.open('GET', url, true); // Set the required response type\n\n request.responseType = responseType;\n request.send();\n } catch (error) {\n reject(error);\n }\n });\n }\n\n // ==========================================================================\n\n function loadSprite(url, id) {\n if (!is.string(url)) {\n return;\n }\n\n const prefix = 'cache';\n const hasId = is.string(id);\n let isCached = false;\n\n const exists = () => document.getElementById(id) !== null;\n\n const update = (container, data) => {\n // eslint-disable-next-line no-param-reassign\n container.innerHTML = data; // Check again incase of race condition\n\n if (hasId && exists()) {\n return;\n } // Inject the SVG to the body\n\n\n document.body.insertAdjacentElement('afterbegin', container);\n }; // Only load once if ID set\n\n\n if (!hasId || !exists()) {\n const useStorage = Storage.supported; // Create container\n\n const container = document.createElement('div');\n container.setAttribute('hidden', '');\n\n if (hasId) {\n container.setAttribute('id', id);\n } // Check in cache\n\n\n if (useStorage) {\n const cached = window.localStorage.getItem(`${prefix}-${id}`);\n isCached = cached !== null;\n\n if (isCached) {\n const data = JSON.parse(cached);\n update(container, data.content);\n }\n } // Get the sprite\n\n\n fetch(url).then(result => {\n if (is.empty(result)) {\n return;\n }\n\n if (useStorage) {\n try {\n window.localStorage.setItem(`${prefix}-${id}`, JSON.stringify({\n content: result\n }));\n } catch (_) {// Do nothing\n }\n }\n\n update(container, result);\n }).catch(() => {});\n }\n }\n\n // ==========================================================================\n\n const getHours = value => Math.trunc(value / 60 / 60 % 60, 10);\n const getMinutes = value => Math.trunc(value / 60 % 60, 10);\n const getSeconds = value => Math.trunc(value % 60, 10); // Format time to UI friendly string\n\n function formatTime(time = 0, displayHours = false, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return formatTime(undefined, displayHours, inverted);\n } // Format time component to add leading zero\n\n\n const format = value => `0${value}`.slice(-2); // Breakdown to hours, mins, secs\n\n\n let hours = getHours(time);\n const mins = getMinutes(time);\n const secs = getSeconds(time); // Do we need to display hours?\n\n if (displayHours || hours > 0) {\n hours = `${hours}:`;\n } else {\n hours = '';\n } // Render\n\n\n return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`;\n }\n\n // ==========================================================================\n\n const controls = {\n // Get icon URL\n getIconUrl() {\n const url = new URL(this.config.iconUrl, window.location);\n const host = window.location.host ? window.location.host : window.top.location.host;\n const cors = url.host !== host || browser.isIE && !window.svg4everybody;\n return {\n url: this.config.iconUrl,\n cors\n };\n },\n\n // Find the UI controls\n findElements() {\n try {\n this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper); // Buttons\n\n this.elements.buttons = {\n play: getElements.call(this, this.config.selectors.buttons.play),\n pause: getElement.call(this, this.config.selectors.buttons.pause),\n restart: getElement.call(this, this.config.selectors.buttons.restart),\n rewind: getElement.call(this, this.config.selectors.buttons.rewind),\n fastForward: getElement.call(this, this.config.selectors.buttons.fastForward),\n mute: getElement.call(this, this.config.selectors.buttons.mute),\n pip: getElement.call(this, this.config.selectors.buttons.pip),\n airplay: getElement.call(this, this.config.selectors.buttons.airplay),\n settings: getElement.call(this, this.config.selectors.buttons.settings),\n captions: getElement.call(this, this.config.selectors.buttons.captions),\n fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen)\n }; // Progress\n\n this.elements.progress = getElement.call(this, this.config.selectors.progress); // Inputs\n\n this.elements.inputs = {\n seek: getElement.call(this, this.config.selectors.inputs.seek),\n volume: getElement.call(this, this.config.selectors.inputs.volume)\n }; // Display\n\n this.elements.display = {\n buffer: getElement.call(this, this.config.selectors.display.buffer),\n currentTime: getElement.call(this, this.config.selectors.display.currentTime),\n duration: getElement.call(this, this.config.selectors.display.duration)\n }; // Seek tooltip\n\n if (is.element(this.elements.progress)) {\n this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`);\n }\n\n return true;\n } catch (error) {\n // Log it\n this.debug.warn('It looks like there is a problem with your custom controls HTML', error); // Restore native video controls\n\n this.toggleNativeControls(true);\n return false;\n }\n },\n\n // Create <svg> icon\n createIcon(type, attributes) {\n const namespace = 'http://www.w3.org/2000/svg';\n const iconUrl = controls.getIconUrl.call(this);\n const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`; // Create <svg>\n\n const icon = document.createElementNS(namespace, 'svg');\n setAttributes(icon, extend(attributes, {\n 'aria-hidden': 'true',\n focusable: 'false'\n })); // Create the <use> to reference sprite\n\n const use = document.createElementNS(namespace, 'use');\n const path = `${iconPath}-${type}`; // Set `href` attributes\n // https://github.com/sampotts/plyr/issues/460\n // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href\n\n if ('href' in use) {\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path);\n } // Always set the older attribute even though it's \"deprecated\" (it'll be around for ages)\n\n\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path); // Add <use> to <svg>\n\n icon.appendChild(use);\n return icon;\n },\n\n // Create hidden text label\n createLabel(key, attr = {}) {\n const text = i18n.get(key, this.config);\n const attributes = { ...attr,\n class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ')\n };\n return createElement('span', attributes, text);\n },\n\n // Create a badge\n createBadge(text) {\n if (is.empty(text)) {\n return null;\n }\n\n const badge = createElement('span', {\n class: this.config.classNames.menu.value\n });\n badge.appendChild(createElement('span', {\n class: this.config.classNames.menu.badge\n }, text));\n return badge;\n },\n\n // Create a <button>\n createButton(buttonType, attr) {\n const attributes = extend({}, attr);\n let type = toCamelCase(buttonType);\n const props = {\n element: 'button',\n toggle: false,\n label: null,\n icon: null,\n labelPressed: null,\n iconPressed: null\n };\n ['element', 'icon', 'label'].forEach(key => {\n if (Object.keys(attributes).includes(key)) {\n props[key] = attributes[key];\n delete attributes[key];\n }\n }); // Default to 'button' type to prevent form submission\n\n if (props.element === 'button' && !Object.keys(attributes).includes('type')) {\n attributes.type = 'button';\n } // Set class name\n\n\n if (Object.keys(attributes).includes('class')) {\n if (!attributes.class.split(' ').some(c => c === this.config.classNames.control)) {\n extend(attributes, {\n class: `${attributes.class} ${this.config.classNames.control}`\n });\n }\n } else {\n attributes.class = this.config.classNames.control;\n } // Large play button\n\n\n switch (buttonType) {\n case 'play':\n props.toggle = true;\n props.label = 'play';\n props.labelPressed = 'pause';\n props.icon = 'play';\n props.iconPressed = 'pause';\n break;\n\n case 'mute':\n props.toggle = true;\n props.label = 'mute';\n props.labelPressed = 'unmute';\n props.icon = 'volume';\n props.iconPressed = 'muted';\n break;\n\n case 'captions':\n props.toggle = true;\n props.label = 'enableCaptions';\n props.labelPressed = 'disableCaptions';\n props.icon = 'captions-off';\n props.iconPressed = 'captions-on';\n break;\n\n case 'fullscreen':\n props.toggle = true;\n props.label = 'enterFullscreen';\n props.labelPressed = 'exitFullscreen';\n props.icon = 'enter-fullscreen';\n props.iconPressed = 'exit-fullscreen';\n break;\n\n case 'play-large':\n attributes.class += ` ${this.config.classNames.control}--overlaid`;\n type = 'play';\n props.label = 'play';\n props.icon = 'play';\n break;\n\n default:\n if (is.empty(props.label)) {\n props.label = type;\n }\n\n if (is.empty(props.icon)) {\n props.icon = buttonType;\n }\n\n }\n\n const button = createElement(props.element); // Setup toggle icon and labels\n\n if (props.toggle) {\n // Icon\n button.appendChild(controls.createIcon.call(this, props.iconPressed, {\n class: 'icon--pressed'\n }));\n button.appendChild(controls.createIcon.call(this, props.icon, {\n class: 'icon--not-pressed'\n })); // Label/Tooltip\n\n button.appendChild(controls.createLabel.call(this, props.labelPressed, {\n class: 'label--pressed'\n }));\n button.appendChild(controls.createLabel.call(this, props.label, {\n class: 'label--not-pressed'\n }));\n } else {\n button.appendChild(controls.createIcon.call(this, props.icon));\n button.appendChild(controls.createLabel.call(this, props.label));\n } // Merge and set attributes\n\n\n extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes));\n setAttributes(button, attributes); // We have multiple play buttons\n\n if (type === 'play') {\n if (!is.array(this.elements.buttons[type])) {\n this.elements.buttons[type] = [];\n }\n\n this.elements.buttons[type].push(button);\n } else {\n this.elements.buttons[type] = button;\n }\n\n return button;\n },\n\n // Create an <input type='range'>\n createRange(type, attributes) {\n // Seek input\n const input = createElement('input', extend(getAttributesFromSelector(this.config.selectors.inputs[type]), {\n type: 'range',\n min: 0,\n max: 100,\n step: 0.01,\n value: 0,\n autocomplete: 'off',\n // A11y fixes for https://github.com/sampotts/plyr/issues/905\n role: 'slider',\n 'aria-label': i18n.get(type, this.config),\n 'aria-valuemin': 0,\n 'aria-valuemax': 100,\n 'aria-valuenow': 0\n }, attributes));\n this.elements.inputs[type] = input; // Set the fill for webkit now\n\n controls.updateRangeFill.call(this, input); // Improve support on touch devices\n\n RangeTouch.setup(input);\n return input;\n },\n\n // Create a <progress>\n createProgress(type, attributes) {\n const progress = createElement('progress', extend(getAttributesFromSelector(this.config.selectors.display[type]), {\n min: 0,\n max: 100,\n value: 0,\n role: 'progressbar',\n 'aria-hidden': true\n }, attributes)); // Create the label inside\n\n if (type !== 'volume') {\n progress.appendChild(createElement('span', null, '0'));\n const suffixKey = {\n played: 'played',\n buffer: 'buffered'\n }[type];\n const suffix = suffixKey ? i18n.get(suffixKey, this.config) : '';\n progress.innerText = `% ${suffix.toLowerCase()}`;\n }\n\n this.elements.display[type] = progress;\n return progress;\n },\n\n // Create time display\n createTime(type, attrs) {\n const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs);\n const container = createElement('div', extend(attributes, {\n class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(),\n 'aria-label': i18n.get(type, this.config)\n }), '00:00'); // Reference for updates\n\n this.elements.display[type] = container;\n return container;\n },\n\n // Bind keyboard shortcuts for a menu item\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n bindMenuItemShortcuts(menuItem, type) {\n // Navigate through menus via arrow keys and space\n on.call(this, menuItem, 'keydown keyup', event => {\n // We only care about space and ⬆️ ⬇️️ ➡️\n if (![32, 38, 39, 40].includes(event.which)) {\n return;\n } // Prevent play / seek\n\n\n event.preventDefault();\n event.stopPropagation(); // We're just here to prevent the keydown bubbling\n\n if (event.type === 'keydown') {\n return;\n }\n\n const isRadioButton = matches(menuItem, '[role=\"menuitemradio\"]'); // Show the respective menu\n\n if (!isRadioButton && [32, 39].includes(event.which)) {\n controls.showMenuPanel.call(this, type, true);\n } else {\n let target;\n\n if (event.which !== 32) {\n if (event.which === 40 || isRadioButton && event.which === 39) {\n target = menuItem.nextElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.firstElementChild;\n }\n } else {\n target = menuItem.previousElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.lastElementChild;\n }\n }\n\n setFocus.call(this, target, true);\n }\n }\n }, false); // Enter will fire a `click` event but we still need to manage focus\n // So we bind to keyup which fires after and set focus here\n\n on.call(this, menuItem, 'keyup', event => {\n if (event.which !== 13) {\n return;\n }\n\n controls.focusFirstMenuItem.call(this, null, true);\n });\n },\n\n // Create a settings menu item\n createMenuItem({\n value,\n list,\n type,\n title,\n badge = null,\n checked = false\n }) {\n const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]);\n const menuItem = createElement('button', extend(attributes, {\n type: 'button',\n role: 'menuitemradio',\n class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(),\n 'aria-checked': checked,\n value\n }));\n const flex = createElement('span'); // We have to set as HTML incase of special characters\n\n flex.innerHTML = title;\n\n if (is.element(badge)) {\n flex.appendChild(badge);\n }\n\n menuItem.appendChild(flex); // Replicate radio button behaviour\n\n Object.defineProperty(menuItem, 'checked', {\n enumerable: true,\n\n get() {\n return menuItem.getAttribute('aria-checked') === 'true';\n },\n\n set(check) {\n // Ensure exclusivity\n if (check) {\n Array.from(menuItem.parentNode.children).filter(node => matches(node, '[role=\"menuitemradio\"]')).forEach(node => node.setAttribute('aria-checked', 'false'));\n }\n\n menuItem.setAttribute('aria-checked', check ? 'true' : 'false');\n }\n\n });\n this.listeners.bind(menuItem, 'click keyup', event => {\n if (is.keyboardEvent(event) && event.which !== 32) {\n return;\n }\n\n event.preventDefault();\n event.stopPropagation();\n menuItem.checked = true;\n\n switch (type) {\n case 'language':\n this.currentTrack = Number(value);\n break;\n\n case 'quality':\n this.quality = value;\n break;\n\n case 'speed':\n this.speed = parseFloat(value);\n break;\n }\n\n controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event));\n }, type, false);\n controls.bindMenuItemShortcuts.call(this, menuItem, type);\n list.appendChild(menuItem);\n },\n\n // Format a time for display\n formatTime(time = 0, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return time;\n } // Always display hours if duration is over an hour\n\n\n const forceHours = getHours(this.duration) > 0;\n return formatTime(time, forceHours, inverted);\n },\n\n // Update the displayed time\n updateTimeDisplay(target = null, time = 0, inverted = false) {\n // Bail if there's no element to display or the value isn't a number\n if (!is.element(target) || !is.number(time)) {\n return;\n } // eslint-disable-next-line no-param-reassign\n\n\n target.innerText = controls.formatTime(time, inverted);\n },\n\n // Update volume UI and storage\n updateVolume() {\n if (!this.supported.ui) {\n return;\n } // Update range\n\n\n if (is.element(this.elements.inputs.volume)) {\n controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);\n } // Update mute state\n\n\n if (is.element(this.elements.buttons.mute)) {\n this.elements.buttons.mute.pressed = this.muted || this.volume === 0;\n }\n },\n\n // Update seek value and lower fill\n setRange(target, value = 0) {\n if (!is.element(target)) {\n return;\n } // eslint-disable-next-line\n\n\n target.value = value; // Webkit range fill\n\n controls.updateRangeFill.call(this, target);\n },\n\n // Update <progress> elements\n updateProgress(event) {\n if (!this.supported.ui || !is.event(event)) {\n return;\n }\n\n let value = 0;\n\n const setProgress = (target, input) => {\n const val = is.number(input) ? input : 0;\n const progress = is.element(target) ? target : this.elements.display.buffer; // Update value and label\n\n if (is.element(progress)) {\n progress.value = val; // Update text label inside\n\n const label = progress.getElementsByTagName('span')[0];\n\n if (is.element(label)) {\n label.childNodes[0].nodeValue = val;\n }\n }\n };\n\n if (event) {\n switch (event.type) {\n // Video playing\n case 'timeupdate':\n case 'seeking':\n case 'seeked':\n value = getPercentage(this.currentTime, this.duration); // Set seek range value only if it's a 'natural' time event\n\n if (event.type === 'timeupdate') {\n controls.setRange.call(this, this.elements.inputs.seek, value);\n }\n\n break;\n // Check buffer status\n\n case 'playing':\n case 'progress':\n setProgress(this.elements.display.buffer, this.buffered * 100);\n break;\n }\n }\n },\n\n // Webkit polyfill for lower fill range\n updateRangeFill(target) {\n // Get range from event if event passed\n const range = is.event(target) ? target.target : target; // Needs to be a valid <input type='range'>\n\n if (!is.element(range) || range.getAttribute('type') !== 'range') {\n return;\n } // Set aria values for https://github.com/sampotts/plyr/issues/905\n\n\n if (matches(range, this.config.selectors.inputs.seek)) {\n range.setAttribute('aria-valuenow', this.currentTime);\n const currentTime = controls.formatTime(this.currentTime);\n const duration = controls.formatTime(this.duration);\n const format = i18n.get('seekLabel', this.config);\n range.setAttribute('aria-valuetext', format.replace('{currentTime}', currentTime).replace('{duration}', duration));\n } else if (matches(range, this.config.selectors.inputs.volume)) {\n const percent = range.value * 100;\n range.setAttribute('aria-valuenow', percent);\n range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`);\n } else {\n range.setAttribute('aria-valuenow', range.value);\n } // WebKit only\n\n\n if (!browser.isWebkit) {\n return;\n } // Set CSS custom property\n\n\n range.style.setProperty('--value', `${range.value / range.max * 100}%`);\n },\n\n // Update hover tooltip for seeking\n updateSeekTooltip(event) {\n // Bail if setting not true\n if (!this.config.tooltips.seek || !is.element(this.elements.inputs.seek) || !is.element(this.elements.display.seekTooltip) || this.duration === 0) {\n return;\n }\n\n const visible = `${this.config.classNames.tooltip}--visible`;\n\n const toggle = show => toggleClass(this.elements.display.seekTooltip, visible, show); // Hide on touch\n\n\n if (this.touch) {\n toggle(false);\n return;\n } // Determine percentage, if already visible\n\n\n let percent = 0;\n const clientRect = this.elements.progress.getBoundingClientRect();\n\n if (is.event(event)) {\n percent = 100 / clientRect.width * (event.pageX - clientRect.left);\n } else if (hasClass(this.elements.display.seekTooltip, visible)) {\n percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);\n } else {\n return;\n } // Set bounds\n\n\n if (percent < 0) {\n percent = 0;\n } else if (percent > 100) {\n percent = 100;\n } // Display the time a click would seek to\n\n\n controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent); // Set position\n\n this.elements.display.seekTooltip.style.left = `${percent}%`; // Show/hide the tooltip\n // If the event is a moues in/out and percentage is inside bounds\n\n if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) {\n toggle(event.type === 'mouseenter');\n }\n },\n\n // Handle time change event\n timeUpdate(event) {\n // Only invert if only one time element is displayed and used for both duration and currentTime\n const invert = !is.element(this.elements.display.duration) && this.config.invertTime; // Duration\n\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, invert ? this.duration - this.currentTime : this.currentTime, invert); // Ignore updates while seeking\n\n if (event && event.type === 'timeupdate' && this.media.seeking) {\n return;\n } // Playing progress\n\n\n controls.updateProgress.call(this, event);\n },\n\n // Show the duration on metadataloaded or durationchange events\n durationUpdate() {\n // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false\n if (!this.supported.ui || !this.config.invertTime && this.currentTime) {\n return;\n } // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar.\n // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415\n // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062\n // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338\n\n\n if (this.duration >= 2 ** 32) {\n toggleHidden(this.elements.display.currentTime, true);\n toggleHidden(this.elements.progress, true);\n return;\n } // Update ARIA values\n\n\n if (is.element(this.elements.inputs.seek)) {\n this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration);\n } // If there's a spot to display duration\n\n\n const hasDuration = is.element(this.elements.display.duration); // If there's only one time display, display duration there\n\n if (!hasDuration && this.config.displayDuration && this.paused) {\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);\n } // If there's a duration element, update content\n\n\n if (hasDuration) {\n controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);\n } // Update the tooltip (if visible)\n\n\n controls.updateSeekTooltip.call(this);\n },\n\n // Hide/show a tab\n toggleMenuButton(setting, toggle) {\n toggleHidden(this.elements.settings.buttons[setting], !toggle);\n },\n\n // Update the selected setting\n updateSetting(setting, container, input) {\n const pane = this.elements.settings.panels[setting];\n let value = null;\n let list = container;\n\n if (setting === 'captions') {\n value = this.currentTrack;\n } else {\n value = !is.empty(input) ? input : this[setting]; // Get default\n\n if (is.empty(value)) {\n value = this.config[setting].default;\n } // Unsupported value\n\n\n if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) {\n this.debug.warn(`Unsupported value of '${value}' for ${setting}`);\n return;\n } // Disabled value\n\n\n if (!this.config[setting].options.includes(value)) {\n this.debug.warn(`Disabled value of '${value}' for ${setting}`);\n return;\n }\n } // Get the list if we need to\n\n\n if (!is.element(list)) {\n list = pane && pane.querySelector('[role=\"menu\"]');\n } // If there's no list it means it's not been rendered...\n\n\n if (!is.element(list)) {\n return;\n } // Update the label\n\n\n const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`);\n label.innerHTML = controls.getLabel.call(this, setting, value); // Find the radio option and check it\n\n const target = list && list.querySelector(`[value=\"${value}\"]`);\n\n if (is.element(target)) {\n target.checked = true;\n }\n },\n\n // Translate a value into a nice label\n getLabel(setting, value) {\n switch (setting) {\n case 'speed':\n return value === 1 ? i18n.get('normal', this.config) : `${value}×`;\n\n case 'quality':\n if (is.number(value)) {\n const label = i18n.get(`qualityLabel.${value}`, this.config);\n\n if (!label.length) {\n return `${value}p`;\n }\n\n return label;\n }\n\n return toTitleCase(value);\n\n case 'captions':\n return captions.getLabel.call(this);\n\n default:\n return null;\n }\n },\n\n // Set the quality menu\n setQualityMenu(options) {\n // Menu required\n if (!is.element(this.elements.settings.panels.quality)) {\n return;\n }\n\n const type = 'quality';\n const list = this.elements.settings.panels.quality.querySelector('[role=\"menu\"]'); // Set options if passed and filter based on uniqueness and config\n\n if (is.array(options)) {\n this.options.quality = dedupe(options).filter(quality => this.config.quality.options.includes(quality));\n } // Toggle the pane and tab\n\n\n const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1;\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If we're hiding, nothing more to do\n\n if (!toggle) {\n return;\n } // Get the badge HTML for HD, 4K etc\n\n\n const getBadge = quality => {\n const label = i18n.get(`qualityBadge.${quality}`, this.config);\n\n if (!label.length) {\n return null;\n }\n\n return controls.createBadge.call(this, label);\n }; // Sort options by the config and then render options\n\n\n this.options.quality.sort((a, b) => {\n const sorting = this.config.quality.options;\n return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1;\n }).forEach(quality => {\n controls.createMenuItem.call(this, {\n value: quality,\n list,\n type,\n title: controls.getLabel.call(this, 'quality', quality),\n badge: getBadge(quality)\n });\n });\n controls.updateSetting.call(this, type, list);\n },\n\n // Set the looping options\n\n /* setLoopMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.loop)) {\n return;\n }\n const options = ['start', 'end', 'all', 'reset'];\n const list = this.elements.settings.panels.loop.querySelector('[role=\"menu\"]');\n // Show the pane and tab\n toggleHidden(this.elements.settings.buttons.loop, false);\n toggleHidden(this.elements.settings.panels.loop, false);\n // Toggle the pane and tab\n const toggle = !is.empty(this.loop.options);\n controls.toggleMenuButton.call(this, 'loop', toggle);\n // Empty the menu\n emptyElement(list);\n options.forEach(option => {\n const item = createElement('li');\n const button = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.loop), {\n type: 'button',\n class: this.config.classNames.control,\n 'data-plyr-loop-action': option,\n }),\n i18n.get(option, this.config)\n );\n if (['start', 'end'].includes(option)) {\n const badge = controls.createBadge.call(this, '00:00');\n button.appendChild(badge);\n }\n item.appendChild(button);\n list.appendChild(item);\n });\n }, */\n // Get current selected caption language\n // TODO: rework this to user the getter in the API?\n // Set a list of available captions languages\n setCaptionsMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.captions)) {\n return;\n } // TODO: Captions or language? Currently it's mixed\n\n\n const type = 'captions';\n const list = this.elements.settings.panels.captions.querySelector('[role=\"menu\"]');\n const tracks = captions.getTracks.call(this);\n const toggle = Boolean(tracks.length); // Toggle the pane and tab\n\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If there's no captions, bail\n\n if (!toggle) {\n return;\n } // Generate options data\n\n\n const options = tracks.map((track, value) => ({\n value,\n checked: this.captions.toggled && this.currentTrack === value,\n title: captions.getLabel.call(this, track),\n badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()),\n list,\n type: 'language'\n })); // Add the \"Disabled\" option to turn off captions\n\n options.unshift({\n value: -1,\n checked: !this.captions.toggled,\n title: i18n.get('disabled', this.config),\n list,\n type: 'language'\n }); // Generate options\n\n options.forEach(controls.createMenuItem.bind(this));\n controls.updateSetting.call(this, type, list);\n },\n\n // Set a list of available captions languages\n setSpeedMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.speed)) {\n return;\n }\n\n const type = 'speed';\n const list = this.elements.settings.panels.speed.querySelector('[role=\"menu\"]'); // Filter out invalid speeds\n\n this.options.speed = this.options.speed.filter(o => o >= this.minimumSpeed && o <= this.maximumSpeed); // Toggle the pane and tab\n\n const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1;\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If we're hiding, nothing more to do\n\n if (!toggle) {\n return;\n } // Create items\n\n\n this.options.speed.forEach(speed => {\n controls.createMenuItem.call(this, {\n value: speed,\n list,\n type,\n title: controls.getLabel.call(this, 'speed', speed)\n });\n });\n controls.updateSetting.call(this, type, list);\n },\n\n // Check if we need to hide/show the settings menu\n checkMenu() {\n const {\n buttons\n } = this.elements.settings;\n const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden);\n toggleHidden(this.elements.settings.menu, !visible);\n },\n\n // Focus the first menu item in a given (or visible) menu\n focusFirstMenuItem(pane, tabFocus = false) {\n if (this.elements.settings.popup.hidden) {\n return;\n }\n\n let target = pane;\n\n if (!is.element(target)) {\n target = Object.values(this.elements.settings.panels).find(p => !p.hidden);\n }\n\n const firstItem = target.querySelector('[role^=\"menuitem\"]');\n setFocus.call(this, firstItem, tabFocus);\n },\n\n // Show/hide menu\n toggleMenu(input) {\n const {\n popup\n } = this.elements.settings;\n const button = this.elements.buttons.settings; // Menu and button are required\n\n if (!is.element(popup) || !is.element(button)) {\n return;\n } // True toggle by default\n\n\n const {\n hidden\n } = popup;\n let show = hidden;\n\n if (is.boolean(input)) {\n show = input;\n } else if (is.keyboardEvent(input) && input.which === 27) {\n show = false;\n } else if (is.event(input)) {\n // If Plyr is in a shadowDOM, the event target is set to the component, instead of the\n // Element in the shadowDOM. The path, if available, is complete.\n const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target;\n const isMenuItem = popup.contains(target); // If the click was inside the menu or if the click\n // wasn't the button or menu item and we're trying to\n // show the menu (a doc click shouldn't show the menu)\n\n if (isMenuItem || !isMenuItem && input.target !== button && show) {\n return;\n }\n } // Set button attributes\n\n\n button.setAttribute('aria-expanded', show); // Show the actual popup\n\n toggleHidden(popup, !show); // Add class hook\n\n toggleClass(this.elements.container, this.config.classNames.menu.open, show); // Focus the first item if key interaction\n\n if (show && is.keyboardEvent(input)) {\n controls.focusFirstMenuItem.call(this, null, true);\n } else if (!show && !hidden) {\n // If closing, re-focus the button\n setFocus.call(this, button, is.keyboardEvent(input));\n }\n },\n\n // Get the natural size of a menu panel\n getMenuSize(tab) {\n const clone = tab.cloneNode(true);\n clone.style.position = 'absolute';\n clone.style.opacity = 0;\n clone.removeAttribute('hidden'); // Append to parent so we get the \"real\" size\n\n tab.parentNode.appendChild(clone); // Get the sizes before we remove\n\n const width = clone.scrollWidth;\n const height = clone.scrollHeight; // Remove from the DOM\n\n removeElement(clone);\n return {\n width,\n height\n };\n },\n\n // Show a panel in the menu\n showMenuPanel(type = '', tabFocus = false) {\n const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`); // Nothing to show, bail\n\n if (!is.element(target)) {\n return;\n } // Hide all other panels\n\n\n const container = target.parentNode;\n const current = Array.from(container.children).find(node => !node.hidden); // If we can do fancy animations, we'll animate the height/width\n\n if (support.transitions && !support.reducedMotion) {\n // Set the current width as a base\n container.style.width = `${current.scrollWidth}px`;\n container.style.height = `${current.scrollHeight}px`; // Get potential sizes\n\n const size = controls.getMenuSize.call(this, target); // Restore auto height/width\n\n const restore = event => {\n // We're only bothered about height and width on the container\n if (event.target !== container || !['width', 'height'].includes(event.propertyName)) {\n return;\n } // Revert back to auto\n\n\n container.style.width = '';\n container.style.height = ''; // Only listen once\n\n off.call(this, container, transitionEndEvent, restore);\n }; // Listen for the transition finishing and restore auto height/width\n\n\n on.call(this, container, transitionEndEvent, restore); // Set dimensions to target\n\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n } // Set attributes on current tab\n\n\n toggleHidden(current, true); // Set attributes on target\n\n toggleHidden(target, false); // Focus the first item\n\n controls.focusFirstMenuItem.call(this, target, tabFocus);\n },\n\n // Set the download URL\n setDownloadUrl() {\n const button = this.elements.buttons.download; // Bail if no button\n\n if (!is.element(button)) {\n return;\n } // Set attribute\n\n\n button.setAttribute('href', this.download);\n },\n\n // Build the default HTML\n create(data) {\n const {\n bindMenuItemShortcuts,\n createButton,\n createProgress,\n createRange,\n createTime,\n setQualityMenu,\n setSpeedMenu,\n showMenuPanel\n } = controls;\n this.elements.controls = null; // Larger overlaid play button\n\n if (is.array(this.config.controls) && this.config.controls.includes('play-large')) {\n this.elements.container.appendChild(createButton.call(this, 'play-large'));\n } // Create the container\n\n\n const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper));\n this.elements.controls = container; // Default item attributes\n\n const defaultAttributes = {\n class: 'plyr__controls__item'\n }; // Loop through controls in order\n\n dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach(control => {\n // Restart button\n if (control === 'restart') {\n container.appendChild(createButton.call(this, 'restart', defaultAttributes));\n } // Rewind button\n\n\n if (control === 'rewind') {\n container.appendChild(createButton.call(this, 'rewind', defaultAttributes));\n } // Play/Pause button\n\n\n if (control === 'play') {\n container.appendChild(createButton.call(this, 'play', defaultAttributes));\n } // Fast forward button\n\n\n if (control === 'fast-forward') {\n container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes));\n } // Progress\n\n\n if (control === 'progress') {\n const progressContainer = createElement('div', {\n class: `${defaultAttributes.class} plyr__progress__container`\n });\n const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress)); // Seek range slider\n\n progress.appendChild(createRange.call(this, 'seek', {\n id: `plyr-seek-${data.id}`\n })); // Buffer progress\n\n progress.appendChild(createProgress.call(this, 'buffer')); // TODO: Add loop display indicator\n // Seek tooltip\n\n if (this.config.tooltips.seek) {\n const tooltip = createElement('span', {\n class: this.config.classNames.tooltip\n }, '00:00');\n progress.appendChild(tooltip);\n this.elements.display.seekTooltip = tooltip;\n }\n\n this.elements.progress = progress;\n progressContainer.appendChild(this.elements.progress);\n container.appendChild(progressContainer);\n } // Media current time display\n\n\n if (control === 'current-time') {\n container.appendChild(createTime.call(this, 'currentTime', defaultAttributes));\n } // Media duration display\n\n\n if (control === 'duration') {\n container.appendChild(createTime.call(this, 'duration', defaultAttributes));\n } // Volume controls\n\n\n if (control === 'mute' || control === 'volume') {\n let {\n volume\n } = this.elements; // Create the volume container if needed\n\n if (!is.element(volume) || !container.contains(volume)) {\n volume = createElement('div', extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__volume`.trim()\n }));\n this.elements.volume = volume;\n container.appendChild(volume);\n } // Toggle mute button\n\n\n if (control === 'mute') {\n volume.appendChild(createButton.call(this, 'mute'));\n } // Volume range control\n // Ignored on iOS as it's handled globally\n // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html\n\n\n if (control === 'volume' && !browser.isIos) {\n // Set the attributes\n const attributes = {\n max: 1,\n step: 0.05,\n value: this.config.volume\n }; // Create the volume range slider\n\n volume.appendChild(createRange.call(this, 'volume', extend(attributes, {\n id: `plyr-volume-${data.id}`\n })));\n }\n } // Toggle captions button\n\n\n if (control === 'captions') {\n container.appendChild(createButton.call(this, 'captions', defaultAttributes));\n } // Settings button / menu\n\n\n if (control === 'settings' && !is.empty(this.config.settings)) {\n const wrapper = createElement('div', extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__menu`.trim(),\n hidden: ''\n }));\n wrapper.appendChild(createButton.call(this, 'settings', {\n 'aria-haspopup': true,\n 'aria-controls': `plyr-settings-${data.id}`,\n 'aria-expanded': false\n }));\n const popup = createElement('div', {\n class: 'plyr__menu__container',\n id: `plyr-settings-${data.id}`,\n hidden: ''\n });\n const inner = createElement('div');\n const home = createElement('div', {\n id: `plyr-settings-${data.id}-home`\n }); // Create the menu\n\n const menu = createElement('div', {\n role: 'menu'\n });\n home.appendChild(menu);\n inner.appendChild(home);\n this.elements.settings.panels.home = home; // Build the menu items\n\n this.config.settings.forEach(type => {\n // TODO: bundle this with the createMenuItem helper and bindings\n const menuItem = createElement('button', extend(getAttributesFromSelector(this.config.selectors.buttons.settings), {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`,\n role: 'menuitem',\n 'aria-haspopup': true,\n hidden: ''\n })); // Bind menu shortcuts for keyboard users\n\n bindMenuItemShortcuts.call(this, menuItem, type); // Show menu on click\n\n on.call(this, menuItem, 'click', () => {\n showMenuPanel.call(this, type, false);\n });\n const flex = createElement('span', null, i18n.get(type, this.config));\n const value = createElement('span', {\n class: this.config.classNames.menu.value\n }); // Speed contains HTML entities\n\n value.innerHTML = data[type];\n flex.appendChild(value);\n menuItem.appendChild(flex);\n menu.appendChild(menuItem); // Build the panes\n\n const pane = createElement('div', {\n id: `plyr-settings-${data.id}-${type}`,\n hidden: ''\n }); // Back button\n\n const backButton = createElement('button', {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--back`\n }); // Visible label\n\n backButton.appendChild(createElement('span', {\n 'aria-hidden': true\n }, i18n.get(type, this.config))); // Screen reader label\n\n backButton.appendChild(createElement('span', {\n class: this.config.classNames.hidden\n }, i18n.get('menuBack', this.config))); // Go back via keyboard\n\n on.call(this, pane, 'keydown', event => {\n // We only care about <-\n if (event.which !== 37) {\n return;\n } // Prevent seek\n\n\n event.preventDefault();\n event.stopPropagation(); // Show the respective menu\n\n showMenuPanel.call(this, 'home', true);\n }, false); // Go back via button click\n\n on.call(this, backButton, 'click', () => {\n showMenuPanel.call(this, 'home', false);\n }); // Add to pane\n\n pane.appendChild(backButton); // Menu\n\n pane.appendChild(createElement('div', {\n role: 'menu'\n }));\n inner.appendChild(pane);\n this.elements.settings.buttons[type] = menuItem;\n this.elements.settings.panels[type] = pane;\n });\n popup.appendChild(inner);\n wrapper.appendChild(popup);\n container.appendChild(wrapper);\n this.elements.settings.popup = popup;\n this.elements.settings.menu = wrapper;\n } // Picture in picture button\n\n\n if (control === 'pip' && support.pip) {\n container.appendChild(createButton.call(this, 'pip', defaultAttributes));\n } // Airplay button\n\n\n if (control === 'airplay' && support.airplay) {\n container.appendChild(createButton.call(this, 'airplay', defaultAttributes));\n } // Download button\n\n\n if (control === 'download') {\n const attributes = extend({}, defaultAttributes, {\n element: 'a',\n href: this.download,\n target: '_blank'\n }); // Set download attribute for HTML5 only\n\n if (this.isHTML5) {\n attributes.download = '';\n }\n\n const {\n download\n } = this.config.urls;\n\n if (!is.url(download) && this.isEmbed) {\n extend(attributes, {\n icon: `logo-${this.provider}`,\n label: this.provider\n });\n }\n\n container.appendChild(createButton.call(this, 'download', attributes));\n } // Toggle fullscreen button\n\n\n if (control === 'fullscreen') {\n container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes));\n }\n }); // Set available quality levels\n\n if (this.isHTML5) {\n setQualityMenu.call(this, html5.getQualityOptions.call(this));\n }\n\n setSpeedMenu.call(this);\n return container;\n },\n\n // Insert controls\n inject() {\n // Sprite\n if (this.config.loadSprite) {\n const icon = controls.getIconUrl.call(this); // Only load external sprite using AJAX\n\n if (icon.cors) {\n loadSprite(icon.url, 'sprite-plyr');\n }\n } // Create a unique ID\n\n\n this.id = Math.floor(Math.random() * 10000); // Null by default\n\n let container = null;\n this.elements.controls = null; // Set template properties\n\n const props = {\n id: this.id,\n seektime: this.config.seekTime,\n title: this.config.title\n };\n let update = true; // If function, run it and use output\n\n if (is.function(this.config.controls)) {\n this.config.controls = this.config.controls.call(this, props);\n } // Convert falsy controls to empty array (primarily for empty strings)\n\n\n if (!this.config.controls) {\n this.config.controls = [];\n }\n\n if (is.element(this.config.controls) || is.string(this.config.controls)) {\n // HTMLElement or Non-empty string passed as the option\n container = this.config.controls;\n } else {\n // Create controls\n container = controls.create.call(this, {\n id: this.id,\n seektime: this.config.seekTime,\n speed: this.speed,\n quality: this.quality,\n captions: captions.getLabel.call(this) // TODO: Looping\n // loop: 'None',\n\n });\n update = false;\n } // Replace props with their value\n\n\n const replace = input => {\n let result = input;\n Object.entries(props).forEach(([key, value]) => {\n result = replaceAll(result, `{${key}}`, value);\n });\n return result;\n }; // Update markup\n\n\n if (update) {\n if (is.string(this.config.controls)) {\n container = replace(container);\n }\n } // Controls container\n\n\n let target; // Inject to custom location\n\n if (is.string(this.config.selectors.controls.container)) {\n target = document.querySelector(this.config.selectors.controls.container);\n } // Inject into the container by default\n\n\n if (!is.element(target)) {\n target = this.elements.container;\n } // Inject controls HTML (needs to be before captions, hence \"afterbegin\")\n\n\n const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML';\n target[insertMethod]('afterbegin', container); // Find the elements if need be\n\n if (!is.element(this.elements.controls)) {\n controls.findElements.call(this);\n } // Add pressed property to buttons\n\n\n if (!is.empty(this.elements.buttons)) {\n const addProperty = button => {\n const className = this.config.classNames.controlPressed;\n Object.defineProperty(button, 'pressed', {\n enumerable: true,\n\n get() {\n return hasClass(button, className);\n },\n\n set(pressed = false) {\n toggleClass(button, className, pressed);\n }\n\n });\n }; // Toggle classname when pressed property is set\n\n\n Object.values(this.elements.buttons).filter(Boolean).forEach(button => {\n if (is.array(button) || is.nodeList(button)) {\n Array.from(button).filter(Boolean).forEach(addProperty);\n } else {\n addProperty(button);\n }\n });\n } // Edge sometimes doesn't finish the paint so force a repaint\n\n\n if (browser.isEdge) {\n repaint(target);\n } // Setup tooltips\n\n\n if (this.config.tooltips.controls) {\n const {\n classNames,\n selectors\n } = this.config;\n const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`;\n const labels = getElements.call(this, selector);\n Array.from(labels).forEach(label => {\n toggleClass(label, this.config.classNames.hidden, false);\n toggleClass(label, this.config.classNames.tooltip, true);\n });\n }\n }\n\n };\n\n // ==========================================================================\n /**\n * Parse a string to a URL object\n * @param {String} input - the URL to be parsed\n * @param {Boolean} safe - failsafe parsing\n */\n\n function parseUrl(input, safe = true) {\n let url = input;\n\n if (safe) {\n const parser = document.createElement('a');\n parser.href = url;\n url = parser.href;\n }\n\n try {\n return new URL(url);\n } catch (_) {\n return null;\n }\n } // Convert object to URLSearchParams\n\n function buildUrlParams(input) {\n const params = new URLSearchParams();\n\n if (is.object(input)) {\n Object.entries(input).forEach(([key, value]) => {\n params.set(key, value);\n });\n }\n\n return params;\n }\n\n // ==========================================================================\n const captions = {\n // Setup captions\n setup() {\n // Requires UI support\n if (!this.supported.ui) {\n return;\n } // Only Vimeo and HTML5 video supported at this point\n\n\n if (!this.isVideo || this.isYouTube || this.isHTML5 && !support.textTracks) {\n // Clear menu and hide\n if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) {\n controls.setCaptionsMenu.call(this);\n }\n\n return;\n } // Inject the container\n\n\n if (!is.element(this.elements.captions)) {\n this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions));\n insertAfter(this.elements.captions, this.elements.wrapper);\n } // Fix IE captions if CORS is used\n // Fetch captions and inject as blobs instead (data URIs not supported!)\n\n\n if (browser.isIE && window.URL) {\n const elements = this.media.querySelectorAll('track');\n Array.from(elements).forEach(track => {\n const src = track.getAttribute('src');\n const url = parseUrl(src);\n\n if (url !== null && url.hostname !== window.location.href.hostname && ['http:', 'https:'].includes(url.protocol)) {\n fetch(src, 'blob').then(blob => {\n track.setAttribute('src', window.URL.createObjectURL(blob));\n }).catch(() => {\n removeElement(track);\n });\n }\n });\n } // Get and set initial data\n // The \"preferred\" options are not realized unless / until the wanted language has a match\n // * languages: Array of user's browser languages.\n // * language: The language preferred by user settings or config\n // * active: The state preferred by user settings or config\n // * toggled: The real captions state\n\n\n const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en'];\n const languages = dedupe(browserLanguages.map(language => language.split('-')[0]));\n let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase(); // Use first browser language when language is 'auto'\n\n if (language === 'auto') {\n [language] = languages;\n }\n\n let active = this.storage.get('captions');\n\n if (!is.boolean(active)) {\n ({\n active\n } = this.config.captions);\n }\n\n Object.assign(this.captions, {\n toggled: false,\n active,\n language,\n languages\n }); // Watch changes to textTracks and update captions menu\n\n if (this.isHTML5) {\n const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack';\n on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this));\n } // Update available languages in list next tick (the event must not be triggered before the listeners)\n\n\n setTimeout(captions.update.bind(this), 0);\n },\n\n // Update available language options in settings based on tracks\n update() {\n const tracks = captions.getTracks.call(this, true); // Get the wanted language\n\n const {\n active,\n language,\n meta,\n currentTrackNode\n } = this.captions;\n const languageExists = Boolean(tracks.find(track => track.language === language)); // Handle tracks (add event listener and \"pseudo\"-default)\n\n if (this.isHTML5 && this.isVideo) {\n tracks.filter(track => !meta.get(track)).forEach(track => {\n this.debug.log('Track added', track); // Attempt to store if the original dom element was \"default\"\n\n meta.set(track, {\n default: track.mode === 'showing'\n }); // Turn off native caption rendering to avoid double captions\n // Note: mode='hidden' forces a track to download. To ensure every track\n // isn't downloaded at once, only 'showing' tracks should be reassigned\n // eslint-disable-next-line no-param-reassign\n\n if (track.mode === 'showing') {\n // eslint-disable-next-line no-param-reassign\n track.mode = 'hidden';\n } // Add event listener for cue changes\n\n\n on.call(this, track, 'cuechange', () => captions.updateCues.call(this));\n });\n } // Update language first time it matches, or if the previous matching track was removed\n\n\n if (languageExists && this.language !== language || !tracks.includes(currentTrackNode)) {\n captions.setLanguage.call(this, language);\n captions.toggle.call(this, active && languageExists);\n } // Enable or disable captions based on track length\n\n\n if (this.elements) {\n toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks));\n } // Update available languages in list\n\n\n if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) {\n controls.setCaptionsMenu.call(this);\n }\n },\n\n // Toggle captions display\n // Used internally for the toggleCaptions method, with the passive option forced to false\n toggle(input, passive = true) {\n // If there's no full support\n if (!this.supported.ui) {\n return;\n }\n\n const {\n toggled\n } = this.captions; // Current state\n\n const activeClass = this.config.classNames.captions.active; // Get the next state\n // If the method is called without parameter, toggle based on current value\n\n const active = is.nullOrUndefined(input) ? !toggled : input; // Update state and trigger event\n\n if (active !== toggled) {\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.active = active;\n this.storage.set({\n captions: active\n });\n } // Force language if the call isn't passive and there is no matching language to toggle to\n\n\n if (!this.language && active && !passive) {\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true); // Override user preferences to avoid switching languages if a matching track is added\n\n this.captions.language = track.language; // Set caption, but don't store in localStorage as user preference\n\n captions.set.call(this, tracks.indexOf(track));\n return;\n } // Toggle button if it's enabled\n\n\n if (this.elements.buttons.captions) {\n this.elements.buttons.captions.pressed = active;\n } // Add class hook\n\n\n toggleClass(this.elements.container, activeClass, active);\n this.captions.toggled = active; // Update settings menu\n\n controls.updateSetting.call(this, 'captions'); // Trigger event (not used internally)\n\n triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled');\n } // Wait for the call stack to clear before setting mode='hidden'\n // on the active track - forcing the browser to download it\n\n\n setTimeout(() => {\n if (active && this.captions.toggled) {\n this.captions.currentTrackNode.mode = 'hidden';\n }\n });\n },\n\n // Set captions by track index\n // Used internally for the currentTrack setter with the passive option forced to false\n set(index, passive = true) {\n const tracks = captions.getTracks.call(this); // Disable captions if setting to -1\n\n if (index === -1) {\n captions.toggle.call(this, false, passive);\n return;\n }\n\n if (!is.number(index)) {\n this.debug.warn('Invalid caption argument', index);\n return;\n }\n\n if (!(index in tracks)) {\n this.debug.warn('Track not found', index);\n return;\n }\n\n if (this.captions.currentTrack !== index) {\n this.captions.currentTrack = index;\n const track = tracks[index];\n const {\n language\n } = track || {}; // Store reference to node for invalidation on remove\n\n this.captions.currentTrackNode = track; // Update settings menu\n\n controls.updateSetting.call(this, 'captions'); // When passive, don't override user preferences\n\n if (!passive) {\n this.captions.language = language;\n this.storage.set({\n language\n });\n } // Handle Vimeo captions\n\n\n if (this.isVimeo) {\n this.embed.enableTextTrack(language);\n } // Trigger event\n\n\n triggerEvent.call(this, this.media, 'languagechange');\n } // Show captions\n\n\n captions.toggle.call(this, true, passive);\n\n if (this.isHTML5 && this.isVideo) {\n // If we change the active track while a cue is already displayed we need to update it\n captions.updateCues.call(this);\n }\n },\n\n // Set captions by language\n // Used internally for the language setter with the passive option forced to false\n setLanguage(input, passive = true) {\n if (!is.string(input)) {\n this.debug.warn('Invalid language argument', input);\n return;\n } // Normalize\n\n\n const language = input.toLowerCase();\n this.captions.language = language; // Set currentTrack\n\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [language]);\n captions.set.call(this, tracks.indexOf(track), passive);\n },\n\n // Get current valid caption tracks\n // If update is false it will also ignore tracks without metadata\n // This is used to \"freeze\" the language options when captions.update is false\n getTracks(update = false) {\n // Handle media or textTracks missing or null\n const tracks = Array.from((this.media || {}).textTracks || []); // For HTML5, use cache instead of current tracks when it exists (if captions.update is false)\n // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata)\n\n return tracks.filter(track => !this.isHTML5 || update || this.captions.meta.has(track)).filter(track => ['captions', 'subtitles'].includes(track.kind));\n },\n\n // Match tracks based on languages and get the first\n findTrack(languages, force = false) {\n const tracks = captions.getTracks.call(this);\n\n const sortIsDefault = track => Number((this.captions.meta.get(track) || {}).default);\n\n const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a));\n let track;\n languages.every(language => {\n track = sorted.find(t => t.language === language);\n return !track; // Break iteration if there is a match\n }); // If no match is found but is required, get first\n\n return track || (force ? sorted[0] : undefined);\n },\n\n // Get the current track\n getCurrentTrack() {\n return captions.getTracks.call(this)[this.currentTrack];\n },\n\n // Get UI label for track\n getLabel(track) {\n let currentTrack = track;\n\n if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) {\n currentTrack = captions.getCurrentTrack.call(this);\n }\n\n if (is.track(currentTrack)) {\n if (!is.empty(currentTrack.label)) {\n return currentTrack.label;\n }\n\n if (!is.empty(currentTrack.language)) {\n return track.language.toUpperCase();\n }\n\n return i18n.get('enabled', this.config);\n }\n\n return i18n.get('disabled', this.config);\n },\n\n // Update captions using current track's active cues\n // Also optional array argument in case there isn't any track (ex: vimeo)\n updateCues(input) {\n // Requires UI\n if (!this.supported.ui) {\n return;\n }\n\n if (!is.element(this.elements.captions)) {\n this.debug.warn('No captions element to render to');\n return;\n } // Only accept array or empty input\n\n\n if (!is.nullOrUndefined(input) && !Array.isArray(input)) {\n this.debug.warn('updateCues: Invalid input', input);\n return;\n }\n\n let cues = input; // Get cues from track\n\n if (!cues) {\n const track = captions.getCurrentTrack.call(this);\n cues = Array.from((track || {}).activeCues || []).map(cue => cue.getCueAsHTML()).map(getHTML);\n } // Set new caption text\n\n\n const content = cues.map(cueText => cueText.trim()).join('\\n');\n const changed = content !== this.elements.captions.innerHTML;\n\n if (changed) {\n // Empty the container and create a new child element\n emptyElement(this.elements.captions);\n const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption));\n caption.innerHTML = content;\n this.elements.captions.appendChild(caption); // Trigger event\n\n triggerEvent.call(this, this.media, 'cuechange');\n }\n }\n\n };\n\n // ==========================================================================\n // Plyr default config\n // ==========================================================================\n const defaults = {\n // Disable\n enabled: true,\n // Custom media title\n title: '',\n // Logging to console\n debug: false,\n // Auto play (if supported)\n autoplay: false,\n // Only allow one media playing at once (vimeo only)\n autopause: true,\n // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present)\n // TODO: Remove iosNative fullscreen option in favour of this (logic needs work)\n playsinline: true,\n // Default time to skip when rewind/fast forward\n seekTime: 10,\n // Default volume\n volume: 1,\n muted: false,\n // Pass a custom duration\n duration: null,\n // Display the media duration on load in the current time position\n // If you have opted to display both duration and currentTime, this is ignored\n displayDuration: true,\n // Invert the current time to be a countdown\n invertTime: true,\n // Clicking the currentTime inverts it's value to show time left rather than elapsed\n toggleInvert: true,\n // Force an aspect ratio\n // The format must be `'w:h'` (e.g. `'16:9'`)\n ratio: null,\n // Click video container to play/pause\n clickToPlay: true,\n // Auto hide the controls\n hideControls: true,\n // Reset to start when playback ended\n resetOnEnd: false,\n // Disable the standard context menu\n disableContextMenu: true,\n // Sprite (for icons)\n loadSprite: true,\n iconPrefix: 'plyr',\n iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg',\n // Blank video (used to prevent errors on source change)\n blankVideo: 'https://cdn.plyr.io/static/blank.mp4',\n // Quality default\n quality: {\n default: 576,\n // The options to display in the UI, if available for the source media\n options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240],\n forced: false,\n onChange: null\n },\n // Set loops\n loop: {\n active: false // start: null,\n // end: null,\n\n },\n // Speed default and options to display\n speed: {\n selected: 1,\n // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x)\n options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4]\n },\n // Keyboard shortcut settings\n keyboard: {\n focused: true,\n global: false\n },\n // Display tooltips\n tooltips: {\n controls: false,\n seek: true\n },\n // Captions settings\n captions: {\n active: false,\n language: 'auto',\n // Listen to new tracks added after Plyr is initialized.\n // This is needed for streaming captions, but may result in unselectable options\n update: false\n },\n // Fullscreen settings\n fullscreen: {\n enabled: true,\n // Allow fullscreen?\n fallback: true,\n // Fallback using full viewport/window\n iosNative: false // Use the native fullscreen in iOS (disables custom controls)\n // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode\n // Non-ancestors of the player element will be ignored\n // container: null, // defaults to the player element\n\n },\n // Local storage\n storage: {\n enabled: true,\n key: 'plyr'\n },\n // Default controls\n controls: ['play-large', // 'restart',\n // 'rewind',\n 'play', // 'fast-forward',\n 'progress', 'current-time', // 'duration',\n 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', // 'download',\n 'fullscreen'],\n settings: ['captions', 'quality', 'speed'],\n // Localisation\n i18n: {\n restart: 'Restart',\n rewind: 'Rewind {seektime}s',\n play: 'Play',\n pause: 'Pause',\n fastForward: 'Forward {seektime}s',\n seek: 'Seek',\n seekLabel: '{currentTime} of {duration}',\n played: 'Played',\n buffered: 'Buffered',\n currentTime: 'Current time',\n duration: 'Duration',\n volume: 'Volume',\n mute: 'Mute',\n unmute: 'Unmute',\n enableCaptions: 'Enable captions',\n disableCaptions: 'Disable captions',\n download: 'Download',\n enterFullscreen: 'Enter fullscreen',\n exitFullscreen: 'Exit fullscreen',\n frameTitle: 'Player for {title}',\n captions: 'Captions',\n settings: 'Settings',\n pip: 'PIP',\n menuBack: 'Go back to previous menu',\n speed: 'Speed',\n normal: 'Normal',\n quality: 'Quality',\n loop: 'Loop',\n start: 'Start',\n end: 'End',\n all: 'All',\n reset: 'Reset',\n disabled: 'Disabled',\n enabled: 'Enabled',\n advertisement: 'Ad',\n qualityBadge: {\n 2160: '4K',\n 1440: 'HD',\n 1080: 'HD',\n 720: 'HD',\n 576: 'SD',\n 480: 'SD'\n }\n },\n // URLs\n urls: {\n download: null,\n vimeo: {\n sdk: 'https://player.vimeo.com/api/player.js',\n iframe: 'https://player.vimeo.com/video/{0}?{1}',\n api: 'https://vimeo.com/api/oembed.json?url={0}'\n },\n youtube: {\n sdk: 'https://www.youtube.com/iframe_api',\n api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}'\n },\n googleIMA: {\n sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js'\n }\n },\n // Custom control listeners\n listeners: {\n seek: null,\n play: null,\n pause: null,\n restart: null,\n rewind: null,\n fastForward: null,\n mute: null,\n volume: null,\n captions: null,\n download: null,\n fullscreen: null,\n pip: null,\n airplay: null,\n speed: null,\n quality: null,\n loop: null,\n language: null\n },\n // Events to watch and bubble\n events: [// Events to watch on HTML5 media elements and bubble\n // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events\n 'ended', 'progress', 'stalled', 'playing', 'waiting', 'canplay', 'canplaythrough', 'loadstart', 'loadeddata', 'loadedmetadata', 'timeupdate', 'volumechange', 'play', 'pause', 'error', 'seeking', 'seeked', 'emptied', 'ratechange', 'cuechange', // Custom events\n 'download', 'enterfullscreen', 'exitfullscreen', 'captionsenabled', 'captionsdisabled', 'languagechange', 'controlshidden', 'controlsshown', 'ready', // YouTube\n 'statechange', // Quality\n 'qualitychange', // Ads\n 'adsloaded', 'adscontentpause', 'adscontentresume', 'adstarted', 'adsmidpoint', 'adscomplete', 'adsallcomplete', 'adsimpression', 'adsclick'],\n // Selectors\n // Change these to match your template if using custom HTML\n selectors: {\n editable: 'input, textarea, select, [contenteditable]',\n container: '.plyr',\n controls: {\n container: null,\n wrapper: '.plyr__controls'\n },\n labels: '[data-plyr]',\n buttons: {\n play: '[data-plyr=\"play\"]',\n pause: '[data-plyr=\"pause\"]',\n restart: '[data-plyr=\"restart\"]',\n rewind: '[data-plyr=\"rewind\"]',\n fastForward: '[data-plyr=\"fast-forward\"]',\n mute: '[data-plyr=\"mute\"]',\n captions: '[data-plyr=\"captions\"]',\n download: '[data-plyr=\"download\"]',\n fullscreen: '[data-plyr=\"fullscreen\"]',\n pip: '[data-plyr=\"pip\"]',\n airplay: '[data-plyr=\"airplay\"]',\n settings: '[data-plyr=\"settings\"]',\n loop: '[data-plyr=\"loop\"]'\n },\n inputs: {\n seek: '[data-plyr=\"seek\"]',\n volume: '[data-plyr=\"volume\"]',\n speed: '[data-plyr=\"speed\"]',\n language: '[data-plyr=\"language\"]',\n quality: '[data-plyr=\"quality\"]'\n },\n display: {\n currentTime: '.plyr__time--current',\n duration: '.plyr__time--duration',\n buffer: '.plyr__progress__buffer',\n loop: '.plyr__progress__loop',\n // Used later\n volume: '.plyr__volume--display'\n },\n progress: '.plyr__progress',\n captions: '.plyr__captions',\n caption: '.plyr__caption'\n },\n // Class hooks added to the player in different states\n classNames: {\n type: 'plyr--{0}',\n provider: 'plyr--{0}',\n video: 'plyr__video-wrapper',\n embed: 'plyr__video-embed',\n videoFixedRatio: 'plyr__video-wrapper--fixed-ratio',\n embedContainer: 'plyr__video-embed__container',\n poster: 'plyr__poster',\n posterEnabled: 'plyr__poster-enabled',\n ads: 'plyr__ads',\n control: 'plyr__control',\n controlPressed: 'plyr__control--pressed',\n playing: 'plyr--playing',\n paused: 'plyr--paused',\n stopped: 'plyr--stopped',\n loading: 'plyr--loading',\n hover: 'plyr--hover',\n tooltip: 'plyr__tooltip',\n cues: 'plyr__cues',\n hidden: 'plyr__sr-only',\n hideControls: 'plyr--hide-controls',\n isIos: 'plyr--is-ios',\n isTouch: 'plyr--is-touch',\n uiSupported: 'plyr--full-ui',\n noTransition: 'plyr--no-transition',\n display: {\n time: 'plyr__time'\n },\n menu: {\n value: 'plyr__menu__value',\n badge: 'plyr__badge',\n open: 'plyr--menu-open'\n },\n captions: {\n enabled: 'plyr--captions-enabled',\n active: 'plyr--captions-active'\n },\n fullscreen: {\n enabled: 'plyr--fullscreen-enabled',\n fallback: 'plyr--fullscreen-fallback'\n },\n pip: {\n supported: 'plyr--pip-supported',\n active: 'plyr--pip-active'\n },\n airplay: {\n supported: 'plyr--airplay-supported',\n active: 'plyr--airplay-active'\n },\n tabFocus: 'plyr__tab-focus',\n previewThumbnails: {\n // Tooltip thumbs\n thumbContainer: 'plyr__preview-thumb',\n thumbContainerShown: 'plyr__preview-thumb--is-shown',\n imageContainer: 'plyr__preview-thumb__image-container',\n timeContainer: 'plyr__preview-thumb__time-container',\n // Scrubbing\n scrubbingContainer: 'plyr__preview-scrubbing',\n scrubbingContainerShown: 'plyr__preview-scrubbing--is-shown'\n }\n },\n // Embed attributes\n attributes: {\n embed: {\n provider: 'data-plyr-provider',\n id: 'data-plyr-embed-id',\n hash: 'data-plyr-embed-hash'\n }\n },\n // Advertisements plugin\n // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio\n ads: {\n enabled: false,\n publisherId: '',\n tagUrl: ''\n },\n // Preview Thumbnails plugin\n previewThumbnails: {\n enabled: false,\n src: ''\n },\n // Vimeo plugin\n vimeo: {\n byline: false,\n portrait: false,\n title: false,\n speed: true,\n transparent: false,\n // Custom settings from Plyr\n customControls: true,\n referrerPolicy: null,\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy\n // Whether the owner of the video has a Pro or Business account\n // (which allows us to properly hide controls without CSS hacks, etc)\n premium: false\n },\n // YouTube plugin\n youtube: {\n rel: 0,\n // No related vids\n showinfo: 0,\n // Hide info\n iv_load_policy: 3,\n // Hide annotations\n modestbranding: 1,\n // Hide logos as much as possible (they still show one in the corner when paused)\n // Custom settings from Plyr\n customControls: true,\n noCookie: false // Whether to use an alternative version of YouTube without cookies\n\n }\n };\n\n // ==========================================================================\n // Plyr states\n // ==========================================================================\n const pip = {\n active: 'picture-in-picture',\n inactive: 'inline'\n };\n\n // ==========================================================================\n // Plyr supported types and providers\n // ==========================================================================\n const providers = {\n html5: 'html5',\n youtube: 'youtube',\n vimeo: 'vimeo'\n };\n const types = {\n audio: 'audio',\n video: 'video'\n };\n /**\n * Get provider by URL\n * @param {String} url\n */\n\n function getProviderByUrl(url) {\n // YouTube\n if (/^(https?:\\/\\/)?(www\\.)?(youtube\\.com|youtube-nocookie\\.com|youtu\\.?be)\\/.+$/.test(url)) {\n return providers.youtube;\n } // Vimeo\n\n\n if (/^https?:\\/\\/player.vimeo.com\\/video\\/\\d{0,9}(?=\\b|\\/)/.test(url)) {\n return providers.vimeo;\n }\n\n return null;\n }\n\n // ==========================================================================\n // Console wrapper\n // ==========================================================================\n const noop = () => {};\n\n class Console {\n constructor(enabled = false) {\n this.enabled = window.console && enabled;\n\n if (this.enabled) {\n this.log('Debugging enabled');\n }\n }\n\n get log() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.log, console) : noop;\n }\n\n get warn() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop;\n }\n\n get error() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.error, console) : noop;\n }\n\n }\n\n class Fullscreen {\n constructor(player) {\n _defineProperty$1(this, \"onChange\", () => {\n if (!this.enabled) {\n return;\n } // Update toggle button\n\n\n const button = this.player.elements.buttons.fullscreen;\n\n if (is.element(button)) {\n button.pressed = this.active;\n } // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up\n\n\n const target = this.target === this.player.media ? this.target : this.player.elements.container; // Trigger an event\n\n triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true);\n });\n\n _defineProperty$1(this, \"toggleFallback\", (toggle = false) => {\n // Store or restore scroll position\n if (toggle) {\n this.scrollPosition = {\n x: window.scrollX || 0,\n y: window.scrollY || 0\n };\n } else {\n window.scrollTo(this.scrollPosition.x, this.scrollPosition.y);\n } // Toggle scroll\n\n\n document.body.style.overflow = toggle ? 'hidden' : ''; // Toggle class hook\n\n toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle); // Force full viewport on iPhone X+\n\n if (browser.isIos) {\n let viewport = document.head.querySelector('meta[name=\"viewport\"]');\n const property = 'viewport-fit=cover'; // Inject the viewport meta if required\n\n if (!viewport) {\n viewport = document.createElement('meta');\n viewport.setAttribute('name', 'viewport');\n } // Check if the property already exists\n\n\n const hasProperty = is.string(viewport.content) && viewport.content.includes(property);\n\n if (toggle) {\n this.cleanupViewport = !hasProperty;\n\n if (!hasProperty) {\n viewport.content += `,${property}`;\n }\n } else if (this.cleanupViewport) {\n viewport.content = viewport.content.split(',').filter(part => part.trim() !== property).join(',');\n }\n } // Toggle button and fire events\n\n\n this.onChange();\n });\n\n _defineProperty$1(this, \"trapFocus\", event => {\n // Bail if iOS, not active, not the tab key\n if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) {\n return;\n } // Get the current focused element\n\n\n const focused = document.activeElement;\n const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]');\n const [first] = focusable;\n const last = focusable[focusable.length - 1];\n\n if (focused === last && !event.shiftKey) {\n // Move focus to first element that can be tabbed if Shift isn't used\n first.focus();\n event.preventDefault();\n } else if (focused === first && event.shiftKey) {\n // Move focus to last element that can be tabbed if Shift is used\n last.focus();\n event.preventDefault();\n }\n });\n\n _defineProperty$1(this, \"update\", () => {\n if (this.enabled) {\n let mode;\n\n if (this.forceFallback) {\n mode = 'Fallback (forced)';\n } else if (Fullscreen.native) {\n mode = 'Native';\n } else {\n mode = 'Fallback';\n }\n\n this.player.debug.log(`${mode} fullscreen enabled`);\n } else {\n this.player.debug.log('Fullscreen not supported and fallback disabled');\n } // Add styling hook to show button\n\n\n toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled);\n });\n\n _defineProperty$1(this, \"enter\", () => {\n if (!this.enabled) {\n return;\n } // iOS native fullscreen doesn't need the request step\n\n\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n if (this.player.isVimeo) {\n this.player.embed.requestFullscreen();\n } else {\n this.target.webkitEnterFullscreen();\n }\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(true);\n } else if (!this.prefix) {\n this.target.requestFullscreen({\n navigationUI: 'hide'\n });\n } else if (!is.empty(this.prefix)) {\n this.target[`${this.prefix}Request${this.property}`]();\n }\n });\n\n _defineProperty$1(this, \"exit\", () => {\n if (!this.enabled) {\n return;\n } // iOS native fullscreen\n\n\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n this.target.webkitExitFullscreen();\n silencePromise(this.player.play());\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(false);\n } else if (!this.prefix) {\n (document.cancelFullScreen || document.exitFullscreen).call(document);\n } else if (!is.empty(this.prefix)) {\n const action = this.prefix === 'moz' ? 'Cancel' : 'Exit';\n document[`${this.prefix}${action}${this.property}`]();\n }\n });\n\n _defineProperty$1(this, \"toggle\", () => {\n if (!this.active) {\n this.enter();\n } else {\n this.exit();\n }\n });\n\n // Keep reference to parent\n this.player = player; // Get prefix\n\n this.prefix = Fullscreen.prefix;\n this.property = Fullscreen.property; // Scroll position\n\n this.scrollPosition = {\n x: 0,\n y: 0\n }; // Force the use of 'full window/browser' rather than fullscreen\n\n this.forceFallback = player.config.fullscreen.fallback === 'force'; // Get the fullscreen element\n // Checks container is an ancestor, defaults to null\n\n this.player.elements.fullscreen = player.config.fullscreen.container && closest$1(this.player.elements.container, player.config.fullscreen.container); // Register event listeners\n // Handle event (incase user presses escape etc)\n\n on.call(this.player, document, this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`, () => {\n // TODO: Filter for target??\n this.onChange();\n }); // Fullscreen toggle on double click\n\n on.call(this.player, this.player.elements.container, 'dblclick', event => {\n // Ignore double click in controls\n if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) {\n return;\n }\n\n this.player.listeners.proxy(event, this.toggle, 'fullscreen');\n }); // Tap focus when in fullscreen\n\n on.call(this, this.player.elements.container, 'keydown', event => this.trapFocus(event)); // Update the UI\n\n this.update(); // this.toggle = this.toggle.bind(this);\n } // Determine if native supported\n\n\n static get native() {\n return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled);\n } // If we're actually using native\n\n\n get usingNative() {\n return Fullscreen.native && !this.forceFallback;\n } // Get the prefix for handlers\n\n\n static get prefix() {\n // No prefix\n if (is.function(document.exitFullscreen)) {\n return '';\n } // Check for fullscreen support by vendor prefix\n\n\n let value = '';\n const prefixes = ['webkit', 'moz', 'ms'];\n prefixes.some(pre => {\n if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) {\n value = pre;\n return true;\n }\n\n return false;\n });\n return value;\n }\n\n static get property() {\n return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen';\n } // Determine if fullscreen is enabled\n\n\n get enabled() {\n return (Fullscreen.native || this.player.config.fullscreen.fallback) && this.player.config.fullscreen.enabled && this.player.supported.ui && this.player.isVideo;\n } // Get active state\n\n\n get active() {\n if (!this.enabled) {\n return false;\n } // Fallback using classname\n\n\n if (!Fullscreen.native || this.forceFallback) {\n return hasClass(this.target, this.player.config.classNames.fullscreen.fallback);\n }\n\n const element = !this.prefix ? this.target.getRootNode().fullscreenElement : this.target.getRootNode()[`${this.prefix}${this.property}Element`];\n return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target;\n } // Get target element\n\n\n get target() {\n return browser.isIos && this.player.config.fullscreen.iosNative ? this.player.media : this.player.elements.fullscreen || this.player.elements.container;\n }\n\n }\n\n // ==========================================================================\n // Load image avoiding xhr/fetch CORS issues\n // Server status can't be obtained this way unfortunately, so this uses \"naturalWidth\" to determine if the image has loaded\n // By default it checks if it is at least 1px, but you can add a second argument to change this\n // ==========================================================================\n function loadImage(src, minWidth = 1) {\n return new Promise((resolve, reject) => {\n const image = new Image();\n\n const handler = () => {\n delete image.onload;\n delete image.onerror;\n (image.naturalWidth >= minWidth ? resolve : reject)(image);\n };\n\n Object.assign(image, {\n onload: handler,\n onerror: handler,\n src\n });\n });\n }\n\n // ==========================================================================\n const ui = {\n addStyleHook() {\n toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);\n toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);\n },\n\n // Toggle native HTML5 media controls\n toggleNativeControls(toggle = false) {\n if (toggle && this.isHTML5) {\n this.media.setAttribute('controls', '');\n } else {\n this.media.removeAttribute('controls');\n }\n },\n\n // Setup the UI\n build() {\n // Re-attach media element listeners\n // TODO: Use event bubbling?\n this.listeners.media(); // Don't setup interface if no support\n\n if (!this.supported.ui) {\n this.debug.warn(`Basic support only for ${this.provider} ${this.type}`); // Restore native controls\n\n ui.toggleNativeControls.call(this, true); // Bail\n\n return;\n } // Inject custom controls if not present\n\n\n if (!is.element(this.elements.controls)) {\n // Inject custom controls\n controls.inject.call(this); // Re-attach control listeners\n\n this.listeners.controls();\n } // Remove native controls\n\n\n ui.toggleNativeControls.call(this); // Setup captions for HTML5\n\n if (this.isHTML5) {\n captions.setup.call(this);\n } // Reset volume\n\n\n this.volume = null; // Reset mute state\n\n this.muted = null; // Reset loop state\n\n this.loop = null; // Reset quality setting\n\n this.quality = null; // Reset speed\n\n this.speed = null; // Reset volume display\n\n controls.updateVolume.call(this); // Reset time display\n\n controls.timeUpdate.call(this); // Reset duration display\n\n controls.durationUpdate.call(this); // Update the UI\n\n ui.checkPlaying.call(this); // Check for picture-in-picture support\n\n toggleClass(this.elements.container, this.config.classNames.pip.supported, support.pip && this.isHTML5 && this.isVideo); // Check for airplay support\n\n toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5); // Add iOS class\n\n toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos); // Add touch class\n\n toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch); // Ready for API calls\n\n this.ready = true; // Ready event at end of execution stack\n\n setTimeout(() => {\n triggerEvent.call(this, this.media, 'ready');\n }, 0); // Set the title\n\n ui.setTitle.call(this); // Assure the poster image is set, if the property was added before the element was created\n\n if (this.poster) {\n ui.setPoster.call(this, this.poster, false).catch(() => {});\n } // Manually set the duration if user has overridden it.\n // The event listeners for it doesn't get called if preload is disabled (#701)\n\n\n if (this.config.duration) {\n controls.durationUpdate.call(this);\n }\n },\n\n // Setup aria attribute for play and iframe title\n setTitle() {\n // Find the current text\n let label = i18n.get('play', this.config); // If there's a media title set, use that for the label\n\n if (is.string(this.config.title) && !is.empty(this.config.title)) {\n label += `, ${this.config.title}`;\n } // If there's a play button, set label\n\n\n Array.from(this.elements.buttons.play || []).forEach(button => {\n button.setAttribute('aria-label', label);\n }); // Set iframe title\n // https://github.com/sampotts/plyr/issues/124\n\n if (this.isEmbed) {\n const iframe = getElement.call(this, 'iframe');\n\n if (!is.element(iframe)) {\n return;\n } // Default to media type\n\n\n const title = !is.empty(this.config.title) ? this.config.title : 'video';\n const format = i18n.get('frameTitle', this.config);\n iframe.setAttribute('title', format.replace('{title}', title));\n }\n },\n\n // Toggle poster\n togglePoster(enable) {\n toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);\n },\n\n // Set the poster image (async)\n // Used internally for the poster setter, with the passive option forced to false\n setPoster(poster, passive = true) {\n // Don't override if call is passive\n if (passive && this.poster) {\n return Promise.reject(new Error('Poster already set'));\n } // Set property synchronously to respect the call order\n\n\n this.media.setAttribute('data-poster', poster); // Show the poster\n\n this.elements.poster.removeAttribute('hidden'); // Wait until ui is ready\n\n return ready.call(this) // Load image\n .then(() => loadImage(poster)).catch(error => {\n // Hide poster on error unless it's been set by another call\n if (poster === this.poster) {\n ui.togglePoster.call(this, false);\n } // Rethrow\n\n\n throw error;\n }).then(() => {\n // Prevent race conditions\n if (poster !== this.poster) {\n throw new Error('setPoster cancelled by later call to setPoster');\n }\n }).then(() => {\n Object.assign(this.elements.poster.style, {\n backgroundImage: `url('${poster}')`,\n // Reset backgroundSize as well (since it can be set to \"cover\" for padded thumbnails for youtube)\n backgroundSize: ''\n });\n ui.togglePoster.call(this, true);\n return poster;\n });\n },\n\n // Check playing state\n checkPlaying(event) {\n // Class hooks\n toggleClass(this.elements.container, this.config.classNames.playing, this.playing);\n toggleClass(this.elements.container, this.config.classNames.paused, this.paused);\n toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped); // Set state\n\n Array.from(this.elements.buttons.play || []).forEach(target => {\n Object.assign(target, {\n pressed: this.playing\n });\n target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config));\n }); // Only update controls on non timeupdate events\n\n if (is.event(event) && event.type === 'timeupdate') {\n return;\n } // Toggle controls\n\n\n ui.toggleControls.call(this);\n },\n\n // Check if media is loading\n checkLoading(event) {\n this.loading = ['stalled', 'waiting'].includes(event.type); // Clear timer\n\n clearTimeout(this.timers.loading); // Timer to prevent flicker when seeking\n\n this.timers.loading = setTimeout(() => {\n // Update progress bar loading class state\n toggleClass(this.elements.container, this.config.classNames.loading, this.loading); // Update controls visibility\n\n ui.toggleControls.call(this);\n }, this.loading ? 250 : 0);\n },\n\n // Toggle controls based on state and `force` argument\n toggleControls(force) {\n const {\n controls: controlsElement\n } = this.elements;\n\n if (controlsElement && this.config.hideControls) {\n // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.)\n const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now(); // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide\n\n this.toggleControls(Boolean(force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek));\n }\n },\n\n // Migrate any custom properties from the media to the parent\n migrateStyles() {\n // Loop through values (as they are the keys when the object is spread 🤔)\n Object.values({ ...this.media.style\n }) // We're only fussed about Plyr specific properties\n .filter(key => !is.empty(key) && is.string(key) && key.startsWith('--plyr')).forEach(key => {\n // Set on the container\n this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key)); // Clean up from media element\n\n this.media.style.removeProperty(key);\n }); // Remove attribute if empty\n\n if (is.empty(this.media.style)) {\n this.media.removeAttribute('style');\n }\n }\n\n };\n\n class Listeners {\n constructor(_player) {\n _defineProperty$1(this, \"firstTouch\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n player.touch = true; // Add touch class\n\n toggleClass(elements.container, player.config.classNames.isTouch, true);\n });\n\n _defineProperty$1(this, \"setTabFocus\", event => {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n clearTimeout(this.focusTimer); // Ignore any key other than tab\n\n if (event.type === 'keydown' && event.which !== 9) {\n return;\n } // Store reference to event timeStamp\n\n\n if (event.type === 'keydown') {\n this.lastKeyDown = event.timeStamp;\n } // Remove current classes\n\n\n const removeCurrent = () => {\n const className = player.config.classNames.tabFocus;\n const current = getElements.call(player, `.${className}`);\n toggleClass(current, className, false);\n }; // Determine if a key was pressed to trigger this event\n\n\n const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20; // Ignore focus events if a key was pressed prior\n\n if (event.type === 'focus' && !wasKeyDown) {\n return;\n } // Remove all current\n\n\n removeCurrent(); // Delay the adding of classname until the focus has changed\n // This event fires before the focusin event\n\n if (event.type !== 'focusout') {\n this.focusTimer = setTimeout(() => {\n const focused = document.activeElement; // Ignore if current focus element isn't inside the player\n\n if (!elements.container.contains(focused)) {\n return;\n }\n\n toggleClass(document.activeElement, player.config.classNames.tabFocus, true);\n }, 10);\n }\n });\n\n _defineProperty$1(this, \"global\", (toggle = true) => {\n const {\n player\n } = this; // Keyboard shortcuts\n\n if (player.config.keyboard.global) {\n toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false);\n } // Click anywhere closes menu\n\n\n toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle); // Detect touch by events\n\n once.call(player, document.body, 'touchstart', this.firstTouch); // Tab focus detection\n\n toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true);\n });\n\n _defineProperty$1(this, \"container\", () => {\n const {\n player\n } = this;\n const {\n config,\n elements,\n timers\n } = player; // Keyboard shortcuts\n\n if (!config.keyboard.global && config.keyboard.focused) {\n on.call(player, elements.container, 'keydown keyup', this.handleKey, false);\n } // Toggle controls on mouse events and entering fullscreen\n\n\n on.call(player, elements.container, 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen', event => {\n const {\n controls: controlsElement\n } = elements; // Remove button states for fullscreen\n\n if (controlsElement && event.type === 'enterfullscreen') {\n controlsElement.pressed = false;\n controlsElement.hover = false;\n } // Show, then hide after a timeout unless another control event occurs\n\n\n const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type);\n let delay = 0;\n\n if (show) {\n ui.toggleControls.call(player, true); // Use longer timeout for touch devices\n\n delay = player.touch ? 3000 : 2000;\n } // Clear timer\n\n\n clearTimeout(timers.controls); // Set new timer to prevent flicker when seeking\n\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n }); // Set a gutter for Vimeo\n\n const setGutter = () => {\n if (!player.isVimeo || player.config.vimeo.premium) {\n return;\n }\n\n const target = elements.wrapper;\n const {\n active\n } = player.fullscreen;\n const [videoWidth, videoHeight] = getAspectRatio.call(player);\n const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`); // If not active, remove styles\n\n if (!active) {\n if (useNativeAspectRatio) {\n target.style.width = null;\n target.style.height = null;\n } else {\n target.style.maxWidth = null;\n target.style.margin = null;\n }\n\n return;\n } // Determine which dimension will overflow and constrain view\n\n\n const [viewportWidth, viewportHeight] = getViewportSize();\n const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight;\n\n if (useNativeAspectRatio) {\n target.style.width = overflow ? 'auto' : '100%';\n target.style.height = overflow ? '100%' : 'auto';\n } else {\n target.style.maxWidth = overflow ? `${viewportHeight / videoHeight * videoWidth}px` : null;\n target.style.margin = overflow ? '0 auto' : null;\n }\n }; // Handle resizing\n\n\n const resized = () => {\n clearTimeout(timers.resized);\n timers.resized = setTimeout(setGutter, 50);\n };\n\n on.call(player, elements.container, 'enterfullscreen exitfullscreen', event => {\n const {\n target\n } = player.fullscreen; // Ignore events not from target\n\n if (target !== elements.container) {\n return;\n } // If it's not an embed and no ratio specified\n\n\n if (!player.isEmbed && is.empty(player.config.ratio)) {\n return;\n } // Set Vimeo gutter\n\n\n setGutter(); // Watch for resizes\n\n const method = event.type === 'enterfullscreen' ? on : off;\n method.call(player, window, 'resize', resized);\n });\n });\n\n _defineProperty$1(this, \"media\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player; // Time change on media\n\n on.call(player, player.media, 'timeupdate seeking seeked', event => controls.timeUpdate.call(player, event)); // Display duration\n\n on.call(player, player.media, 'durationchange loadeddata loadedmetadata', event => controls.durationUpdate.call(player, event)); // Handle the media finishing\n\n on.call(player, player.media, 'ended', () => {\n // Show poster on end\n if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) {\n // Restart\n player.restart(); // Call pause otherwise IE11 will start playing the video again\n\n player.pause();\n }\n }); // Check for buffer progress\n\n on.call(player, player.media, 'progress playing seeking seeked', event => controls.updateProgress.call(player, event)); // Handle volume changes\n\n on.call(player, player.media, 'volumechange', event => controls.updateVolume.call(player, event)); // Handle play/pause\n\n on.call(player, player.media, 'playing play pause ended emptied timeupdate', event => ui.checkPlaying.call(player, event)); // Loading state\n\n on.call(player, player.media, 'waiting canplay seeked playing', event => ui.checkLoading.call(player, event)); // Click video\n\n if (player.supported.ui && player.config.clickToPlay && !player.isAudio) {\n // Re-fetch the wrapper\n const wrapper = getElement.call(player, `.${player.config.classNames.video}`); // Bail if there's no wrapper (this should never happen)\n\n if (!is.element(wrapper)) {\n return;\n } // On click play, pause or restart\n\n\n on.call(player, elements.container, 'click', event => {\n const targets = [elements.container, wrapper]; // Ignore if click if not container or in video wrapper\n\n if (!targets.includes(event.target) && !wrapper.contains(event.target)) {\n return;\n } // Touch devices will just show controls (if hidden)\n\n\n if (player.touch && player.config.hideControls) {\n return;\n }\n\n if (player.ended) {\n this.proxy(event, player.restart, 'restart');\n this.proxy(event, () => {\n silencePromise(player.play());\n }, 'play');\n } else {\n this.proxy(event, () => {\n silencePromise(player.togglePlay());\n }, 'play');\n }\n });\n } // Disable right click\n\n\n if (player.supported.ui && player.config.disableContextMenu) {\n on.call(player, elements.wrapper, 'contextmenu', event => {\n event.preventDefault();\n }, false);\n } // Volume change\n\n\n on.call(player, player.media, 'volumechange', () => {\n // Save to storage\n player.storage.set({\n volume: player.volume,\n muted: player.muted\n });\n }); // Speed change\n\n on.call(player, player.media, 'ratechange', () => {\n // Update UI\n controls.updateSetting.call(player, 'speed'); // Save to storage\n\n player.storage.set({\n speed: player.speed\n });\n }); // Quality change\n\n on.call(player, player.media, 'qualitychange', event => {\n // Update UI\n controls.updateSetting.call(player, 'quality', null, event.detail.quality);\n }); // Update download link when ready and if quality changes\n\n on.call(player, player.media, 'ready qualitychange', () => {\n controls.setDownloadUrl.call(player);\n }); // Proxy events to container\n // Bubble up key events for Edge\n\n const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' ');\n on.call(player, player.media, proxyEvents, event => {\n let {\n detail = {}\n } = event; // Get error details from media\n\n if (event.type === 'error') {\n detail = player.media.error;\n }\n\n triggerEvent.call(player, elements.container, event.type, true, detail);\n });\n });\n\n _defineProperty$1(this, \"proxy\", (event, defaultHandler, customHandlerKey) => {\n const {\n player\n } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n let returned = true; // Execute custom handler\n\n if (hasCustomHandler) {\n returned = customHandler.call(player, event);\n } // Only call default handler if not prevented in custom handler\n\n\n if (returned !== false && is.function(defaultHandler)) {\n defaultHandler.call(player, event);\n }\n });\n\n _defineProperty$1(this, \"bind\", (element, type, defaultHandler, customHandlerKey, passive = true) => {\n const {\n player\n } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n on.call(player, element, type, event => this.proxy(event, defaultHandler, customHandlerKey), passive && !hasCustomHandler);\n });\n\n _defineProperty$1(this, \"controls\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player; // IE doesn't support input event, so we fallback to change\n\n const inputEvent = browser.isIE ? 'change' : 'input'; // Play/pause toggle\n\n if (elements.buttons.play) {\n Array.from(elements.buttons.play).forEach(button => {\n this.bind(button, 'click', () => {\n silencePromise(player.togglePlay());\n }, 'play');\n });\n } // Pause\n\n\n this.bind(elements.buttons.restart, 'click', player.restart, 'restart'); // Rewind\n\n this.bind(elements.buttons.rewind, 'click', () => {\n // Record seek time so we can prevent hiding controls for a few seconds after rewind\n player.lastSeekTime = Date.now();\n player.rewind();\n }, 'rewind'); // Rewind\n\n this.bind(elements.buttons.fastForward, 'click', () => {\n // Record seek time so we can prevent hiding controls for a few seconds after fast forward\n player.lastSeekTime = Date.now();\n player.forward();\n }, 'fastForward'); // Mute toggle\n\n this.bind(elements.buttons.mute, 'click', () => {\n player.muted = !player.muted;\n }, 'mute'); // Captions toggle\n\n this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions()); // Download\n\n this.bind(elements.buttons.download, 'click', () => {\n triggerEvent.call(player, player.media, 'download');\n }, 'download'); // Fullscreen toggle\n\n this.bind(elements.buttons.fullscreen, 'click', () => {\n player.fullscreen.toggle();\n }, 'fullscreen'); // Picture-in-Picture\n\n this.bind(elements.buttons.pip, 'click', () => {\n player.pip = 'toggle';\n }, 'pip'); // Airplay\n\n this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay'); // Settings menu - click toggle\n\n this.bind(elements.buttons.settings, 'click', event => {\n // Prevent the document click listener closing the menu\n event.stopPropagation();\n event.preventDefault();\n controls.toggleMenu.call(player, event);\n }, null, false); // Can't be passive as we're preventing default\n // Settings menu - keyboard toggle\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n\n this.bind(elements.buttons.settings, 'keyup', event => {\n const code = event.which; // We only care about space and return\n\n if (![13, 32].includes(code)) {\n return;\n } // Because return triggers a click anyway, all we need to do is set focus\n\n\n if (code === 13) {\n controls.focusFirstMenuItem.call(player, null, true);\n return;\n } // Prevent scroll\n\n\n event.preventDefault(); // Prevent playing video (Firefox)\n\n event.stopPropagation(); // Toggle menu\n\n controls.toggleMenu.call(player, event);\n }, null, false // Can't be passive as we're preventing default\n ); // Escape closes menu\n\n this.bind(elements.settings.menu, 'keydown', event => {\n if (event.which === 27) {\n controls.toggleMenu.call(player, event);\n }\n }); // Set range input alternative \"value\", which matches the tooltip time (#954)\n\n this.bind(elements.inputs.seek, 'mousedown mousemove', event => {\n const rect = elements.progress.getBoundingClientRect();\n const percent = 100 / rect.width * (event.pageX - rect.left);\n event.currentTarget.setAttribute('seek-value', percent);\n }); // Pause while seeking\n\n this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', event => {\n const seek = event.currentTarget;\n const code = event.keyCode ? event.keyCode : event.which;\n const attribute = 'play-on-seeked';\n\n if (is.keyboardEvent(event) && code !== 39 && code !== 37) {\n return;\n } // Record seek time so we can prevent hiding controls for a few seconds after seek\n\n\n player.lastSeekTime = Date.now(); // Was playing before?\n\n const play = seek.hasAttribute(attribute); // Done seeking\n\n const done = ['mouseup', 'touchend', 'keyup'].includes(event.type); // If we're done seeking and it was playing, resume playback\n\n if (play && done) {\n seek.removeAttribute(attribute);\n silencePromise(player.play());\n } else if (!done && player.playing) {\n seek.setAttribute(attribute, '');\n player.pause();\n }\n }); // Fix range inputs on iOS\n // Super weird iOS bug where after you interact with an <input type=\"range\">,\n // it takes over further interactions on the page. This is a hack\n\n if (browser.isIos) {\n const inputs = getElements.call(player, 'input[type=\"range\"]');\n Array.from(inputs).forEach(input => this.bind(input, inputEvent, event => repaint(event.target)));\n } // Seek\n\n\n this.bind(elements.inputs.seek, inputEvent, event => {\n const seek = event.currentTarget; // If it exists, use seek-value instead of \"value\" for consistency with tooltip time (#954)\n\n let seekTo = seek.getAttribute('seek-value');\n\n if (is.empty(seekTo)) {\n seekTo = seek.value;\n }\n\n seek.removeAttribute('seek-value');\n player.currentTime = seekTo / seek.max * player.duration;\n }, 'seek'); // Seek tooltip\n\n this.bind(elements.progress, 'mouseenter mouseleave mousemove', event => controls.updateSeekTooltip.call(player, event)); // Preview thumbnails plugin\n // TODO: Really need to work on some sort of plug-in wide event bus or pub-sub for this\n\n this.bind(elements.progress, 'mousemove touchmove', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startMove(event);\n }\n }); // Hide thumbnail preview - on mouse click, mouse leave, and video play/seek. All four are required, e.g., for buffering\n\n this.bind(elements.progress, 'mouseleave touchend click', () => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endMove(false, true);\n }\n }); // Show scrubbing preview\n\n this.bind(elements.progress, 'mousedown touchstart', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startScrubbing(event);\n }\n });\n this.bind(elements.progress, 'mouseup touchend', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endScrubbing(event);\n }\n }); // Polyfill for lower fill in <input type=\"range\"> for webkit\n\n if (browser.isWebkit) {\n Array.from(getElements.call(player, 'input[type=\"range\"]')).forEach(element => {\n this.bind(element, 'input', event => controls.updateRangeFill.call(player, event.target));\n });\n } // Current time invert\n // Only if one time element is used for both currentTime and duration\n\n\n if (player.config.toggleInvert && !is.element(elements.display.duration)) {\n this.bind(elements.display.currentTime, 'click', () => {\n // Do nothing if we're at the start\n if (player.currentTime === 0) {\n return;\n }\n\n player.config.invertTime = !player.config.invertTime;\n controls.timeUpdate.call(player);\n });\n } // Volume\n\n\n this.bind(elements.inputs.volume, inputEvent, event => {\n player.volume = event.target.value;\n }, 'volume'); // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting)\n\n this.bind(elements.controls, 'mouseenter mouseleave', event => {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }); // Also update controls.hover state for any non-player children of fullscreen element (as above)\n\n if (elements.fullscreen) {\n Array.from(elements.fullscreen.children).filter(c => !c.contains(elements.container)).forEach(child => {\n this.bind(child, 'mouseenter mouseleave', event => {\n if (elements.controls) {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }\n });\n });\n } // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting)\n\n\n this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', event => {\n elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type);\n }); // Show controls when they receive focus (e.g., when using keyboard tab key)\n\n this.bind(elements.controls, 'focusin', () => {\n const {\n config,\n timers\n } = player; // Skip transition to prevent focus from scrolling the parent element\n\n toggleClass(elements.controls, config.classNames.noTransition, true); // Toggle\n\n ui.toggleControls.call(player, true); // Restore transition\n\n setTimeout(() => {\n toggleClass(elements.controls, config.classNames.noTransition, false);\n }, 0); // Delay a little more for mouse users\n\n const delay = this.touch ? 3000 : 4000; // Clear timer\n\n clearTimeout(timers.controls); // Hide again after delay\n\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n }); // Mouse wheel for volume\n\n this.bind(elements.inputs.volume, 'wheel', event => {\n // Detect \"natural\" scroll - suppored on OS X Safari only\n // Other browsers on OS X will be inverted until support improves\n const inverted = event.webkitDirectionInvertedFromDevice; // Get delta from event. Invert if `inverted` is true\n\n const [x, y] = [event.deltaX, -event.deltaY].map(value => inverted ? -value : value); // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta)\n\n const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y); // Change the volume by 2%\n\n player.increaseVolume(direction / 50); // Don't break page scrolling at max and min\n\n const {\n volume\n } = player.media;\n\n if (direction === 1 && volume < 1 || direction === -1 && volume > 0) {\n event.preventDefault();\n }\n }, 'volume', false);\n });\n\n this.player = _player;\n this.lastKey = null;\n this.focusTimer = null;\n this.lastKeyDown = null;\n this.handleKey = this.handleKey.bind(this);\n this.toggleMenu = this.toggleMenu.bind(this);\n this.setTabFocus = this.setTabFocus.bind(this);\n this.firstTouch = this.firstTouch.bind(this);\n } // Handle key presses\n\n\n handleKey(event) {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n const code = event.keyCode ? event.keyCode : event.which;\n const pressed = event.type === 'keydown';\n const repeat = pressed && code === this.lastKey; // Bail if a modifier key is set\n\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {\n return;\n } // If the event is bubbled from the media element\n // Firefox doesn't get the keycode for whatever reason\n\n\n if (!is.number(code)) {\n return;\n } // Seek by the number keys\n\n\n const seekByKey = () => {\n // Divide the max duration into 10th's and times by the number value\n player.currentTime = player.duration / 10 * (code - 48);\n }; // Handle the key on keydown\n // Reset on keyup\n\n\n if (pressed) {\n // Check focused element\n // and if the focused element is not editable (e.g. text input)\n // and any that accept key input http://webaim.org/techniques/keyboard/\n const focused = document.activeElement;\n\n if (is.element(focused)) {\n const {\n editable\n } = player.config.selectors;\n const {\n seek\n } = elements.inputs;\n\n if (focused !== seek && matches(focused, editable)) {\n return;\n }\n\n if (event.which === 32 && matches(focused, 'button, [role^=\"menuitem\"]')) {\n return;\n }\n } // Which keycodes should we prevent default\n\n\n const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79]; // If the code is found prevent default (e.g. prevent scrolling for arrows)\n\n if (preventDefault.includes(code)) {\n event.preventDefault();\n event.stopPropagation();\n }\n\n switch (code) {\n case 48:\n case 49:\n case 50:\n case 51:\n case 52:\n case 53:\n case 54:\n case 55:\n case 56:\n case 57:\n // 0-9\n if (!repeat) {\n seekByKey();\n }\n\n break;\n\n case 32:\n case 75:\n // Space and K key\n if (!repeat) {\n silencePromise(player.togglePlay());\n }\n\n break;\n\n case 38:\n // Arrow up\n player.increaseVolume(0.1);\n break;\n\n case 40:\n // Arrow down\n player.decreaseVolume(0.1);\n break;\n\n case 77:\n // M key\n if (!repeat) {\n player.muted = !player.muted;\n }\n\n break;\n\n case 39:\n // Arrow forward\n player.forward();\n break;\n\n case 37:\n // Arrow back\n player.rewind();\n break;\n\n case 70:\n // F key\n player.fullscreen.toggle();\n break;\n\n case 67:\n // C key\n if (!repeat) {\n player.toggleCaptions();\n }\n\n break;\n\n case 76:\n // L key\n player.loop = !player.loop;\n break;\n } // Escape is handle natively when in full screen\n // So we only need to worry about non native\n\n\n if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) {\n player.fullscreen.toggle();\n } // Store last code for next cycle\n\n\n this.lastKey = code;\n } else {\n this.lastKey = null;\n }\n } // Toggle menu\n\n\n toggleMenu(event) {\n controls.toggleMenu.call(this.player, event);\n } // Device is touch enabled\n\n\n }\n\n var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\n function createCommonjsModule(fn, module) {\n \treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n }\n\n var loadjs_umd = createCommonjsModule(function (module, exports) {\n (function (root, factory) {\n {\n module.exports = factory();\n }\n })(commonjsGlobal, function () {\n /**\n * Global dependencies.\n * @global {Object} document - DOM\n */\n var devnull = function () {},\n bundleIdCache = {},\n bundleResultCache = {},\n bundleCallbackQueue = {};\n /**\n * Subscribe to bundle load event.\n * @param {string[]} bundleIds - Bundle ids\n * @param {Function} callbackFn - The callback function\n */\n\n\n function subscribe(bundleIds, callbackFn) {\n // listify\n bundleIds = bundleIds.push ? bundleIds : [bundleIds];\n var depsNotFound = [],\n i = bundleIds.length,\n numWaiting = i,\n fn,\n bundleId,\n r,\n q; // define callback function\n\n fn = function (bundleId, pathsNotFound) {\n if (pathsNotFound.length) depsNotFound.push(bundleId);\n numWaiting--;\n if (!numWaiting) callbackFn(depsNotFound);\n }; // register callback\n\n\n while (i--) {\n bundleId = bundleIds[i]; // execute callback if in result cache\n\n r = bundleResultCache[bundleId];\n\n if (r) {\n fn(bundleId, r);\n continue;\n } // add to callback queue\n\n\n q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];\n q.push(fn);\n }\n }\n /**\n * Publish bundle load event.\n * @param {string} bundleId - Bundle id\n * @param {string[]} pathsNotFound - List of files not found\n */\n\n\n function publish(bundleId, pathsNotFound) {\n // exit if id isn't defined\n if (!bundleId) return;\n var q = bundleCallbackQueue[bundleId]; // cache result\n\n bundleResultCache[bundleId] = pathsNotFound; // exit if queue is empty\n\n if (!q) return; // empty callback queue\n\n while (q.length) {\n q[0](bundleId, pathsNotFound);\n q.splice(0, 1);\n }\n }\n /**\n * Execute callbacks.\n * @param {Object or Function} args - The callback args\n * @param {string[]} depsNotFound - List of dependencies not found\n */\n\n\n function executeCallbacks(args, depsNotFound) {\n // accept function as argument\n if (args.call) args = {\n success: args\n }; // success and error callbacks\n\n if (depsNotFound.length) (args.error || devnull)(depsNotFound);else (args.success || devnull)(args);\n }\n /**\n * Load individual file.\n * @param {string} path - The file path\n * @param {Function} callbackFn - The callback function\n */\n\n\n function loadFile(path, callbackFn, args, numTries) {\n var doc = document,\n async = args.async,\n maxTries = (args.numRetries || 0) + 1,\n beforeCallbackFn = args.before || devnull,\n pathname = path.replace(/[\\?|#].*$/, ''),\n pathStripped = path.replace(/^(css|img)!/, ''),\n isLegacyIECss,\n e;\n numTries = numTries || 0;\n\n if (/(^css!|\\.css$)/.test(pathname)) {\n // css\n e = doc.createElement('link');\n e.rel = 'stylesheet';\n e.href = pathStripped; // tag IE9+\n\n isLegacyIECss = 'hideFocus' in e; // use preload in IE Edge (to detect load errors)\n\n if (isLegacyIECss && e.relList) {\n isLegacyIECss = 0;\n e.rel = 'preload';\n e.as = 'style';\n }\n } else if (/(^img!|\\.(png|gif|jpg|svg|webp)$)/.test(pathname)) {\n // image\n e = doc.createElement('img');\n e.src = pathStripped;\n } else {\n // javascript\n e = doc.createElement('script');\n e.src = path;\n e.async = async === undefined ? true : async;\n }\n\n e.onload = e.onerror = e.onbeforeload = function (ev) {\n var result = ev.type[0]; // treat empty stylesheets as failures to get around lack of onerror\n // support in IE9-11\n\n if (isLegacyIECss) {\n try {\n if (!e.sheet.cssText.length) result = 'e';\n } catch (x) {\n // sheets objects created from load errors don't allow access to\n // `cssText` (unless error is Code:18 SecurityError)\n if (x.code != 18) result = 'e';\n }\n } // handle retries in case of load failure\n\n\n if (result == 'e') {\n // increment counter\n numTries += 1; // exit function and try again\n\n if (numTries < maxTries) {\n return loadFile(path, callbackFn, args, numTries);\n }\n } else if (e.rel == 'preload' && e.as == 'style') {\n // activate preloaded stylesheets\n return e.rel = 'stylesheet'; // jshint ignore:line\n } // execute callback\n\n\n callbackFn(path, result, ev.defaultPrevented);\n }; // add to document (unless callback returns `false`)\n\n\n if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);\n }\n /**\n * Load multiple files.\n * @param {string[]} paths - The file paths\n * @param {Function} callbackFn - The callback function\n */\n\n\n function loadFiles(paths, callbackFn, args) {\n // listify paths\n paths = paths.push ? paths : [paths];\n var numWaiting = paths.length,\n x = numWaiting,\n pathsNotFound = [],\n fn,\n i; // define callback function\n\n fn = function (path, result, defaultPrevented) {\n // handle error\n if (result == 'e') pathsNotFound.push(path); // handle beforeload event. If defaultPrevented then that means the load\n // will be blocked (ex. Ghostery/ABP on Safari)\n\n if (result == 'b') {\n if (defaultPrevented) pathsNotFound.push(path);else return;\n }\n\n numWaiting--;\n if (!numWaiting) callbackFn(pathsNotFound);\n }; // load scripts\n\n\n for (i = 0; i < x; i++) loadFile(paths[i], fn, args);\n }\n /**\n * Initiate script load and register bundle.\n * @param {(string|string[])} paths - The file paths\n * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success\n * callback or (3) object literal with success/error arguments, numRetries,\n * etc.\n * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object\n * literal with success/error arguments, numRetries, etc.\n */\n\n\n function loadjs(paths, arg1, arg2) {\n var bundleId, args; // bundleId (if string)\n\n if (arg1 && arg1.trim) bundleId = arg1; // args (default is {})\n\n args = (bundleId ? arg2 : arg1) || {}; // throw error if bundle is already defined\n\n if (bundleId) {\n if (bundleId in bundleIdCache) {\n throw \"LoadJS\";\n } else {\n bundleIdCache[bundleId] = true;\n }\n }\n\n function loadFn(resolve, reject) {\n loadFiles(paths, function (pathsNotFound) {\n // execute callbacks\n executeCallbacks(args, pathsNotFound); // resolve Promise\n\n if (resolve) {\n executeCallbacks({\n success: resolve,\n error: reject\n }, pathsNotFound);\n } // publish bundle load event\n\n\n publish(bundleId, pathsNotFound);\n }, args);\n }\n\n if (args.returnPromise) return new Promise(loadFn);else loadFn();\n }\n /**\n * Execute callbacks when dependencies have been satisfied.\n * @param {(string|string[])} deps - List of bundle ids\n * @param {Object} args - success/error arguments\n */\n\n\n loadjs.ready = function ready(deps, args) {\n // subscribe to bundle load event\n subscribe(deps, function (depsNotFound) {\n // execute callbacks\n executeCallbacks(args, depsNotFound);\n });\n return loadjs;\n };\n /**\n * Manually satisfy bundle dependencies.\n * @param {string} bundleId - The bundle id\n */\n\n\n loadjs.done = function done(bundleId) {\n publish(bundleId, []);\n };\n /**\n * Reset loadjs dependencies statuses\n */\n\n\n loadjs.reset = function reset() {\n bundleIdCache = {};\n bundleResultCache = {};\n bundleCallbackQueue = {};\n };\n /**\n * Determine if bundle has already been defined\n * @param String} bundleId - The bundle id\n */\n\n\n loadjs.isDefined = function isDefined(bundleId) {\n return bundleId in bundleIdCache;\n }; // export\n\n\n return loadjs;\n });\n });\n\n // ==========================================================================\n function loadScript(url) {\n return new Promise((resolve, reject) => {\n loadjs_umd(url, {\n success: resolve,\n error: reject\n });\n });\n }\n\n // ==========================================================================\n\n function parseId$1(url) {\n if (is.empty(url)) {\n return null;\n }\n\n if (is.number(Number(url))) {\n return url;\n }\n\n const regex = /^.*(vimeo.com\\/|video\\/)(\\d+).*/;\n return url.match(regex) ? RegExp.$2 : url;\n } // Try to extract a hash for private videos from the URL\n\n\n function parseHash(url) {\n /* This regex matches a hexadecimal hash if given in any of these forms:\n * - [https://player.]vimeo.com/video/{id}/{hash}[?params]\n * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms]\n * - [https://player.]vimeo.com/video/{id}?[params]&h={hash}\n * - video/{id}/{hash}\n * If matched, the hash is available in the named group `hash`\n */\n const regex = /^.*(?:vimeo.com\\/|video\\/)(?:\\d+)(?:\\?.*&*h=|\\/)+(?<hash>[\\d,a-f]+)/;\n const found = url.match(regex);\n return found ? found.groups.hash : null;\n } // Set playback state and trigger change (only on actual change)\n\n\n function assurePlaybackState$1(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n }\n\n const vimeo = {\n setup() {\n const player = this; // Add embed class for responsive\n\n toggleClass(player.elements.wrapper, player.config.classNames.embed, true); // Set speed options from config\n\n player.options.speed = player.config.speed.options; // Set intial ratio\n\n setAspectRatio.call(player); // Load the SDK if not already\n\n if (!is.object(window.Vimeo)) {\n loadScript(player.config.urls.vimeo.sdk).then(() => {\n vimeo.ready.call(player);\n }).catch(error => {\n player.debug.warn('Vimeo SDK (player.js) failed to load', error);\n });\n } else {\n vimeo.ready.call(player);\n }\n },\n\n // API Ready\n ready() {\n const player = this;\n const config = player.config.vimeo;\n const {\n premium,\n referrerPolicy,\n ...frameParams\n } = config; // Get the source URL or ID\n\n let source = player.media.getAttribute('src');\n let hash = ''; // Get from <div> if needed\n\n if (is.empty(source)) {\n source = player.media.getAttribute(player.config.attributes.embed.id); // hash can also be set as attribute on the <div>\n\n hash = player.media.getAttribute(player.config.attributes.embed.hash);\n } else {\n hash = parseHash(source);\n }\n\n const hashParam = hash ? {\n h: hash\n } : {}; // If the owner has a pro or premium account then we can hide controls etc\n\n if (premium) {\n Object.assign(frameParams, {\n controls: false,\n sidedock: false\n });\n } // Get Vimeo params for the iframe\n\n\n const params = buildUrlParams({\n loop: player.config.loop.active,\n autoplay: player.autoplay,\n muted: player.muted,\n gesture: 'media',\n playsinline: !this.config.fullscreen.iosNative,\n // hash has to be added to iframe-URL\n ...hashParam,\n ...frameParams\n });\n const id = parseId$1(source); // Build an iframe\n\n const iframe = createElement('iframe');\n const src = format(player.config.urls.vimeo.iframe, id, params);\n iframe.setAttribute('src', src);\n iframe.setAttribute('allowfullscreen', '');\n iframe.setAttribute('allow', ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; ')); // Set the referrer policy if required\n\n if (!is.empty(referrerPolicy)) {\n iframe.setAttribute('referrerPolicy', referrerPolicy);\n } // Inject the package\n\n\n if (premium || !config.customControls) {\n iframe.setAttribute('data-poster', player.poster);\n player.media = replaceElement(iframe, player.media);\n } else {\n const wrapper = createElement('div', {\n class: player.config.classNames.embedContainer,\n 'data-poster': player.poster\n });\n wrapper.appendChild(iframe);\n player.media = replaceElement(wrapper, player.media);\n } // Get poster image\n\n\n if (!config.customControls) {\n fetch(format(player.config.urls.vimeo.api, src)).then(response => {\n if (is.empty(response) || !response.thumbnail_url) {\n return;\n } // Set and show poster\n\n\n ui.setPoster.call(player, response.thumbnail_url).catch(() => {});\n });\n } // Setup instance\n // https://github.com/vimeo/player.js\n\n\n player.embed = new window.Vimeo.Player(iframe, {\n autopause: player.config.autopause,\n muted: player.muted\n });\n player.media.paused = true;\n player.media.currentTime = 0; // Disable native text track rendering\n\n if (player.supported.ui) {\n player.embed.disableTextTrack();\n } // Create a faux HTML5 API using the Vimeo API\n\n\n player.media.play = () => {\n assurePlaybackState$1.call(player, true);\n return player.embed.play();\n };\n\n player.media.pause = () => {\n assurePlaybackState$1.call(player, false);\n return player.embed.pause();\n };\n\n player.media.stop = () => {\n player.pause();\n player.currentTime = 0;\n }; // Seeking\n\n\n let {\n currentTime\n } = player.media;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return currentTime;\n },\n\n set(time) {\n // Vimeo will automatically play on seek if the video hasn't been played before\n // Get current paused state and volume etc\n const {\n embed,\n media,\n paused,\n volume\n } = player;\n const restorePause = paused && !embed.hasPlayed; // Set seeking state and trigger event\n\n media.seeking = true;\n triggerEvent.call(player, media, 'seeking'); // If paused, mute until seek is complete\n\n Promise.resolve(restorePause && embed.setVolume(0)) // Seek\n .then(() => embed.setCurrentTime(time)) // Restore paused\n .then(() => restorePause && embed.pause()) // Restore volume\n .then(() => restorePause && embed.setVolume(volume)).catch(() => {// Do nothing\n });\n }\n\n }); // Playback speed\n\n let speed = player.config.speed.selected;\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return speed;\n },\n\n set(input) {\n player.embed.setPlaybackRate(input).then(() => {\n speed = input;\n triggerEvent.call(player, player.media, 'ratechange');\n }).catch(() => {\n // Cannot set Playback Rate, Video is probably not on Pro account\n player.options.speed = [1];\n });\n }\n\n }); // Volume\n\n let {\n volume\n } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n\n set(input) {\n player.embed.setVolume(input).then(() => {\n volume = input;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n }\n\n }); // Muted\n\n let {\n muted\n } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : false;\n player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => {\n muted = toggle;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n }\n\n }); // Loop\n\n let {\n loop\n } = player.config;\n Object.defineProperty(player.media, 'loop', {\n get() {\n return loop;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : player.config.loop.active;\n player.embed.setLoop(toggle).then(() => {\n loop = toggle;\n });\n }\n\n }); // Source\n\n let currentSrc;\n player.embed.getVideoUrl().then(value => {\n currentSrc = value;\n controls.setDownloadUrl.call(player);\n }).catch(error => {\n this.debug.warn(error);\n });\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return currentSrc;\n }\n\n }); // Ended\n\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n }\n\n }); // Set aspect ratio based on video size\n\n Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(dimensions => {\n const [width, height] = dimensions;\n player.embed.ratio = roundAspectRatio(width, height);\n setAspectRatio.call(this);\n }); // Set autopause\n\n player.embed.setAutopause(player.config.autopause).then(state => {\n player.config.autopause = state;\n }); // Get title\n\n player.embed.getVideoTitle().then(title => {\n player.config.title = title;\n ui.setTitle.call(this);\n }); // Get current time\n\n player.embed.getCurrentTime().then(value => {\n currentTime = value;\n triggerEvent.call(player, player.media, 'timeupdate');\n }); // Get duration\n\n player.embed.getDuration().then(value => {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }); // Get captions\n\n player.embed.getTextTracks().then(tracks => {\n player.media.textTracks = tracks;\n captions.setup.call(player);\n });\n player.embed.on('cuechange', ({\n cues = []\n }) => {\n const strippedCues = cues.map(cue => stripHTML(cue.text));\n captions.updateCues.call(player, strippedCues);\n });\n player.embed.on('loaded', () => {\n // Assure state and events are updated on autoplay\n player.embed.getPaused().then(paused => {\n assurePlaybackState$1.call(player, !paused);\n\n if (!paused) {\n triggerEvent.call(player, player.media, 'playing');\n }\n });\n\n if (is.element(player.embed.element) && player.supported.ui) {\n const frame = player.embed.element; // Fix keyboard focus issues\n // https://github.com/sampotts/plyr/issues/317\n\n frame.setAttribute('tabindex', -1);\n }\n });\n player.embed.on('bufferstart', () => {\n triggerEvent.call(player, player.media, 'waiting');\n });\n player.embed.on('bufferend', () => {\n triggerEvent.call(player, player.media, 'playing');\n });\n player.embed.on('play', () => {\n assurePlaybackState$1.call(player, true);\n triggerEvent.call(player, player.media, 'playing');\n });\n player.embed.on('pause', () => {\n assurePlaybackState$1.call(player, false);\n });\n player.embed.on('timeupdate', data => {\n player.media.seeking = false;\n currentTime = data.seconds;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n player.embed.on('progress', data => {\n player.media.buffered = data.percent;\n triggerEvent.call(player, player.media, 'progress'); // Check all loaded\n\n if (parseInt(data.percent, 10) === 1) {\n triggerEvent.call(player, player.media, 'canplaythrough');\n } // Get duration as if we do it before load, it gives an incorrect value\n // https://github.com/sampotts/plyr/issues/891\n\n\n player.embed.getDuration().then(value => {\n if (value !== player.media.duration) {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }\n });\n });\n player.embed.on('seeked', () => {\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n });\n player.embed.on('ended', () => {\n player.media.paused = true;\n triggerEvent.call(player, player.media, 'ended');\n });\n player.embed.on('error', detail => {\n player.media.error = detail;\n triggerEvent.call(player, player.media, 'error');\n }); // Rebuild UI\n\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 0);\n }\n }\n\n };\n\n // ==========================================================================\n\n function parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n const regex = /^.*(youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=|&v=)([^#&?]*).*/;\n return url.match(regex) ? RegExp.$2 : url;\n } // Set playback state and trigger change (only on actual change)\n\n\n function assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n }\n\n function getHost(config) {\n if (config.noCookie) {\n return 'https://www.youtube-nocookie.com';\n }\n\n if (window.location.protocol === 'http:') {\n return 'http://www.youtube.com';\n } // Use YouTube's default\n\n\n return undefined;\n }\n\n const youtube = {\n setup() {\n // Add embed class for responsive\n toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Setup API\n\n if (is.object(window.YT) && is.function(window.YT.Player)) {\n youtube.ready.call(this);\n } else {\n // Reference current global callback\n const callback = window.onYouTubeIframeAPIReady; // Set callback to process queue\n\n window.onYouTubeIframeAPIReady = () => {\n // Call global callback if set\n if (is.function(callback)) {\n callback();\n }\n\n youtube.ready.call(this);\n }; // Load the SDK\n\n\n loadScript(this.config.urls.youtube.sdk).catch(error => {\n this.debug.warn('YouTube API failed to load', error);\n });\n }\n },\n\n // Get the media title\n getTitle(videoId) {\n const url = format(this.config.urls.youtube.api, videoId);\n fetch(url).then(data => {\n if (is.object(data)) {\n const {\n title,\n height,\n width\n } = data; // Set title\n\n this.config.title = title;\n ui.setTitle.call(this); // Set aspect ratio\n\n this.embed.ratio = roundAspectRatio(width, height);\n }\n\n setAspectRatio.call(this);\n }).catch(() => {\n // Set aspect ratio\n setAspectRatio.call(this);\n });\n },\n\n // API ready\n ready() {\n const player = this;\n const config = player.config.youtube; // Ignore already setup (race condition)\n\n const currentId = player.media && player.media.getAttribute('id');\n\n if (!is.empty(currentId) && currentId.startsWith('youtube-')) {\n return;\n } // Get the source URL or ID\n\n\n let source = player.media.getAttribute('src'); // Get from <div> if needed\n\n if (is.empty(source)) {\n source = player.media.getAttribute(this.config.attributes.embed.id);\n } // Replace the <iframe> with a <div> due to YouTube API issues\n\n\n const videoId = parseId(source);\n const id = generateId(player.provider); // Replace media element\n\n const container = createElement('div', {\n id,\n 'data-poster': config.customControls ? player.poster : undefined\n });\n player.media = replaceElement(container, player.media); // Only load the poster when using custom controls\n\n if (config.customControls) {\n const posterSrc = s => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`; // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide)\n\n\n loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded\n .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3\n .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists\n .then(image => ui.setPoster.call(player, image.src)).then(src => {\n // If the image is padded, use background-size \"cover\" instead (like youtube does too with their posters)\n if (!src.includes('maxres')) {\n player.elements.poster.style.backgroundSize = 'cover';\n }\n }).catch(() => {});\n } // Setup instance\n // https://developers.google.com/youtube/iframe_api_reference\n\n\n player.embed = new window.YT.Player(player.media, {\n videoId,\n host: getHost(config),\n playerVars: extend({}, {\n // Autoplay\n autoplay: player.config.autoplay ? 1 : 0,\n // iframe interface language\n hl: player.config.hl,\n // Only show controls if not fully supported or opted out\n controls: player.supported.ui && config.customControls ? 0 : 1,\n // Disable keyboard as we handle it\n disablekb: 1,\n // Allow iOS inline playback\n playsinline: !player.config.fullscreen.iosNative ? 1 : 0,\n // Captions are flaky on YouTube\n cc_load_policy: player.captions.active ? 1 : 0,\n cc_lang_pref: player.config.captions.language,\n // Tracking for stats\n widget_referrer: window ? window.location.href : null\n }, config),\n events: {\n onError(event) {\n // YouTube may fire onError twice, so only handle it once\n if (!player.media.error) {\n const code = event.data; // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError\n\n const message = {\n 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.',\n 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.',\n 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.',\n 101: 'The owner of the requested video does not allow it to be played in embedded players.',\n 150: 'The owner of the requested video does not allow it to be played in embedded players.'\n }[code] || 'An unknown error occured';\n player.media.error = {\n code,\n message\n };\n triggerEvent.call(player, player.media, 'error');\n }\n },\n\n onPlaybackRateChange(event) {\n // Get the instance\n const instance = event.target; // Get current speed\n\n player.media.playbackRate = instance.getPlaybackRate();\n triggerEvent.call(player, player.media, 'ratechange');\n },\n\n onReady(event) {\n // Bail if onReady has already been called. See issue #1108\n if (is.function(player.media.play)) {\n return;\n } // Get the instance\n\n\n const instance = event.target; // Get the title\n\n youtube.getTitle.call(player, videoId); // Create a faux HTML5 API using the YouTube API\n\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n instance.playVideo();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n instance.pauseVideo();\n };\n\n player.media.stop = () => {\n instance.stopVideo();\n };\n\n player.media.duration = instance.getDuration();\n player.media.paused = true; // Seeking\n\n player.media.currentTime = 0;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return Number(instance.getCurrentTime());\n },\n\n set(time) {\n // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet).\n if (player.paused && !player.embed.hasPlayed) {\n player.embed.mute();\n } // Set seeking state and trigger event\n\n\n player.media.seeking = true;\n triggerEvent.call(player, player.media, 'seeking'); // Seek after events sent\n\n instance.seekTo(time);\n }\n\n }); // Playback speed\n\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return instance.getPlaybackRate();\n },\n\n set(input) {\n instance.setPlaybackRate(input);\n }\n\n }); // Volume\n\n let {\n volume\n } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n\n set(input) {\n volume = input;\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n }\n\n }); // Muted\n\n let {\n muted\n } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : muted;\n muted = toggle;\n instance[toggle ? 'mute' : 'unMute']();\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n }\n\n }); // Source\n\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return instance.getVideoUrl();\n }\n\n }); // Ended\n\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n }\n\n }); // Get available speeds\n\n const speeds = instance.getAvailablePlaybackRates(); // Filter based on config\n\n player.options.speed = speeds.filter(s => player.config.speed.options.includes(s)); // Set the tabindex to avoid focus entering iframe\n\n if (player.supported.ui && config.customControls) {\n player.media.setAttribute('tabindex', -1);\n }\n\n triggerEvent.call(player, player.media, 'timeupdate');\n triggerEvent.call(player, player.media, 'durationchange'); // Reset timer\n\n clearInterval(player.timers.buffering); // Setup buffering\n\n player.timers.buffering = setInterval(() => {\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction(); // Trigger progress only when we actually buffer something\n\n if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) {\n triggerEvent.call(player, player.media, 'progress');\n } // Set last buffer point\n\n\n player.media.lastBuffered = player.media.buffered; // Bail if we're at 100%\n\n if (player.media.buffered === 1) {\n clearInterval(player.timers.buffering); // Trigger event\n\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n }, 200); // Rebuild UI\n\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 50);\n }\n },\n\n onStateChange(event) {\n // Get the instance\n const instance = event.target; // Reset timer\n\n clearInterval(player.timers.playing);\n const seeked = player.media.seeking && [1, 2].includes(event.data);\n\n if (seeked) {\n // Unset seeking and fire seeked event\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n } // Handle events\n // -1 Unstarted\n // 0 Ended\n // 1 Playing\n // 2 Paused\n // 3 Buffering\n // 5 Video cued\n\n\n switch (event.data) {\n case -1:\n // Update scrubber\n triggerEvent.call(player, player.media, 'timeupdate'); // Get loaded % from YouTube\n\n player.media.buffered = instance.getVideoLoadedFraction();\n triggerEvent.call(player, player.media, 'progress');\n break;\n\n case 0:\n assurePlaybackState.call(player, false); // YouTube doesn't support loop for a single video, so mimick it.\n\n if (player.media.loop) {\n // YouTube needs a call to `stopVideo` before playing again\n instance.stopVideo();\n instance.playVideo();\n } else {\n triggerEvent.call(player, player.media, 'ended');\n }\n\n break;\n\n case 1:\n // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet)\n if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) {\n player.media.pause();\n } else {\n assurePlaybackState.call(player, true);\n triggerEvent.call(player, player.media, 'playing'); // Poll to get playback progress\n\n player.timers.playing = setInterval(() => {\n triggerEvent.call(player, player.media, 'timeupdate');\n }, 50); // Check duration again due to YouTube bug\n // https://github.com/sampotts/plyr/issues/374\n // https://code.google.com/p/gdata-issues/issues/detail?id=8690\n\n if (player.media.duration !== instance.getDuration()) {\n player.media.duration = instance.getDuration();\n triggerEvent.call(player, player.media, 'durationchange');\n }\n }\n\n break;\n\n case 2:\n // Restore audio (YouTube starts playing on seek if the video hasn't been played yet)\n if (!player.muted) {\n player.embed.unMute();\n }\n\n assurePlaybackState.call(player, false);\n break;\n\n case 3:\n // Trigger waiting event to add loading classes to container as the video buffers.\n triggerEvent.call(player, player.media, 'waiting');\n break;\n }\n\n triggerEvent.call(player, player.elements.container, 'statechange', false, {\n code: event.data\n });\n }\n\n }\n });\n }\n\n };\n\n // ==========================================================================\n const media = {\n // Setup media\n setup() {\n // If there's no media, bail\n if (!this.media) {\n this.debug.warn('No media element found!');\n return;\n } // Add type class\n\n\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true); // Add provider class\n\n toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true); // Add video class for embeds\n // This will require changes if audio embeds are added\n\n if (this.isEmbed) {\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true);\n } // Inject the player wrapper\n\n\n if (this.isVideo) {\n // Create the wrapper div\n this.elements.wrapper = createElement('div', {\n class: this.config.classNames.video\n }); // Wrap the video in a container\n\n wrap(this.media, this.elements.wrapper); // Poster image container\n\n this.elements.poster = createElement('div', {\n class: this.config.classNames.poster\n });\n this.elements.wrapper.appendChild(this.elements.poster);\n }\n\n if (this.isHTML5) {\n html5.setup.call(this);\n } else if (this.isYouTube) {\n youtube.setup.call(this);\n } else if (this.isVimeo) {\n vimeo.setup.call(this);\n }\n }\n\n };\n\n const destroy = instance => {\n // Destroy our adsManager\n if (instance.manager) {\n instance.manager.destroy();\n } // Destroy our adsManager\n\n\n if (instance.elements.displayContainer) {\n instance.elements.displayContainer.destroy();\n }\n\n instance.elements.container.remove();\n };\n\n class Ads {\n /**\n * Ads constructor.\n * @param {Object} player\n * @return {Ads}\n */\n constructor(player) {\n _defineProperty$1(this, \"load\", () => {\n if (!this.enabled) {\n return;\n } // Check if the Google IMA3 SDK is loaded or load it ourselves\n\n\n if (!is.object(window.google) || !is.object(window.google.ima)) {\n loadScript(this.player.config.urls.googleIMA.sdk).then(() => {\n this.ready();\n }).catch(() => {\n // Script failed to load or is blocked\n this.trigger('error', new Error('Google IMA SDK failed to load'));\n });\n } else {\n this.ready();\n }\n });\n\n _defineProperty$1(this, \"ready\", () => {\n // Double check we're enabled\n if (!this.enabled) {\n destroy(this);\n } // Start ticking our safety timer. If the whole advertisement\n // thing doesn't resolve within our set time; we bail\n\n\n this.startSafetyTimer(12000, 'ready()'); // Clear the safety timer\n\n this.managerPromise.then(() => {\n this.clearSafetyTimer('onAdsManagerLoaded()');\n }); // Set listeners on the Plyr instance\n\n this.listeners(); // Setup the IMA SDK\n\n this.setupIMA();\n });\n\n _defineProperty$1(this, \"setupIMA\", () => {\n // Create the container for our advertisements\n this.elements.container = createElement('div', {\n class: this.player.config.classNames.ads\n });\n this.player.elements.container.appendChild(this.elements.container); // So we can run VPAID2\n\n google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED); // Set language\n\n google.ima.settings.setLocale(this.player.config.ads.language); // Set playback for iOS10+\n\n 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\n\n this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container, this.player.media); // Create ads loader\n\n this.loader = new google.ima.AdsLoader(this.elements.displayContainer); // Listen and respond to ads loaded and error events\n\n this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false);\n this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false); // Request video ads to be pre-loaded\n\n this.requestAds();\n });\n\n _defineProperty$1(this, \"requestAds\", () => {\n const {\n container\n } = this.player.elements;\n\n try {\n // Request video ads\n const request = new google.ima.AdsRequest();\n request.adTagUrl = this.tagUrl; // Specify the linear and nonlinear slot sizes. This helps the SDK\n // to select the correct creative if multiple are returned\n\n request.linearAdSlotWidth = container.offsetWidth;\n request.linearAdSlotHeight = container.offsetHeight;\n request.nonLinearAdSlotWidth = container.offsetWidth;\n request.nonLinearAdSlotHeight = container.offsetHeight; // We only overlay ads as we only support video.\n\n request.forceNonLinearFullSlot = false; // Mute based on current state\n\n request.setAdWillPlayMuted(!this.player.muted);\n this.loader.requestAds(request);\n } catch (error) {\n this.onAdError(error);\n }\n });\n\n _defineProperty$1(this, \"pollCountdown\", (start = false) => {\n if (!start) {\n clearInterval(this.countdownTimer);\n this.elements.container.removeAttribute('data-badge-text');\n return;\n }\n\n const update = () => {\n const time = formatTime(Math.max(this.manager.getRemainingTime(), 0));\n const label = `${i18n.get('advertisement', this.player.config)} - ${time}`;\n this.elements.container.setAttribute('data-badge-text', label);\n };\n\n this.countdownTimer = setInterval(update, 100);\n });\n\n _defineProperty$1(this, \"onAdsManagerLoaded\", event => {\n // Load could occur after a source change (race condition)\n if (!this.enabled) {\n return;\n } // Get the ads manager\n\n\n const settings = new google.ima.AdsRenderingSettings(); // Tell the SDK to save and restore content video state on our behalf\n\n settings.restoreCustomPlaybackStateOnAdBreakComplete = true;\n settings.enablePreloading = true; // The SDK is polling currentTime on the contentPlayback. And needs a duration\n // so it can determine when to start the mid- and post-roll\n\n this.manager = event.getAdsManager(this.player, settings); // Get the cue points for any mid-rolls by filtering out the pre- and post-roll\n\n this.cuePoints = this.manager.getCuePoints(); // Add listeners to the required events\n // Advertisement error events\n\n this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error)); // Advertisement regular events\n\n Object.keys(google.ima.AdEvent.Type).forEach(type => {\n this.manager.addEventListener(google.ima.AdEvent.Type[type], e => this.onAdEvent(e));\n }); // Resolve our adsManager\n\n this.trigger('loaded');\n });\n\n _defineProperty$1(this, \"addCuePoints\", () => {\n // Add advertisement cue's within the time line if available\n if (!is.empty(this.cuePoints)) {\n this.cuePoints.forEach(cuePoint => {\n if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {\n const seekElement = this.player.elements.progress;\n\n if (is.element(seekElement)) {\n const cuePercentage = 100 / this.player.duration * cuePoint;\n const cue = createElement('span', {\n class: this.player.config.classNames.cues\n });\n cue.style.left = `${cuePercentage.toString()}%`;\n seekElement.appendChild(cue);\n }\n }\n });\n }\n });\n\n _defineProperty$1(this, \"onAdEvent\", event => {\n const {\n container\n } = this.player.elements; // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)\n // don't have ad object associated\n\n const ad = event.getAd();\n const adData = event.getAdData(); // Proxy event\n\n const dispatchEvent = type => {\n triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`);\n }; // Bubble the event\n\n\n dispatchEvent(event.type);\n\n switch (event.type) {\n case google.ima.AdEvent.Type.LOADED:\n // This is the first event sent for an ad - it is possible to determine whether the\n // ad is a video ad or an overlay\n this.trigger('loaded'); // Start countdown\n\n this.pollCountdown(true);\n\n if (!ad.isLinear()) {\n // Position AdDisplayContainer correctly for overlay\n ad.width = container.offsetWidth;\n ad.height = container.offsetHeight;\n } // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex());\n // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset());\n\n\n break;\n\n case google.ima.AdEvent.Type.STARTED:\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n break;\n\n case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:\n // All ads for the current videos are done. We can now request new advertisements\n // in case the video is re-played\n // TODO: Example for what happens when a next video in a playlist would be loaded.\n // So here we load a new video when all ads are done.\n // Then we load new ads within a new adsManager. When the video\n // Is started - after - the ads are loaded, then we get ads.\n // You can also easily test cancelling and reloading by running\n // player.ads.cancel() and player.ads.play from the console I guess.\n // this.player.source = {\n // type: 'video',\n // title: 'View From A Blue Moon',\n // sources: [{\n // src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type:\n // 'video/mp4', }], poster:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks:\n // [ { kind: 'captions', label: 'English', srclang: 'en', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',\n // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ],\n // };\n // TODO: So there is still this thing where a video should only be allowed to start\n // playing when the IMA SDK is ready or has failed\n if (this.player.ended) {\n this.loadAds();\n } else {\n // The SDK won't allow new ads to be called without receiving a contentComplete()\n this.loader.contentComplete();\n }\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:\n // This event indicates the ad has started - the video player can adjust the UI,\n // for example display a pause button and remaining time. Fired when content should\n // be paused. This usually happens right before an ad is about to cover the content\n this.pauseContent();\n break;\n\n case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:\n // This event indicates the ad has finished - the video player can perform\n // appropriate UI actions, such as removing the timer for remaining time detection.\n // Fired when content should be resumed. This usually happens when an ad finishes\n // or collapses\n this.pollCountdown();\n this.resumeContent();\n break;\n\n case google.ima.AdEvent.Type.LOG:\n if (adData.adError) {\n this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);\n }\n\n break;\n }\n });\n\n _defineProperty$1(this, \"onAdError\", event => {\n this.cancel();\n this.player.debug.warn('Ads error', event);\n });\n\n _defineProperty$1(this, \"listeners\", () => {\n const {\n container\n } = this.player.elements;\n let time;\n this.player.on('canplay', () => {\n this.addCuePoints();\n });\n this.player.on('ended', () => {\n this.loader.contentComplete();\n });\n this.player.on('timeupdate', () => {\n time = this.player.currentTime;\n });\n this.player.on('seeked', () => {\n const seekedTime = this.player.currentTime;\n\n if (is.empty(this.cuePoints)) {\n return;\n }\n\n this.cuePoints.forEach((cuePoint, index) => {\n if (time < cuePoint && cuePoint < seekedTime) {\n this.manager.discardAdBreak();\n this.cuePoints.splice(index, 1);\n }\n });\n }); // Listen to the resizing of the window. And resize ad accordingly\n // TODO: eventually implement ResizeObserver\n\n window.addEventListener('resize', () => {\n if (this.manager) {\n this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n }\n });\n });\n\n _defineProperty$1(this, \"play\", () => {\n const {\n container\n } = this.player.elements;\n\n if (!this.managerPromise) {\n this.resumeContent();\n } // Play the requested advertisement whenever the adsManager is ready\n\n\n this.managerPromise.then(() => {\n // Set volume to match player\n this.manager.setVolume(this.player.volume); // Initialize the container. Must be done via a user action on mobile devices\n\n this.elements.displayContainer.initialize();\n\n try {\n if (!this.initialized) {\n // Initialize the ads manager. Ad rules playlist will start at this time\n this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will\n // start at this time; the call will be ignored for ad rules\n\n this.manager.start();\n }\n\n this.initialized = true;\n } catch (adError) {\n // An error may be thrown if there was a problem with the\n // VAST response\n this.onAdError(adError);\n }\n }).catch(() => {});\n });\n\n _defineProperty$1(this, \"resumeContent\", () => {\n // Hide the advertisement container\n this.elements.container.style.zIndex = ''; // Ad is stopped\n\n this.playing = false; // Play video\n\n silencePromise(this.player.media.play());\n });\n\n _defineProperty$1(this, \"pauseContent\", () => {\n // Show the advertisement container\n this.elements.container.style.zIndex = 3; // Ad is playing\n\n this.playing = true; // Pause our video.\n\n this.player.media.pause();\n });\n\n _defineProperty$1(this, \"cancel\", () => {\n // Pause our video\n if (this.initialized) {\n this.resumeContent();\n } // Tell our instance that we're done for now\n\n\n this.trigger('error'); // Re-create our adsManager\n\n this.loadAds();\n });\n\n _defineProperty$1(this, \"loadAds\", () => {\n // Tell our adsManager to go bye bye\n this.managerPromise.then(() => {\n // Destroy our adsManager\n if (this.manager) {\n this.manager.destroy();\n } // Re-set our adsManager promises\n\n\n this.managerPromise = new Promise(resolve => {\n this.on('loaded', resolve);\n this.player.debug.log(this.manager);\n }); // Now that the manager has been destroyed set it to also be un-initialized\n\n this.initialized = false; // Now request some new advertisements\n\n this.requestAds();\n }).catch(() => {});\n });\n\n _defineProperty$1(this, \"trigger\", (event, ...args) => {\n const handlers = this.events[event];\n\n if (is.array(handlers)) {\n handlers.forEach(handler => {\n if (is.function(handler)) {\n handler.apply(this, args);\n }\n });\n }\n });\n\n _defineProperty$1(this, \"on\", (event, callback) => {\n if (!is.array(this.events[event])) {\n this.events[event] = [];\n }\n\n this.events[event].push(callback);\n return this;\n });\n\n _defineProperty$1(this, \"startSafetyTimer\", (time, from) => {\n this.player.debug.log(`Safety timer invoked from: ${from}`);\n this.safetyTimer = setTimeout(() => {\n this.cancel();\n this.clearSafetyTimer('startSafetyTimer()');\n }, time);\n });\n\n _defineProperty$1(this, \"clearSafetyTimer\", from => {\n if (!is.nullOrUndefined(this.safetyTimer)) {\n this.player.debug.log(`Safety timer cleared from: ${from}`);\n clearTimeout(this.safetyTimer);\n this.safetyTimer = null;\n }\n });\n\n this.player = player;\n this.config = player.config.ads;\n this.playing = false;\n this.initialized = false;\n this.elements = {\n container: null,\n displayContainer: null\n };\n this.manager = null;\n this.loader = null;\n this.cuePoints = null;\n this.events = {};\n this.safetyTimer = null;\n this.countdownTimer = null; // Setup a promise to resolve when the IMA manager is ready\n\n this.managerPromise = new Promise((resolve, reject) => {\n // The ad is loaded and ready\n this.on('loaded', resolve); // Ads failed\n\n this.on('error', reject);\n });\n this.load();\n }\n\n get enabled() {\n const {\n config\n } = this;\n return this.player.isHTML5 && this.player.isVideo && config.enabled && (!is.empty(config.publisherId) || is.url(config.tagUrl));\n }\n /**\n * Load the IMA SDK\n */\n\n\n // Build the tag URL\n get tagUrl() {\n const {\n config\n } = this;\n\n if (is.url(config.tagUrl)) {\n return config.tagUrl;\n }\n\n const params = {\n AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',\n AV_CHANNELID: '5a0458dc28a06145e4519d21',\n AV_URL: window.location.hostname,\n cb: Date.now(),\n AV_WIDTH: 640,\n AV_HEIGHT: 480,\n AV_CDIM2: config.publisherId\n };\n const base = 'https://go.aniview.com/api/adserver6/vast/';\n return `${base}?${buildUrlParams(params)}`;\n }\n /**\n * In order for the SDK to display ads for our video, we need to tell it where to put them,\n * so here we define our ad container. This div is set up to render on top of the video player.\n * Using the code below, we tell the SDK to render ads within that div. We also provide a\n * handle to the content video player - the SDK will poll the current time of our player to\n * properly place mid-rolls. After we create the ad display container, we initialize it. On\n * mobile devices, this initialization is done as the result of a user action.\n */\n\n\n }\n\n const parseVtt = vttDataString => {\n const processedList = [];\n const frames = vttDataString.split(/\\r\\n\\r\\n|\\n\\n|\\r\\r/);\n frames.forEach(frame => {\n const result = {};\n const lines = frame.split(/\\r\\n|\\n|\\r/);\n lines.forEach(line => {\n if (!is.number(result.startTime)) {\n // The line with start and end times on it is the first line of interest\n 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\n\n if (matchTimes) {\n result.startTime = Number(matchTimes[1] || 0) * 60 * 60 + Number(matchTimes[2]) * 60 + Number(matchTimes[3]) + Number(`0.${matchTimes[4]}`);\n result.endTime = Number(matchTimes[6] || 0) * 60 * 60 + Number(matchTimes[7]) * 60 + Number(matchTimes[8]) + Number(`0.${matchTimes[9]}`);\n }\n } else if (!is.empty(line.trim()) && is.empty(result.text)) {\n // If we already have the startTime, then we're definitely up to the text line(s)\n const lineSplit = line.trim().split('#xywh=');\n [result.text] = lineSplit; // If there's content in lineSplit[1], then we have sprites. If not, then it's just one frame per image\n\n if (lineSplit[1]) {\n [result.x, result.y, result.w, result.h] = lineSplit[1].split(',');\n }\n }\n });\n\n if (result.text) {\n processedList.push(result);\n }\n });\n return processedList;\n };\n /**\n * Preview thumbnails for seek hover and scrubbing\n * Seeking: Hover over the seek bar (desktop only): shows a small preview container above the seek bar\n * 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\n *\n * Notes:\n * - 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\n * - 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\n * - 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\n */\n\n\n const fitRatio = (ratio, outer) => {\n const targetRatio = outer.width / outer.height;\n const result = {};\n\n if (ratio > targetRatio) {\n result.width = outer.width;\n result.height = 1 / ratio * outer.width;\n } else {\n result.height = outer.height;\n result.width = ratio * outer.height;\n }\n\n return result;\n };\n\n class PreviewThumbnails {\n /**\n * PreviewThumbnails constructor.\n * @param {Plyr} player\n * @return {PreviewThumbnails}\n */\n constructor(player) {\n _defineProperty$1(this, \"load\", () => {\n // Toggle the regular seek tooltip\n if (this.player.elements.display.seekTooltip) {\n this.player.elements.display.seekTooltip.hidden = this.enabled;\n }\n\n if (!this.enabled) {\n return;\n }\n\n this.getThumbnails().then(() => {\n if (!this.enabled) {\n return;\n } // Render DOM elements\n\n\n this.render(); // Check to see if thumb container size was specified manually in CSS\n\n this.determineContainerAutoSizing();\n this.loaded = true;\n });\n });\n\n _defineProperty$1(this, \"getThumbnails\", () => {\n return new Promise(resolve => {\n const {\n src\n } = this.player.config.previewThumbnails;\n\n if (is.empty(src)) {\n throw new Error('Missing previewThumbnails.src config attribute');\n } // Resolve promise\n\n\n const sortAndResolve = () => {\n // Sort smallest to biggest (e.g., [120p, 480p, 1080p])\n this.thumbnails.sort((x, y) => x.height - y.height);\n this.player.debug.log('Preview thumbnails', this.thumbnails);\n resolve();\n }; // Via callback()\n\n\n if (is.function(src)) {\n src(thumbnails => {\n this.thumbnails = thumbnails;\n sortAndResolve();\n });\n } // VTT urls\n else {\n // If string, convert into single-element list\n 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\n\n const promises = urls.map(u => this.getThumbnail(u)); // Resolve\n\n Promise.all(promises).then(sortAndResolve);\n }\n });\n });\n\n _defineProperty$1(this, \"getThumbnail\", url => {\n return new Promise(resolve => {\n fetch(url).then(response => {\n const thumbnail = {\n frames: parseVtt(response),\n height: null,\n urlPrefix: ''\n }; // If the URLs don't start with '/', then we need to set their relative path to be the location of the VTT file\n // If the URLs do start with '/', then they obviously don't need a prefix, so it will remain blank\n // If the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file\n\n if (!thumbnail.frames[0].text.startsWith('/') && !thumbnail.frames[0].text.startsWith('http://') && !thumbnail.frames[0].text.startsWith('https://')) {\n thumbnail.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1);\n } // Download the first frame, so that we can determine/set the height of this thumbnailsDef\n\n\n const tempImage = new Image();\n\n tempImage.onload = () => {\n thumbnail.height = tempImage.naturalHeight;\n thumbnail.width = tempImage.naturalWidth;\n this.thumbnails.push(thumbnail);\n resolve();\n };\n\n tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;\n });\n });\n });\n\n _defineProperty$1(this, \"startMove\", event => {\n if (!this.loaded) {\n return;\n }\n\n if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {\n return;\n } // Wait until media has a duration\n\n\n if (!this.player.media.duration) {\n return;\n }\n\n if (event.type === 'touchmove') {\n // Calculate seek hover position as approx video seconds\n this.seekTime = this.player.media.duration * (this.player.elements.inputs.seek.value / 100);\n } else {\n // Calculate seek hover position as approx video seconds\n const clientRect = this.player.elements.progress.getBoundingClientRect();\n const percentage = 100 / clientRect.width * (event.pageX - clientRect.left);\n this.seekTime = this.player.media.duration * (percentage / 100);\n\n if (this.seekTime < 0) {\n // The mousemove fires for 10+px out to the left\n this.seekTime = 0;\n }\n\n if (this.seekTime > this.player.media.duration - 1) {\n // Took 1 second off the duration for safety, because different players can disagree on the real duration of a video\n this.seekTime = this.player.media.duration - 1;\n }\n\n this.mousePosX = event.pageX; // Set time text inside image container\n\n this.elements.thumb.time.innerText = formatTime(this.seekTime);\n } // Download and show image\n\n\n this.showImageAtCurrentTime();\n });\n\n _defineProperty$1(this, \"endMove\", () => {\n this.toggleThumbContainer(false, true);\n });\n\n _defineProperty$1(this, \"startScrubbing\", event => {\n // Only act on left mouse button (0), or touch device (event.button does not exist or is false)\n if (is.nullOrUndefined(event.button) || event.button === false || event.button === 0) {\n this.mouseDown = true; // Wait until media has a duration\n\n if (this.player.media.duration) {\n this.toggleScrubbingContainer(true);\n this.toggleThumbContainer(false, true); // Download and show image\n\n this.showImageAtCurrentTime();\n }\n }\n });\n\n _defineProperty$1(this, \"endScrubbing\", () => {\n this.mouseDown = false; // Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview\n\n if (Math.ceil(this.lastTime) === Math.ceil(this.player.media.currentTime)) {\n // The video was already seeked/loaded at the chosen time - hide immediately\n this.toggleScrubbingContainer(false);\n } else {\n // The video hasn't seeked yet. Wait for that\n once.call(this.player, this.player.media, 'timeupdate', () => {\n // Re-check mousedown - we might have already started scrubbing again\n if (!this.mouseDown) {\n this.toggleScrubbingContainer(false);\n }\n });\n }\n });\n\n _defineProperty$1(this, \"listeners\", () => {\n // 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\n this.player.on('play', () => {\n this.toggleThumbContainer(false, true);\n });\n this.player.on('seeked', () => {\n this.toggleThumbContainer(false);\n });\n this.player.on('timeupdate', () => {\n this.lastTime = this.player.media.currentTime;\n });\n });\n\n _defineProperty$1(this, \"render\", () => {\n // Create HTML element: plyr__preview-thumbnail-container\n this.elements.thumb.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.thumbContainer\n }); // Wrapper for the image for styling\n\n this.elements.thumb.imageContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.imageContainer\n });\n this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer); // Create HTML element, parent+span: time text (e.g., 01:32:00)\n\n const timeContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.timeContainer\n });\n this.elements.thumb.time = createElement('span', {}, '00:00');\n timeContainer.appendChild(this.elements.thumb.time);\n this.elements.thumb.container.appendChild(timeContainer); // Inject the whole thumb\n\n if (is.element(this.player.elements.progress)) {\n this.player.elements.progress.appendChild(this.elements.thumb.container);\n } // Create HTML element: plyr__preview-scrubbing-container\n\n\n this.elements.scrubbing.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.scrubbingContainer\n });\n this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);\n });\n\n _defineProperty$1(this, \"destroy\", () => {\n if (this.elements.thumb.container) {\n this.elements.thumb.container.remove();\n }\n\n if (this.elements.scrubbing.container) {\n this.elements.scrubbing.container.remove();\n }\n });\n\n _defineProperty$1(this, \"showImageAtCurrentTime\", () => {\n if (this.mouseDown) {\n this.setScrubbingContainerSize();\n } else {\n this.setThumbContainerSizeAndPos();\n } // Find the desired thumbnail index\n // TODO: Handle a video longer than the thumbs where thumbNum is null\n\n\n const thumbNum = this.thumbnails[0].frames.findIndex(frame => this.seekTime >= frame.startTime && this.seekTime <= frame.endTime);\n const hasThumb = thumbNum >= 0;\n let qualityIndex = 0; // Show the thumb container if we're not scrubbing\n\n if (!this.mouseDown) {\n this.toggleThumbContainer(hasThumb);\n } // No matching thumb found\n\n\n if (!hasThumb) {\n return;\n } // Check to see if we've already downloaded higher quality versions of this image\n\n\n this.thumbnails.forEach((thumbnail, index) => {\n if (this.loadedImages.includes(thumbnail.frames[thumbNum].text)) {\n qualityIndex = index;\n }\n }); // Only proceed if either thumbnum or thumbfilename has changed\n\n if (thumbNum !== this.showingThumb) {\n this.showingThumb = thumbNum;\n this.loadImage(qualityIndex);\n }\n });\n\n _defineProperty$1(this, \"loadImage\", (qualityIndex = 0) => {\n const thumbNum = this.showingThumb;\n const thumbnail = this.thumbnails[qualityIndex];\n const {\n urlPrefix\n } = thumbnail;\n const frame = thumbnail.frames[thumbNum];\n const thumbFilename = thumbnail.frames[thumbNum].text;\n const thumbUrl = urlPrefix + thumbFilename;\n\n if (!this.currentImageElement || this.currentImageElement.dataset.filename !== thumbFilename) {\n // If we're already loading a previous image, remove its onload handler - we don't want it to load after this one\n // Only do this if not using sprites. Without sprites we really want to show as many images as possible, as a best-effort\n if (this.loadingImage && this.usingSprites) {\n this.loadingImage.onload = null;\n } // We're building and adding a new image. In other implementations of similar functionality (YouTube), background image\n // is instead used. But this causes issues with larger images in Firefox and Safari - switching between background\n // images causes a flicker. Putting a new image over the top does not\n\n\n const previewImage = new Image();\n previewImage.src = thumbUrl;\n previewImage.dataset.index = thumbNum;\n previewImage.dataset.filename = thumbFilename;\n this.showingThumbFilename = thumbFilename;\n 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...\n\n previewImage.onload = () => this.showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, true);\n\n this.loadingImage = previewImage;\n this.removeOldImages(previewImage);\n } else {\n // Update the existing image\n this.showImage(this.currentImageElement, frame, qualityIndex, thumbNum, thumbFilename, false);\n this.currentImageElement.dataset.index = thumbNum;\n this.removeOldImages(this.currentImageElement);\n }\n });\n\n _defineProperty$1(this, \"showImage\", (previewImage, frame, qualityIndex, thumbNum, thumbFilename, newImage = true) => {\n this.player.debug.log(`Showing thumb: ${thumbFilename}. num: ${thumbNum}. qual: ${qualityIndex}. newimg: ${newImage}`);\n this.setImageSizeAndOffset(previewImage, frame);\n\n if (newImage) {\n this.currentImageContainer.appendChild(previewImage);\n this.currentImageElement = previewImage;\n\n if (!this.loadedImages.includes(thumbFilename)) {\n this.loadedImages.push(thumbFilename);\n }\n } // Preload images before and after the current one\n // Show higher quality of the same frame\n // 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\n\n\n this.preloadNearby(thumbNum, true).then(this.preloadNearby(thumbNum, false)).then(this.getHigherQuality(qualityIndex, previewImage, frame, thumbFilename));\n });\n\n _defineProperty$1(this, \"removeOldImages\", currentImage => {\n // Get a list of all images, convert it from a DOM list to an array\n Array.from(this.currentImageContainer.children).forEach(image => {\n if (image.tagName.toLowerCase() !== 'img') {\n return;\n }\n\n const removeDelay = this.usingSprites ? 500 : 1000;\n\n if (image.dataset.index !== currentImage.dataset.index && !image.dataset.deleting) {\n // 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\n // First set attribute 'deleting' to prevent multi-handling of this on repeat firing of this function\n // eslint-disable-next-line no-param-reassign\n image.dataset.deleting = true; // This has to be set before the timeout - to prevent issues switching between hover and scrub\n\n const {\n currentImageContainer\n } = this;\n setTimeout(() => {\n currentImageContainer.removeChild(image);\n this.player.debug.log(`Removing thumb: ${image.dataset.filename}`);\n }, removeDelay);\n }\n });\n });\n\n _defineProperty$1(this, \"preloadNearby\", (thumbNum, forward = true) => {\n return new Promise(resolve => {\n setTimeout(() => {\n const oldThumbFilename = this.thumbnails[0].frames[thumbNum].text;\n\n if (this.showingThumbFilename === oldThumbFilename) {\n // 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\n let thumbnailsClone;\n\n if (forward) {\n thumbnailsClone = this.thumbnails[0].frames.slice(thumbNum);\n } else {\n thumbnailsClone = this.thumbnails[0].frames.slice(0, thumbNum).reverse();\n }\n\n let foundOne = false;\n thumbnailsClone.forEach(frame => {\n const newThumbFilename = frame.text;\n\n if (newThumbFilename !== oldThumbFilename) {\n // Found one with a different filename. Make sure it hasn't already been loaded on this page visit\n if (!this.loadedImages.includes(newThumbFilename)) {\n foundOne = true;\n this.player.debug.log(`Preloading thumb filename: ${newThumbFilename}`);\n const {\n urlPrefix\n } = this.thumbnails[0];\n const thumbURL = urlPrefix + newThumbFilename;\n const previewImage = new Image();\n previewImage.src = thumbURL;\n\n previewImage.onload = () => {\n this.player.debug.log(`Preloaded thumb filename: ${newThumbFilename}`);\n if (!this.loadedImages.includes(newThumbFilename)) this.loadedImages.push(newThumbFilename); // We don't resolve until the thumb is loaded\n\n resolve();\n };\n }\n }\n }); // If there are none to preload then we want to resolve immediately\n\n if (!foundOne) {\n resolve();\n }\n }\n }, 300);\n });\n });\n\n _defineProperty$1(this, \"getHigherQuality\", (currentQualityIndex, previewImage, frame, thumbFilename) => {\n if (currentQualityIndex < this.thumbnails.length - 1) {\n // 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\n let previewImageHeight = previewImage.naturalHeight;\n\n if (this.usingSprites) {\n previewImageHeight = frame.h;\n }\n\n if (previewImageHeight < this.thumbContainerHeight) {\n // Recurse back to the loadImage function - show a higher quality one, but only if the viewer is on this frame for a while\n setTimeout(() => {\n // Make sure the mouse hasn't already moved on and started hovering at another image\n if (this.showingThumbFilename === thumbFilename) {\n this.player.debug.log(`Showing higher quality thumb for: ${thumbFilename}`);\n this.loadImage(currentQualityIndex + 1);\n }\n }, 300);\n }\n }\n });\n\n _defineProperty$1(this, \"toggleThumbContainer\", (toggle = false, clearShowing = false) => {\n const className = this.player.config.classNames.previewThumbnails.thumbContainerShown;\n this.elements.thumb.container.classList.toggle(className, toggle);\n\n if (!toggle && clearShowing) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n });\n\n _defineProperty$1(this, \"toggleScrubbingContainer\", (toggle = false) => {\n const className = this.player.config.classNames.previewThumbnails.scrubbingContainerShown;\n this.elements.scrubbing.container.classList.toggle(className, toggle);\n\n if (!toggle) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n });\n\n _defineProperty$1(this, \"determineContainerAutoSizing\", () => {\n if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) {\n // This will prevent auto sizing in this.setThumbContainerSizeAndPos()\n this.sizeSpecifiedInCSS = true;\n }\n });\n\n _defineProperty$1(this, \"setThumbContainerSizeAndPos\", () => {\n if (!this.sizeSpecifiedInCSS) {\n const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${this.thumbContainerHeight}px`;\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (this.elements.thumb.imageContainer.clientHeight > 20 && this.elements.thumb.imageContainer.clientWidth < 20) {\n const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (this.elements.thumb.imageContainer.clientHeight < 20 && this.elements.thumb.imageContainer.clientWidth > 20) {\n const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`;\n }\n\n this.setThumbContainerPos();\n });\n\n _defineProperty$1(this, \"setThumbContainerPos\", () => {\n const seekbarRect = this.player.elements.progress.getBoundingClientRect();\n const plyrRect = this.player.elements.container.getBoundingClientRect();\n const {\n container\n } = this.elements.thumb; // Find the lowest and highest desired left-position, so we don't slide out the side of the video container\n\n const minVal = plyrRect.left - seekbarRect.left + 10;\n const maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10; // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth\n\n let previewPos = this.mousePosX - seekbarRect.left - container.clientWidth / 2;\n\n if (previewPos < minVal) {\n previewPos = minVal;\n }\n\n if (previewPos > maxVal) {\n previewPos = maxVal;\n }\n\n container.style.left = `${previewPos}px`;\n });\n\n _defineProperty$1(this, \"setScrubbingContainerSize\", () => {\n const {\n width,\n height\n } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight\n });\n this.elements.scrubbing.container.style.width = `${width}px`;\n this.elements.scrubbing.container.style.height = `${height}px`;\n });\n\n _defineProperty$1(this, \"setImageSizeAndOffset\", (previewImage, frame) => {\n if (!this.usingSprites) {\n return;\n } // Find difference between height and preview container height\n\n\n const multiplier = this.thumbContainerHeight / frame.h; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.left = `-${frame.x * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.top = `-${frame.y * multiplier}px`;\n });\n\n this.player = player;\n this.thumbnails = [];\n this.loaded = false;\n this.lastMouseMoveTime = Date.now();\n this.mouseDown = false;\n this.loadedImages = [];\n this.elements = {\n thumb: {},\n scrubbing: {}\n };\n this.load();\n }\n\n get enabled() {\n return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;\n }\n\n get currentImageContainer() {\n if (this.mouseDown) {\n return this.elements.scrubbing.container;\n }\n\n return this.elements.thumb.imageContainer;\n }\n\n get usingSprites() {\n return Object.keys(this.thumbnails[0].frames[0]).includes('w');\n }\n\n get thumbAspectRatio() {\n if (this.usingSprites) {\n return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;\n }\n\n return this.thumbnails[0].width / this.thumbnails[0].height;\n }\n\n get thumbContainerHeight() {\n if (this.mouseDown) {\n const {\n height\n } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight\n });\n return height;\n } // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset)\n\n\n if (this.sizeSpecifiedInCSS) {\n return this.elements.thumb.imageContainer.clientHeight;\n }\n\n return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);\n }\n\n get currentImageElement() {\n if (this.mouseDown) {\n return this.currentScrubbingImageElement;\n }\n\n return this.currentThumbnailImageElement;\n }\n\n set currentImageElement(element) {\n if (this.mouseDown) {\n this.currentScrubbingImageElement = element;\n } else {\n this.currentThumbnailImageElement = element;\n }\n }\n\n }\n\n // ==========================================================================\n const source = {\n // Add elements to HTML5 media (source, tracks, etc)\n insertElements(type, attributes) {\n if (is.string(attributes)) {\n insertElement(type, this.media, {\n src: attributes\n });\n } else if (is.array(attributes)) {\n attributes.forEach(attribute => {\n insertElement(type, this.media, attribute);\n });\n }\n },\n\n // Update source\n // Sources are not checked for support so be careful\n change(input) {\n if (!getDeep(input, 'sources.length')) {\n this.debug.warn('Invalid source format');\n return;\n } // Cancel current network requests\n\n\n html5.cancelRequests.call(this); // Destroy instance and re-setup\n\n this.destroy.call(this, () => {\n // Reset quality options\n this.options.quality = []; // Remove elements\n\n removeElement(this.media);\n this.media = null; // Reset class name\n\n if (is.element(this.elements.container)) {\n this.elements.container.removeAttribute('class');\n } // Set the type and provider\n\n\n const {\n sources,\n type\n } = input;\n const [{\n provider = providers.html5,\n src\n }] = sources;\n const tagName = provider === 'html5' ? type : 'div';\n const attributes = provider === 'html5' ? {} : {\n src\n };\n Object.assign(this, {\n provider,\n type,\n // Check for support\n supported: support.check(type, provider, this.config.playsinline),\n // Create new element\n media: createElement(tagName, attributes)\n }); // Inject the new element\n\n this.elements.container.appendChild(this.media); // Autoplay the new source?\n\n if (is.boolean(input.autoplay)) {\n this.config.autoplay = input.autoplay;\n } // Set attributes for audio and video\n\n\n if (this.isHTML5) {\n if (this.config.crossorigin) {\n this.media.setAttribute('crossorigin', '');\n }\n\n if (this.config.autoplay) {\n this.media.setAttribute('autoplay', '');\n }\n\n if (!is.empty(input.poster)) {\n this.poster = input.poster;\n }\n\n if (this.config.loop.active) {\n this.media.setAttribute('loop', '');\n }\n\n if (this.config.muted) {\n this.media.setAttribute('muted', '');\n }\n\n if (this.config.playsinline) {\n this.media.setAttribute('playsinline', '');\n }\n } // Restore class hook\n\n\n ui.addStyleHook.call(this); // Set new sources for html5\n\n if (this.isHTML5) {\n source.insertElements.call(this, 'source', sources);\n } // Set video title\n\n\n this.config.title = input.title; // Set up from scratch\n\n media.setup.call(this); // HTML5 stuff\n\n if (this.isHTML5) {\n // Setup captions\n if (Object.keys(input).includes('tracks')) {\n source.insertElements.call(this, 'track', input.tracks);\n }\n } // If HTML5 or embed but not fully supported, setupInterface and call ready now\n\n\n if (this.isHTML5 || this.isEmbed && !this.supported.ui) {\n // Setup interface\n ui.build.call(this);\n } // Load HTML5 sources\n\n\n if (this.isHTML5) {\n this.media.load();\n } // Update previewThumbnails config & reload plugin\n\n\n if (!is.empty(input.previewThumbnails)) {\n Object.assign(this.config.previewThumbnails, input.previewThumbnails); // Cleanup previewThumbnails plugin if it was loaded\n\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n } // Create new instance if it is still enabled\n\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n } // Update the fullscreen support\n\n\n this.fullscreen.update();\n }, true);\n }\n\n };\n\n /**\n * Returns a number whose value is limited to the given range.\n *\n * Example: limit the output of this computation to between 0 and 255\n * (x * 255).clamp(0, 255)\n *\n * @param {Number} input\n * @param {Number} min The lower boundary of the output range\n * @param {Number} max The upper boundary of the output range\n * @returns A number in the range [min, max]\n * @type Number\n */\n function clamp(input = 0, min = 0, max = 255) {\n return Math.min(Math.max(input, min), max);\n }\n\n // TODO: Use a WeakMap for private globals\n // const globals = new WeakMap();\n // Plyr instance\n\n class Plyr {\n constructor(target, options) {\n _defineProperty$1(this, \"play\", () => {\n if (!is.function(this.media.play)) {\n return null;\n } // Intecept play with ads\n\n\n if (this.ads && this.ads.enabled) {\n this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play()));\n } // Return the promise (for HTML5)\n\n\n return this.media.play();\n });\n\n _defineProperty$1(this, \"pause\", () => {\n if (!this.playing || !is.function(this.media.pause)) {\n return null;\n }\n\n return this.media.pause();\n });\n\n _defineProperty$1(this, \"togglePlay\", input => {\n // Toggle based on current state if nothing passed\n const toggle = is.boolean(input) ? input : !this.playing;\n\n if (toggle) {\n return this.play();\n }\n\n return this.pause();\n });\n\n _defineProperty$1(this, \"stop\", () => {\n if (this.isHTML5) {\n this.pause();\n this.restart();\n } else if (is.function(this.media.stop)) {\n this.media.stop();\n }\n });\n\n _defineProperty$1(this, \"restart\", () => {\n this.currentTime = 0;\n });\n\n _defineProperty$1(this, \"rewind\", seekTime => {\n this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime;\n });\n\n _defineProperty$1(this, \"forward\", seekTime => {\n this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime;\n });\n\n _defineProperty$1(this, \"increaseVolume\", step => {\n const volume = this.media.muted ? 0 : this.volume;\n this.volume = volume + (is.number(step) ? step : 0);\n });\n\n _defineProperty$1(this, \"decreaseVolume\", step => {\n this.increaseVolume(-step);\n });\n\n _defineProperty$1(this, \"airplay\", () => {\n // Show dialog if supported\n if (support.airplay) {\n this.media.webkitShowPlaybackTargetPicker();\n }\n });\n\n _defineProperty$1(this, \"toggleControls\", toggle => {\n // Don't toggle if missing UI support or if it's audio\n if (this.supported.ui && !this.isAudio) {\n // Get state before change\n const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls); // Negate the argument if not undefined since adding the class to hides the controls\n\n const force = typeof toggle === 'undefined' ? undefined : !toggle; // Apply and get updated state\n\n const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force); // Close menu\n\n if (hiding && is.array(this.config.controls) && this.config.controls.includes('settings') && !is.empty(this.config.settings)) {\n controls.toggleMenu.call(this, false);\n } // Trigger event on change\n\n\n if (hiding !== isHidden) {\n const eventName = hiding ? 'controlshidden' : 'controlsshown';\n triggerEvent.call(this, this.media, eventName);\n }\n\n return !hiding;\n }\n\n return false;\n });\n\n _defineProperty$1(this, \"on\", (event, callback) => {\n on.call(this, this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"once\", (event, callback) => {\n once.call(this, this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"off\", (event, callback) => {\n off(this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"destroy\", (callback, soft = false) => {\n if (!this.ready) {\n return;\n }\n\n const done = () => {\n // Reset overflow (incase destroyed while in fullscreen)\n document.body.style.overflow = ''; // GC for embed\n\n this.embed = null; // If it's a soft destroy, make minimal changes\n\n if (soft) {\n if (Object.keys(this.elements).length) {\n // Remove elements\n removeElement(this.elements.buttons.play);\n removeElement(this.elements.captions);\n removeElement(this.elements.controls);\n removeElement(this.elements.wrapper); // Clear for GC\n\n this.elements.buttons.play = null;\n this.elements.captions = null;\n this.elements.controls = null;\n this.elements.wrapper = null;\n } // Callback\n\n\n if (is.function(callback)) {\n callback();\n }\n } else {\n // Unbind listeners\n unbindListeners.call(this); // Cancel current network requests\n\n html5.cancelRequests.call(this); // Replace the container with the original element provided\n\n replaceElement(this.elements.original, this.elements.container); // Event\n\n triggerEvent.call(this, this.elements.original, 'destroyed', true); // Callback\n\n if (is.function(callback)) {\n callback.call(this.elements.original);\n } // Reset state\n\n\n this.ready = false; // Clear for garbage collection\n\n setTimeout(() => {\n this.elements = null;\n this.media = null;\n }, 200);\n }\n }; // Stop playback\n\n\n this.stop(); // Clear timeouts\n\n clearTimeout(this.timers.loading);\n clearTimeout(this.timers.controls);\n clearTimeout(this.timers.resized); // Provider specific stuff\n\n if (this.isHTML5) {\n // Restore native video controls\n ui.toggleNativeControls.call(this, true); // Clean up\n\n done();\n } else if (this.isYouTube) {\n // Clear timers\n clearInterval(this.timers.buffering);\n clearInterval(this.timers.playing); // Destroy YouTube API\n\n if (this.embed !== null && is.function(this.embed.destroy)) {\n this.embed.destroy();\n } // Clean up\n\n\n done();\n } else if (this.isVimeo) {\n // Destroy Vimeo API\n // then clean up (wait, to prevent postmessage errors)\n if (this.embed !== null) {\n this.embed.unload().then(done);\n } // Vimeo does not always return\n\n\n setTimeout(done, 200);\n }\n });\n\n _defineProperty$1(this, \"supports\", type => support.mime.call(this, type));\n\n this.timers = {}; // State\n\n this.ready = false;\n this.loading = false;\n this.failed = false; // Touch device\n\n this.touch = support.touch; // Set the media element\n\n this.media = target; // String selector passed\n\n if (is.string(this.media)) {\n this.media = document.querySelectorAll(this.media);\n } // jQuery, NodeList or Array passed, use first element\n\n\n if (window.jQuery && this.media instanceof jQuery || is.nodeList(this.media) || is.array(this.media)) {\n // eslint-disable-next-line\n this.media = this.media[0];\n } // Set config\n\n\n this.config = extend({}, defaults, Plyr.defaults, options || {}, (() => {\n try {\n return JSON.parse(this.media.getAttribute('data-plyr-config'));\n } catch (_) {\n return {};\n }\n })()); // Elements cache\n\n this.elements = {\n container: null,\n fullscreen: null,\n captions: null,\n buttons: {},\n display: {},\n progress: {},\n inputs: {},\n settings: {\n popup: null,\n menu: null,\n panels: {},\n buttons: {}\n }\n }; // Captions\n\n this.captions = {\n active: null,\n currentTrack: -1,\n meta: new WeakMap()\n }; // Fullscreen\n\n this.fullscreen = {\n active: false\n }; // Options\n\n this.options = {\n speed: [],\n quality: []\n }; // Debugging\n // TODO: move to globals\n\n this.debug = new Console(this.config.debug); // Log config options and support\n\n this.debug.log('Config', this.config);\n this.debug.log('Support', support); // We need an element to setup\n\n if (is.nullOrUndefined(this.media) || !is.element(this.media)) {\n this.debug.error('Setup failed: no suitable element passed');\n return;\n } // Bail if the element is initialized\n\n\n if (this.media.plyr) {\n this.debug.warn('Target already setup');\n return;\n } // Bail if not enabled\n\n\n if (!this.config.enabled) {\n this.debug.error('Setup failed: disabled by config');\n return;\n } // Bail if disabled or no basic support\n // You may want to disable certain UAs etc\n\n\n if (!support.check().api) {\n this.debug.error('Setup failed: no support');\n return;\n } // Cache original element state for .destroy()\n\n\n const clone = this.media.cloneNode(true);\n clone.autoplay = false;\n this.elements.original = clone; // Set media type based on tag or data attribute\n // Supported: video, audio, vimeo, youtube\n\n const _type = this.media.tagName.toLowerCase(); // Embed properties\n\n\n let iframe = null;\n let url = null; // Different setup based on type\n\n switch (_type) {\n case 'div':\n // Find the frame\n iframe = this.media.querySelector('iframe'); // <iframe> type\n\n if (is.element(iframe)) {\n // Detect provider\n url = parseUrl(iframe.getAttribute('src'));\n this.provider = getProviderByUrl(url.toString()); // Rework elements\n\n this.elements.container = this.media;\n this.media = iframe; // Reset classname\n\n this.elements.container.className = ''; // Get attributes from URL and set config\n\n if (url.search.length) {\n const truthy = ['1', 'true'];\n\n if (truthy.includes(url.searchParams.get('autoplay'))) {\n this.config.autoplay = true;\n }\n\n if (truthy.includes(url.searchParams.get('loop'))) {\n this.config.loop.active = true;\n } // TODO: replace fullscreen.iosNative with this playsinline config option\n // YouTube requires the playsinline in the URL\n\n\n if (this.isYouTube) {\n this.config.playsinline = truthy.includes(url.searchParams.get('playsinline'));\n this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language?\n } else {\n this.config.playsinline = true;\n }\n }\n } else {\n // <div> with attributes\n this.provider = this.media.getAttribute(this.config.attributes.embed.provider); // Remove attribute\n\n this.media.removeAttribute(this.config.attributes.embed.provider);\n } // Unsupported or missing provider\n\n\n if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) {\n this.debug.error('Setup failed: Invalid provider');\n return;\n } // Audio will come later for external providers\n\n\n this.type = types.video;\n break;\n\n case 'video':\n case 'audio':\n this.type = _type;\n this.provider = providers.html5; // Get config from attributes\n\n if (this.media.hasAttribute('crossorigin')) {\n this.config.crossorigin = true;\n }\n\n if (this.media.hasAttribute('autoplay')) {\n this.config.autoplay = true;\n }\n\n if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) {\n this.config.playsinline = true;\n }\n\n if (this.media.hasAttribute('muted')) {\n this.config.muted = true;\n }\n\n if (this.media.hasAttribute('loop')) {\n this.config.loop.active = true;\n }\n\n break;\n\n default:\n this.debug.error('Setup failed: unsupported type');\n return;\n } // Check for support again but with type\n\n\n this.supported = support.check(this.type, this.provider, this.config.playsinline); // If no support for even API, bail\n\n if (!this.supported.api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n this.eventListeners = []; // Create listeners\n\n this.listeners = new Listeners(this); // Setup local storage for user settings\n\n this.storage = new Storage(this); // Store reference\n\n this.media.plyr = this; // Wrap media\n\n if (!is.element(this.elements.container)) {\n this.elements.container = createElement('div', {\n tabindex: 0\n });\n wrap(this.media, this.elements.container);\n } // Migrate custom properties from media to container (so they work 😉)\n\n\n ui.migrateStyles.call(this); // Add style hook\n\n ui.addStyleHook.call(this); // Setup media\n\n media.setup.call(this); // Listen for events if debugging\n\n if (this.config.debug) {\n on.call(this, this.elements.container, this.config.events.join(' '), event => {\n this.debug.log(`event: ${event.type}`);\n });\n } // Setup fullscreen\n\n\n this.fullscreen = new Fullscreen(this); // Setup interface\n // If embed but not fully supported, build interface now to avoid flash of controls\n\n if (this.isHTML5 || this.isEmbed && !this.supported.ui) {\n ui.build.call(this);\n } // Container listeners\n\n\n this.listeners.container(); // Global listeners\n\n this.listeners.global(); // Setup ads if provided\n\n if (this.config.ads.enabled) {\n this.ads = new Ads(this);\n } // Autoplay if required\n\n\n if (this.isHTML5 && this.config.autoplay) {\n this.once('canplay', () => silencePromise(this.play()));\n } // Seek time will be recorded (in listeners.js) so we can prevent hiding controls for a few seconds after seek\n\n\n this.lastSeekTime = 0; // Setup preview thumbnails if enabled\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n } // ---------------------------------------\n // API\n // ---------------------------------------\n\n /**\n * Types and provider helpers\n */\n\n\n get isHTML5() {\n return this.provider === providers.html5;\n }\n\n get isEmbed() {\n return this.isYouTube || this.isVimeo;\n }\n\n get isYouTube() {\n return this.provider === providers.youtube;\n }\n\n get isVimeo() {\n return this.provider === providers.vimeo;\n }\n\n get isVideo() {\n return this.type === types.video;\n }\n\n get isAudio() {\n return this.type === types.audio;\n }\n /**\n * Play the media, or play the advertisement (if they are not blocked)\n */\n\n\n /**\n * Get playing state\n */\n get playing() {\n return Boolean(this.ready && !this.paused && !this.ended);\n }\n /**\n * Get paused state\n */\n\n\n get paused() {\n return Boolean(this.media.paused);\n }\n /**\n * Get stopped state\n */\n\n\n get stopped() {\n return Boolean(this.paused && this.currentTime === 0);\n }\n /**\n * Get ended state\n */\n\n\n get ended() {\n return Boolean(this.media.ended);\n }\n /**\n * Toggle playback based on current status\n * @param {Boolean} input\n */\n\n\n /**\n * Seek to a time\n * @param {Number} input - where to seek to in seconds. Defaults to 0 (the start)\n */\n set currentTime(input) {\n // Bail if media duration isn't available yet\n if (!this.duration) {\n return;\n } // Validate input\n\n\n const inputIsValid = is.number(input) && input > 0; // Set\n\n this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0; // Logging\n\n this.debug.log(`Seeking to ${this.currentTime} seconds`);\n }\n /**\n * Get current time\n */\n\n\n get currentTime() {\n return Number(this.media.currentTime);\n }\n /**\n * Get buffered\n */\n\n\n get buffered() {\n const {\n buffered\n } = this.media; // YouTube / Vimeo return a float between 0-1\n\n if (is.number(buffered)) {\n return buffered;\n } // HTML5\n // TODO: Handle buffered chunks of the media\n // (i.e. seek to another section buffers only that section)\n\n\n if (buffered && buffered.length && this.duration > 0) {\n return buffered.end(0) / this.duration;\n }\n\n return 0;\n }\n /**\n * Get seeking status\n */\n\n\n get seeking() {\n return Boolean(this.media.seeking);\n }\n /**\n * Get the duration of the current media\n */\n\n\n get duration() {\n // Faux duration set via config\n const fauxDuration = parseFloat(this.config.duration); // Media duration can be NaN or Infinity before the media has loaded\n\n const realDuration = (this.media || {}).duration;\n const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration; // If config duration is funky, use regular duration\n\n return fauxDuration || duration;\n }\n /**\n * Set the player volume\n * @param {Number} value - must be between 0 and 1. Defaults to the value from local storage and config.volume if not set in storage\n */\n\n\n set volume(value) {\n let volume = value;\n const max = 1;\n const min = 0;\n\n if (is.string(volume)) {\n volume = Number(volume);\n } // Load volume from storage if no value specified\n\n\n if (!is.number(volume)) {\n volume = this.storage.get('volume');\n } // Use config if all else fails\n\n\n if (!is.number(volume)) {\n ({\n volume\n } = this.config);\n } // Maximum is volumeMax\n\n\n if (volume > max) {\n volume = max;\n } // Minimum is volumeMin\n\n\n if (volume < min) {\n volume = min;\n } // Update config\n\n\n this.config.volume = volume; // Set the player volume\n\n this.media.volume = volume; // If muted, and we're increasing volume manually, reset muted state\n\n if (!is.empty(value) && this.muted && volume > 0) {\n this.muted = false;\n }\n }\n /**\n * Get the current player volume\n */\n\n\n get volume() {\n return Number(this.media.volume);\n }\n /**\n * Increase volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n\n\n /**\n * Set muted state\n * @param {Boolean} mute\n */\n set muted(mute) {\n let toggle = mute; // Load muted state from storage\n\n if (!is.boolean(toggle)) {\n toggle = this.storage.get('muted');\n } // Use config if all else fails\n\n\n if (!is.boolean(toggle)) {\n toggle = this.config.muted;\n } // Update config\n\n\n this.config.muted = toggle; // Set mute on the player\n\n this.media.muted = toggle;\n }\n /**\n * Get current muted state\n */\n\n\n get muted() {\n return Boolean(this.media.muted);\n }\n /**\n * Check if the media has audio\n */\n\n\n get hasAudio() {\n // Assume yes for all non HTML5 (as we can't tell...)\n if (!this.isHTML5) {\n return true;\n }\n\n if (this.isAudio) {\n return true;\n } // Get audio tracks\n\n\n return Boolean(this.media.mozHasAudio) || Boolean(this.media.webkitAudioDecodedByteCount) || Boolean(this.media.audioTracks && this.media.audioTracks.length);\n }\n /**\n * Set playback speed\n * @param {Number} speed - the speed of playback (0.5-2.0)\n */\n\n\n set speed(input) {\n let speed = null;\n\n if (is.number(input)) {\n speed = input;\n }\n\n if (!is.number(speed)) {\n speed = this.storage.get('speed');\n }\n\n if (!is.number(speed)) {\n speed = this.config.speed.selected;\n } // Clamp to min/max\n\n\n const {\n minimumSpeed: min,\n maximumSpeed: max\n } = this;\n speed = clamp(speed, min, max); // Update config\n\n this.config.speed.selected = speed; // Set media speed\n\n setTimeout(() => {\n if (this.media) {\n this.media.playbackRate = speed;\n }\n }, 0);\n }\n /**\n * Get current playback speed\n */\n\n\n get speed() {\n return Number(this.media.playbackRate);\n }\n /**\n * Get the minimum allowed speed\n */\n\n\n get minimumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.min(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 0.5;\n } // https://stackoverflow.com/a/32320020/1191319\n\n\n return 0.0625;\n }\n /**\n * Get the maximum allowed speed\n */\n\n\n get maximumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.max(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 2;\n } // https://stackoverflow.com/a/32320020/1191319\n\n\n return 16;\n }\n /**\n * Set playback quality\n * Currently HTML5 & YouTube only\n * @param {Number} input - Quality level\n */\n\n\n set quality(input) {\n const config = this.config.quality;\n const options = this.options.quality;\n\n if (!options.length) {\n return;\n }\n\n let quality = [!is.empty(input) && Number(input), this.storage.get('quality'), config.selected, config.default].find(is.number);\n let updateStorage = true;\n\n if (!options.includes(quality)) {\n const value = closest(options, quality);\n this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`);\n quality = value; // Don't update storage if quality is not supported\n\n updateStorage = false;\n } // Update config\n\n\n config.selected = quality; // Set quality\n\n this.media.quality = quality; // Save to storage\n\n if (updateStorage) {\n this.storage.set({\n quality\n });\n }\n }\n /**\n * Get current quality level\n */\n\n\n get quality() {\n return this.media.quality;\n }\n /**\n * Toggle loop\n * TODO: Finish fancy new logic. Set the indicator on load as user may pass loop as config\n * @param {Boolean} input - Whether to loop or not\n */\n\n\n set loop(input) {\n const toggle = is.boolean(input) ? input : this.config.loop.active;\n this.config.loop.active = toggle;\n this.media.loop = toggle; // Set default to be a true toggle\n\n /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle';\n switch (type) {\n case 'start':\n if (this.config.loop.end && this.config.loop.end <= this.currentTime) {\n this.config.loop.end = null;\n }\n this.config.loop.start = this.currentTime;\n // this.config.loop.indicator.start = this.elements.display.played.value;\n break;\n case 'end':\n if (this.config.loop.start >= this.currentTime) {\n return this;\n }\n this.config.loop.end = this.currentTime;\n // this.config.loop.indicator.end = this.elements.display.played.value;\n break;\n case 'all':\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n this.config.loop.indicator.start = 0;\n this.config.loop.indicator.end = 100;\n break;\n case 'toggle':\n if (this.config.loop.active) {\n this.config.loop.start = 0;\n this.config.loop.end = null;\n } else {\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n }\n break;\n default:\n this.config.loop.start = 0;\n this.config.loop.end = null;\n break;\n } */\n }\n /**\n * Get current loop state\n */\n\n\n get loop() {\n return Boolean(this.media.loop);\n }\n /**\n * Set new media source\n * @param {Object} input - The new source object (see docs)\n */\n\n\n set source(input) {\n source.change.call(this, input);\n }\n /**\n * Get current source\n */\n\n\n get source() {\n return this.media.currentSrc;\n }\n /**\n * Get a download URL (either source or custom)\n */\n\n\n get download() {\n const {\n download\n } = this.config.urls;\n return is.url(download) ? download : this.source;\n }\n /**\n * Set the download URL\n */\n\n\n set download(input) {\n if (!is.url(input)) {\n return;\n }\n\n this.config.urls.download = input;\n controls.setDownloadUrl.call(this);\n }\n /**\n * Set the poster image for a video\n * @param {String} input - the URL for the new poster image\n */\n\n\n set poster(input) {\n if (!this.isVideo) {\n this.debug.warn('Poster can only be set for video');\n return;\n }\n\n ui.setPoster.call(this, input, false).catch(() => {});\n }\n /**\n * Get the current poster image\n */\n\n\n get poster() {\n if (!this.isVideo) {\n return null;\n }\n\n return this.media.getAttribute('poster') || this.media.getAttribute('data-poster');\n }\n /**\n * Get the current aspect ratio in use\n */\n\n\n get ratio() {\n if (!this.isVideo) {\n return null;\n }\n\n const ratio = reduceAspectRatio(getAspectRatio.call(this));\n return is.array(ratio) ? ratio.join(':') : ratio;\n }\n /**\n * Set video aspect ratio\n */\n\n\n set ratio(input) {\n if (!this.isVideo) {\n this.debug.warn('Aspect ratio can only be set for video');\n return;\n }\n\n if (!is.string(input) || !validateAspectRatio(input)) {\n this.debug.error(`Invalid aspect ratio specified (${input})`);\n return;\n }\n\n this.config.ratio = reduceAspectRatio(input);\n setAspectRatio.call(this);\n }\n /**\n * Set the autoplay state\n * @param {Boolean} input - Whether to autoplay or not\n */\n\n\n set autoplay(input) {\n const toggle = is.boolean(input) ? input : this.config.autoplay;\n this.config.autoplay = toggle;\n }\n /**\n * Get the current autoplay state\n */\n\n\n get autoplay() {\n return Boolean(this.config.autoplay);\n }\n /**\n * Toggle captions\n * @param {Boolean} input - Whether to enable captions\n */\n\n\n toggleCaptions(input) {\n captions.toggle.call(this, input, false);\n }\n /**\n * Set the caption track by index\n * @param {Number} - Caption index\n */\n\n\n set currentTrack(input) {\n captions.set.call(this, input, false);\n captions.setup();\n }\n /**\n * Get the current caption track index (-1 if disabled)\n */\n\n\n get currentTrack() {\n const {\n toggled,\n currentTrack\n } = this.captions;\n return toggled ? currentTrack : -1;\n }\n /**\n * Set the wanted language for captions\n * Since tracks can be added later it won't update the actual caption track until there is a matching track\n * @param {String} - Two character ISO language code (e.g. EN, FR, PT, etc)\n */\n\n\n set language(input) {\n captions.setLanguage.call(this, input, false);\n }\n /**\n * Get the current track's language\n */\n\n\n get language() {\n return (captions.getCurrentTrack.call(this) || {}).language;\n }\n /**\n * Toggle picture-in-picture playback on WebKit/MacOS\n * TODO: update player with state, support, enabled\n * TODO: detect outside changes\n */\n\n\n set pip(input) {\n // Bail if no support\n if (!support.pip) {\n return;\n } // Toggle based on current state if not passed\n\n\n const toggle = is.boolean(input) ? input : !this.pip; // Toggle based on current state\n // Safari\n\n if (is.function(this.media.webkitSetPresentationMode)) {\n this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive);\n } // Chrome\n\n\n if (is.function(this.media.requestPictureInPicture)) {\n if (!this.pip && toggle) {\n this.media.requestPictureInPicture();\n } else if (this.pip && !toggle) {\n document.exitPictureInPicture();\n }\n }\n }\n /**\n * Get the current picture-in-picture state\n */\n\n\n get pip() {\n if (!support.pip) {\n return null;\n } // Safari\n\n\n if (!is.empty(this.media.webkitPresentationMode)) {\n return this.media.webkitPresentationMode === pip.active;\n } // Chrome\n\n\n return this.media === document.pictureInPictureElement;\n }\n /**\n * Sets the preview thubmnails for the current source\n */\n\n\n setPreviewThumbnails(thumbnailSource) {\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n Object.assign(this.config.previewThumbnails, thumbnailSource); // Create new instance if it is still enabled\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n /**\n * Trigger the airplay dialog\n * TODO: update player with state, support, enabled\n */\n\n\n /**\n * Check for support\n * @param {String} type - Player type (audio/video)\n * @param {String} provider - Provider (html5/youtube/vimeo)\n * @param {Boolean} inline - Where player has `playsinline` sttribute\n */\n static supported(type, provider, inline) {\n return support.check(type, provider, inline);\n }\n /**\n * Load an SVG sprite into the page\n * @param {String} url - URL for the SVG sprite\n * @param {String} [id] - Unique ID\n */\n\n\n static loadSprite(url, id) {\n return loadSprite(url, id);\n }\n /**\n * Setup multiple instances\n * @param {*} selector\n * @param {Object} options\n */\n\n\n static setup(selector, options = {}) {\n let targets = null;\n\n if (is.string(selector)) {\n targets = Array.from(document.querySelectorAll(selector));\n } else if (is.nodeList(selector)) {\n targets = Array.from(selector);\n } else if (is.array(selector)) {\n targets = selector.filter(is.element);\n }\n\n if (is.empty(targets)) {\n return null;\n }\n\n return targets.map(t => new Plyr(t, options));\n }\n\n }\n\n Plyr.defaults = cloneDeep(defaults);\n\n return Plyr;\n\n}));\n","function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var defaults={addCSS:!0,thumbWidth:15,watch:!0};function matches(e,t){return function(){return Array.from(document.querySelectorAll(t)).includes(this)}.call(e,t)}function trigger(e,t){if(e&&t){var n=new Event(t,{bubbles:!0});e.dispatchEvent(n)}}var getConstructor=function(e){return null!=e?e.constructor:null},instanceOf=function(e,t){return!!(e&&t&&e instanceof t)},isNullOrUndefined=function(e){return null==e},isObject=function(e){return getConstructor(e)===Object},isNumber=function(e){return getConstructor(e)===Number&&!Number.isNaN(e)},isString=function(e){return getConstructor(e)===String},isBoolean=function(e){return getConstructor(e)===Boolean},isFunction=function(e){return getConstructor(e)===Function},isArray=function(e){return Array.isArray(e)},isNodeList=function(e){return instanceOf(e,NodeList)},isElement=function(e){return instanceOf(e,Element)},isEvent=function(e){return instanceOf(e,Event)},isEmpty=function(e){return isNullOrUndefined(e)||(isString(e)||isArray(e)||isNodeList(e))&&!e.length||isObject(e)&&!Object.keys(e).length},is={nullOrUndefined:isNullOrUndefined,object:isObject,number:isNumber,string:isString,boolean:isBoolean,function:isFunction,array:isArray,nodeList:isNodeList,element:isElement,event:isEvent,empty:isEmpty};function getDecimalPlaces(e){var t=\"\".concat(e).match(/(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0}function round(e,t){if(1>t){var n=getDecimalPlaces(t);return parseFloat(e.toFixed(n))}return Math.round(e/t)*t}var RangeTouch=function(){function e(t,n){_classCallCheck(this,e),is.element(t)?this.element=t:is.string(t)&&(this.element=document.querySelector(t)),is.element(this.element)&&is.empty(this.element.rangeTouch)&&(this.config=_objectSpread2({},defaults,{},n),this.init())}return _createClass(e,[{key:\"init\",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect=\"none\",this.element.style.webKitUserSelect=\"none\",this.element.style.touchAction=\"manipulation\"),this.listeners(!0),this.element.rangeTouch=this)}},{key:\"destroy\",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect=\"\",this.element.style.webKitUserSelect=\"\",this.element.style.touchAction=\"\"),this.listeners(!1),this.element.rangeTouch=null)}},{key:\"listeners\",value:function(e){var t=this,n=e?\"addEventListener\":\"removeEventListener\";[\"touchstart\",\"touchmove\",\"touchend\"].forEach((function(e){t.element[n](e,(function(e){return t.set(e)}),!1)}))}},{key:\"get\",value:function(t){if(!e.enabled||!is.event(t))return null;var n,r=t.target,i=t.changedTouches[0],o=parseFloat(r.getAttribute(\"min\"))||0,s=parseFloat(r.getAttribute(\"max\"))||100,u=parseFloat(r.getAttribute(\"step\"))||1,c=r.getBoundingClientRect(),a=100/c.width*(this.config.thumbWidth/2)/100;return 0>(n=100/c.width*(i.clientX-c.left))?n=0:100<n&&(n=100),50>n?n-=(100-2*n)*a:50<n&&(n+=2*(n-50)*a),o+round(n/100*(s-o),u)}},{key:\"set\",value:function(t){e.enabled&&is.event(t)&&!t.target.disabled&&(t.preventDefault(),t.target.value=this.get(t),trigger(t.target,\"touchend\"===t.type?\"change\":\"input\"))}}],[{key:\"setup\",value:function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r=null;if(is.empty(t)||is.string(t)?r=Array.from(document.querySelectorAll(is.string(t)?t:'input[type=\"range\"]')):is.element(t)?r=[t]:is.nodeList(t)?r=Array.from(t):is.array(t)&&(r=t.filter(is.element)),is.empty(r))return null;var i=_objectSpread2({},defaults,{},n);if(is.string(t)&&i.watch){var o=new MutationObserver((function(n){Array.from(n).forEach((function(n){Array.from(n.addedNodes).forEach((function(n){is.element(n)&&matches(n,t)&&new e(n,i)}))}))}));o.observe(document.body,{childList:!0,subtree:!0})}return r.map((function(t){return new e(t,n)}))}},{key:\"enabled\",get:function(){return\"ontouchstart\"in document.documentElement}}]),e}();export default RangeTouch;","// ==========================================================================\n// Type checking utils\n// ==========================================================================\n\nconst getConstructor = (input) => (input !== null && typeof input !== 'undefined' ? input.constructor : null);\nconst instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor);\nconst isNullOrUndefined = (input) => input === null || typeof input === 'undefined';\nconst isObject = (input) => getConstructor(input) === Object;\nconst isNumber = (input) => getConstructor(input) === Number && !Number.isNaN(input);\nconst isString = (input) => getConstructor(input) === String;\nconst isBoolean = (input) => getConstructor(input) === Boolean;\nconst isFunction = (input) => getConstructor(input) === Function;\nconst isArray = (input) => Array.isArray(input);\nconst isWeakMap = (input) => instanceOf(input, WeakMap);\nconst isNodeList = (input) => instanceOf(input, NodeList);\nconst isTextNode = (input) => getConstructor(input) === Text;\nconst isEvent = (input) => instanceOf(input, Event);\nconst isKeyboardEvent = (input) => instanceOf(input, KeyboardEvent);\nconst isCue = (input) => instanceOf(input, window.TextTrackCue) || instanceOf(input, window.VTTCue);\nconst isTrack = (input) => instanceOf(input, TextTrack) || (!isNullOrUndefined(input) && isString(input.kind));\nconst isPromise = (input) => instanceOf(input, Promise) && isFunction(input.then);\n\nconst isElement = (input) =>\n input !== null &&\n typeof input === 'object' &&\n input.nodeType === 1 &&\n typeof input.style === 'object' &&\n typeof input.ownerDocument === 'object';\n\nconst isEmpty = (input) =>\n isNullOrUndefined(input) ||\n ((isString(input) || isArray(input) || isNodeList(input)) && !input.length) ||\n (isObject(input) && !Object.keys(input).length);\n\nconst isUrl = (input) => {\n // Accept a URL object\n if (instanceOf(input, window.URL)) {\n return true;\n }\n\n // Must be string from here\n if (!isString(input)) {\n return false;\n }\n\n // Add the protocol if required\n let string = input;\n if (!input.startsWith('http://') || !input.startsWith('https://')) {\n string = `http://${input}`;\n }\n\n try {\n return !isEmpty(new URL(string).hostname);\n } catch (_) {\n return false;\n }\n};\n\nexport default {\n nullOrUndefined: isNullOrUndefined,\n object: isObject,\n number: isNumber,\n string: isString,\n boolean: isBoolean,\n function: isFunction,\n array: isArray,\n weakMap: isWeakMap,\n nodeList: isNodeList,\n element: isElement,\n textNode: isTextNode,\n event: isEvent,\n keyboardEvent: isKeyboardEvent,\n cue: isCue,\n track: isTrack,\n promise: isPromise,\n url: isUrl,\n empty: isEmpty,\n};\n","// ==========================================================================\n// Animation utils\n// ==========================================================================\n\nimport is from './is';\n\nexport const transitionEndEvent = (() => {\n const element = document.createElement('span');\n\n const events = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend',\n };\n\n const type = Object.keys(events).find((event) => element.style[event] !== undefined);\n\n return is.string(type) ? events[type] : false;\n})();\n\n// Force repaint of element\nexport function repaint(element, delay) {\n setTimeout(() => {\n try {\n // eslint-disable-next-line no-param-reassign\n element.hidden = true;\n\n // eslint-disable-next-line no-unused-expressions\n element.offsetHeight;\n\n // eslint-disable-next-line no-param-reassign\n element.hidden = false;\n } catch (_) {\n // Do nothing\n }\n }, delay);\n}\n","// ==========================================================================\n// Browser sniffing\n// Unfortunately, due to mixed support, UA sniffing is required\n// ==========================================================================\n\nconst browser = {\n isIE: Boolean(window.document.documentMode),\n isEdge: window.navigator.userAgent.includes('Edge'),\n isWebkit: 'WebkitAppearance' in document.documentElement.style && !/Edge/.test(navigator.userAgent),\n isIPhone: /(iPhone|iPod)/gi.test(navigator.platform),\n isIos:\n (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) ||\n /(iPad|iPhone|iPod)/gi.test(navigator.platform),\n};\n\nexport default browser;\n","// ==========================================================================\n// Object utils\n// ==========================================================================\n\nimport is from './is';\n\n// Clone nested objects\nexport function cloneDeep(object) {\n return JSON.parse(JSON.stringify(object));\n}\n\n// Get a nested value in an object\nexport function getDeep(object, path) {\n return path.split('.').reduce((obj, key) => obj && obj[key], object);\n}\n\n// Deep extend destination object with N more objects\nexport function extend(target = {}, ...sources) {\n if (!sources.length) {\n return target;\n }\n\n const source = sources.shift();\n\n if (!is.object(source)) {\n return target;\n }\n\n Object.keys(source).forEach((key) => {\n if (is.object(source[key])) {\n if (!Object.keys(target).includes(key)) {\n Object.assign(target, { [key]: {} });\n }\n\n extend(target[key], source[key]);\n } else {\n Object.assign(target, { [key]: source[key] });\n }\n });\n\n return extend(target, ...sources);\n}\n","// ==========================================================================\n// Element utils\n// ==========================================================================\n\nimport is from './is';\nimport { extend } from './objects';\n\n// Wrap an element\nexport function wrap(elements, wrapper) {\n // Convert `elements` to an array, if necessary.\n const targets = elements.length ? elements : [elements];\n\n // Loops backwards to prevent having to clone the wrapper on the\n // first element (see `child` below).\n Array.from(targets)\n .reverse()\n .forEach((element, index) => {\n const child = index > 0 ? wrapper.cloneNode(true) : wrapper;\n // Cache the current parent and sibling.\n const parent = element.parentNode;\n const sibling = element.nextSibling;\n\n // Wrap the element (is automatically removed from its current\n // parent).\n child.appendChild(element);\n\n // If the element had a sibling, insert the wrapper before\n // the sibling to maintain the HTML structure; otherwise, just\n // append it to the parent.\n if (sibling) {\n parent.insertBefore(child, sibling);\n } else {\n parent.appendChild(child);\n }\n });\n}\n\n// Set attributes\nexport function setAttributes(element, attributes) {\n if (!is.element(element) || is.empty(attributes)) {\n return;\n }\n\n // Assume null and undefined attributes should be left out,\n // Setting them would otherwise convert them to \"null\" and \"undefined\"\n Object.entries(attributes)\n .filter(([, value]) => !is.nullOrUndefined(value))\n .forEach(([key, value]) => element.setAttribute(key, value));\n}\n\n// Create a DocumentFragment\nexport function createElement(type, attributes, text) {\n // Create a new <element>\n const element = document.createElement(type);\n\n // Set all passed attributes\n if (is.object(attributes)) {\n setAttributes(element, attributes);\n }\n\n // Add text node\n if (is.string(text)) {\n element.innerText = text;\n }\n\n // Return built element\n return element;\n}\n\n// Inaert an element after another\nexport function insertAfter(element, target) {\n if (!is.element(element) || !is.element(target)) {\n return;\n }\n\n target.parentNode.insertBefore(element, target.nextSibling);\n}\n\n// Insert a DocumentFragment\nexport function insertElement(type, parent, attributes, text) {\n if (!is.element(parent)) {\n return;\n }\n\n parent.appendChild(createElement(type, attributes, text));\n}\n\n// Remove element(s)\nexport function removeElement(element) {\n if (is.nodeList(element) || is.array(element)) {\n Array.from(element).forEach(removeElement);\n return;\n }\n\n if (!is.element(element) || !is.element(element.parentNode)) {\n return;\n }\n\n element.parentNode.removeChild(element);\n}\n\n// Remove all child elements\nexport function emptyElement(element) {\n if (!is.element(element)) {\n return;\n }\n\n let { length } = element.childNodes;\n\n while (length > 0) {\n element.removeChild(element.lastChild);\n length -= 1;\n }\n}\n\n// Replace element\nexport function replaceElement(newChild, oldChild) {\n if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) {\n return null;\n }\n\n oldChild.parentNode.replaceChild(newChild, oldChild);\n\n return newChild;\n}\n\n// Get an attribute object from a string selector\nexport function getAttributesFromSelector(sel, existingAttributes) {\n // For example:\n // '.test' to { class: 'test' }\n // '#test' to { id: 'test' }\n // '[data-test=\"test\"]' to { 'data-test': 'test' }\n\n if (!is.string(sel) || is.empty(sel)) {\n return {};\n }\n\n const attributes = {};\n const existing = extend({}, existingAttributes);\n\n sel.split(',').forEach((s) => {\n // Remove whitespace\n const selector = s.trim();\n const className = selector.replace('.', '');\n const stripped = selector.replace(/[[\\]]/g, '');\n // Get the parts and value\n const parts = stripped.split('=');\n const [key] = parts;\n const value = parts.length > 1 ? parts[1].replace(/[\"']/g, '') : '';\n // Get the first character\n const start = selector.charAt(0);\n\n switch (start) {\n case '.':\n // Add to existing classname\n if (is.string(existing.class)) {\n attributes.class = `${existing.class} ${className}`;\n } else {\n attributes.class = className;\n }\n break;\n\n case '#':\n // ID selector\n attributes.id = selector.replace('#', '');\n break;\n\n case '[':\n // Attribute selector\n attributes[key] = value;\n\n break;\n\n default:\n break;\n }\n });\n\n return extend(existing, attributes);\n}\n\n// Toggle hidden\nexport function toggleHidden(element, hidden) {\n if (!is.element(element)) {\n return;\n }\n\n let hide = hidden;\n\n if (!is.boolean(hide)) {\n hide = !element.hidden;\n }\n\n // eslint-disable-next-line no-param-reassign\n element.hidden = hide;\n}\n\n// Mirror Element.classList.toggle, with IE compatibility for \"force\" argument\nexport function toggleClass(element, className, force) {\n if (is.nodeList(element)) {\n return Array.from(element).map((e) => toggleClass(e, className, force));\n }\n\n if (is.element(element)) {\n let method = 'toggle';\n if (typeof force !== 'undefined') {\n method = force ? 'add' : 'remove';\n }\n\n element.classList[method](className);\n return element.classList.contains(className);\n }\n\n return false;\n}\n\n// Has class name\nexport function hasClass(element, className) {\n return is.element(element) && element.classList.contains(className);\n}\n\n// Element matches selector\nexport function matches(element, selector) {\n const { prototype } = Element;\n\n function match() {\n return Array.from(document.querySelectorAll(selector)).includes(this);\n }\n\n const method =\n prototype.matches ||\n prototype.webkitMatchesSelector ||\n prototype.mozMatchesSelector ||\n prototype.msMatchesSelector ||\n match;\n\n return method.call(element, selector);\n}\n\n// Closest ancestor element matching selector (also tests element itself)\nexport function closest(element, selector) {\n const { prototype } = Element;\n\n // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill\n function closestElement() {\n let el = this;\n\n do {\n if (matches.matches(el, selector)) return el;\n el = el.parentElement || el.parentNode;\n } while (el !== null && el.nodeType === 1);\n return null;\n }\n\n const method = prototype.closest || closestElement;\n\n return method.call(element, selector);\n}\n\n// Find all elements\nexport function getElements(selector) {\n return this.elements.container.querySelectorAll(selector);\n}\n\n// Find a single element\nexport function getElement(selector) {\n return this.elements.container.querySelector(selector);\n}\n\n// Set focus and tab focus class\nexport function setFocus(element = null, tabFocus = false) {\n if (!is.element(element)) {\n return;\n }\n\n // Set regular focus\n element.focus({ preventScroll: true });\n\n // If we want to mimic keyboard focus via tab\n if (tabFocus) {\n toggleClass(element, this.config.classNames.tabFocus);\n }\n}\n","// ==========================================================================\n// Plyr support checks\n// ==========================================================================\n\nimport { transitionEndEvent } from './utils/animation';\nimport browser from './utils/browser';\nimport { createElement } from './utils/elements';\nimport is from './utils/is';\n\n// Default codecs for checking mimetype support\nconst defaultCodecs = {\n 'audio/ogg': 'vorbis',\n 'audio/wav': '1',\n 'video/webm': 'vp8, vorbis',\n 'video/mp4': 'avc1.42E01E, mp4a.40.2',\n 'video/ogg': 'theora',\n};\n\n// Check for feature support\nconst support = {\n // Basic support\n audio: 'canPlayType' in document.createElement('audio'),\n video: 'canPlayType' in document.createElement('video'),\n\n // Check for support\n // Basic functionality vs full UI\n check(type, provider, playsinline) {\n const canPlayInline = browser.isIPhone && playsinline && support.playsinline;\n const api = support[type] || provider !== 'html5';\n const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline);\n\n return {\n api,\n ui,\n };\n },\n\n // Picture-in-picture support\n // Safari & Chrome only currently\n pip: (() => {\n if (browser.isIPhone) {\n return false;\n }\n\n // Safari\n // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls\n if (is.function(createElement('video').webkitSetPresentationMode)) {\n return true;\n }\n\n // Chrome\n // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture\n if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) {\n return true;\n }\n\n return false;\n })(),\n\n // Airplay support\n // Safari only currently\n airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent),\n\n // Inline playback support\n // https://webkit.org/blog/6784/new-video-policies-for-ios/\n playsinline: 'playsInline' in document.createElement('video'),\n\n // Check for mime type support against a player instance\n // Credits: http://diveintohtml5.info/everything.html\n // Related: http://www.leanbackplayer.com/test/h5mt.html\n mime(input) {\n if (is.empty(input)) {\n return false;\n }\n\n const [mediaType] = input.split('/');\n let type = input;\n\n // Verify we're using HTML5 and there's no media type mismatch\n if (!this.isHTML5 || mediaType !== this.type) {\n return false;\n }\n\n // Add codec if required\n if (Object.keys(defaultCodecs).includes(type)) {\n type += `; codecs=\"${defaultCodecs[input]}\"`;\n }\n\n try {\n return Boolean(type && this.media.canPlayType(type).replace(/no/, ''));\n } catch (_) {\n return false;\n }\n },\n\n // Check for textTracks support\n textTracks: 'textTracks' in document.createElement('video'),\n\n // <input type=\"range\"> Sliders\n rangeInput: (() => {\n const range = document.createElement('input');\n range.type = 'range';\n return range.type === 'range';\n })(),\n\n // Touch\n // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event\n touch: 'ontouchstart' in document.documentElement,\n\n // Detect transitions support\n transitions: transitionEndEvent !== false,\n\n // Reduced motion iOS & MacOS setting\n // https://webkit.org/blog/7551/responsive-design-for-motion/\n reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches,\n};\n\nexport default support;\n","// ==========================================================================\n// Event utils\n// ==========================================================================\n\nimport is from './is';\n\n// Check for passive event listener support\n// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md\n// https://www.youtube.com/watch?v=NPM6172J22g\nconst supportsPassiveListeners = (() => {\n // Test via a getter in the options object to see if the passive property is accessed\n let supported = false;\n try {\n const options = Object.defineProperty({}, 'passive', {\n get() {\n supported = true;\n return null;\n },\n });\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n } catch (_) {\n // Do nothing\n }\n\n return supported;\n})();\n\n// Toggle event listener\nexport function toggleListener(element, event, callback, toggle = false, passive = true, capture = false) {\n // Bail if no element, event, or callback\n if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) {\n return;\n }\n\n // Allow multiple events\n const events = event.split(' ');\n // Build options\n // Default to just the capture boolean for browsers with no passive listener support\n let options = capture;\n\n // If passive events listeners are supported\n if (supportsPassiveListeners) {\n options = {\n // Whether the listener can be passive (i.e. default never prevented)\n passive,\n // Whether the listener is a capturing listener or not\n capture,\n };\n }\n\n // If a single node is passed, bind the event listener\n events.forEach((type) => {\n if (this && this.eventListeners && toggle) {\n // Cache event listener\n this.eventListeners.push({ element, type, callback, options });\n }\n\n element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options);\n });\n}\n\n// Bind event handler\nexport function on(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, true, passive, capture);\n}\n\n// Unbind event handler\nexport function off(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, false, passive, capture);\n}\n\n// Bind once-only event handler\nexport function once(element, events = '', callback, passive = true, capture = false) {\n const onceCallback = (...args) => {\n off(element, events, onceCallback, passive, capture);\n callback.apply(this, args);\n };\n\n toggleListener.call(this, element, events, onceCallback, true, passive, capture);\n}\n\n// Trigger event\nexport function triggerEvent(element, type = '', bubbles = false, detail = {}) {\n // Bail if no element\n if (!is.element(element) || is.empty(type)) {\n return;\n }\n\n // Create and dispatch the event\n const event = new CustomEvent(type, {\n bubbles,\n detail: { ...detail, plyr: this },\n });\n\n // Dispatch the event\n element.dispatchEvent(event);\n}\n\n// Unbind all cached event listeners\nexport function unbindListeners() {\n if (this && this.eventListeners) {\n this.eventListeners.forEach((item) => {\n const { element, type, callback, options } = item;\n element.removeEventListener(type, callback, options);\n });\n\n this.eventListeners = [];\n }\n}\n\n// Run method when / if player is ready\nexport function ready() {\n return new Promise((resolve) =>\n this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve),\n ).then(() => {});\n}\n","import is from './is';\n/**\n * Silence a Promise-like object.\n * This is useful for avoiding non-harmful, but potentially confusing \"uncaught\n * play promise\" rejection error messages.\n * @param {Object} value An object that may or may not be `Promise`-like.\n */\nexport function silencePromise(value) {\n if (is.promise(value)) {\n value.then(null, () => {});\n }\n}\n\nexport default { silencePromise };\n","// ==========================================================================\n// Array utils\n// ==========================================================================\n\nimport is from './is';\n\n// Remove duplicates in an array\nexport function dedupe(array) {\n if (!is.array(array)) {\n return array;\n }\n\n return array.filter((item, index) => array.indexOf(item) === index);\n}\n\n// Get the closest value in an array\nexport function closest(array, value) {\n if (!is.array(array) || !array.length) {\n return null;\n }\n\n return array.reduce((prev, curr) => (Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev));\n}\n","// ==========================================================================\n// Style utils\n// ==========================================================================\n\nimport { closest } from './arrays';\nimport is from './is';\n\n// Check support for a CSS declaration\nexport function supportsCSS(declaration) {\n if (!window || !window.CSS) {\n return false;\n }\n\n return window.CSS.supports(declaration);\n}\n\n// Standard/common aspect ratios\nconst standardRatios = [\n [1, 1],\n [4, 3],\n [3, 4],\n [5, 4],\n [4, 5],\n [3, 2],\n [2, 3],\n [16, 10],\n [10, 16],\n [16, 9],\n [9, 16],\n [21, 9],\n [9, 21],\n [32, 9],\n [9, 32],\n].reduce((out, [x, y]) => ({ ...out, [x / y]: [x, y] }), {});\n\n// Validate an aspect ratio\nexport function validateAspectRatio(input) {\n if (!is.array(input) && (!is.string(input) || !input.includes(':'))) {\n return false;\n }\n\n const ratio = is.array(input) ? input : input.split(':');\n\n return ratio.map(Number).every(is.number);\n}\n\n// Reduce an aspect ratio to it's lowest form\nexport function reduceAspectRatio(ratio) {\n if (!is.array(ratio) || !ratio.every(is.number)) {\n return null;\n }\n\n const [width, height] = ratio;\n const getDivider = (w, h) => (h === 0 ? w : getDivider(h, w % h));\n const divider = getDivider(width, height);\n\n return [width / divider, height / divider];\n}\n\n// Calculate an aspect ratio\nexport function getAspectRatio(input) {\n const parse = (ratio) => (validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null);\n // Try provided ratio\n let ratio = parse(input);\n\n // Get from config\n if (ratio === null) {\n ratio = parse(this.config.ratio);\n }\n\n // Get from embed\n if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) {\n ({ ratio } = this.embed);\n }\n\n // Get from HTML5 video\n if (ratio === null && this.isHTML5) {\n const { videoWidth, videoHeight } = this.media;\n ratio = [videoWidth, videoHeight];\n }\n\n return reduceAspectRatio(ratio);\n}\n\n// Set aspect ratio for responsive container\nexport function setAspectRatio(input) {\n if (!this.isVideo) {\n return {};\n }\n\n const { wrapper } = this.elements;\n const ratio = getAspectRatio.call(this, input);\n\n if (!is.array(ratio)) {\n return {};\n }\n\n const [x, y] = reduceAspectRatio(ratio);\n const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`);\n const padding = (100 / x) * y;\n\n if (useNative) {\n wrapper.style.aspectRatio = `${x}/${y}`;\n } else {\n wrapper.style.paddingBottom = `${padding}%`;\n }\n\n // For Vimeo we have an extra <div> to hide the standard controls and UI\n if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) {\n const height = (100 / this.media.offsetWidth) * parseInt(window.getComputedStyle(this.media).paddingBottom, 10);\n const offset = (height - padding) / (height / 50);\n\n if (this.fullscreen.active) {\n wrapper.style.paddingBottom = null;\n } else {\n this.media.style.transform = `translateY(-${offset}%)`;\n }\n } else if (this.isHTML5) {\n wrapper.classList.add(this.config.classNames.videoFixedRatio);\n }\n\n return { padding, ratio };\n}\n\n// Round an aspect ratio to closest standard ratio\nexport function roundAspectRatio(x, y, tolerance = 0.05) {\n const ratio = x / y;\n const closestRatio = closest(Object.keys(standardRatios), ratio);\n\n // Check match is within tolerance\n if (Math.abs(closestRatio - ratio) <= tolerance) {\n return standardRatios[closestRatio];\n }\n\n // No match\n return [x, y];\n}\n\n// Get the size of the viewport\n// https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions\nexport function getViewportSize() {\n const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);\n const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);\n return [width, height];\n}\n","// ==========================================================================\n// Plyr HTML5 helpers\n// ==========================================================================\n\nimport support from './support';\nimport { removeElement } from './utils/elements';\nimport { triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\nimport { setAspectRatio } from './utils/style';\n\nconst html5 = {\n getSources() {\n if (!this.isHTML5) {\n return [];\n }\n\n const sources = Array.from(this.media.querySelectorAll('source'));\n\n // Filter out unsupported sources (if type is specified)\n return sources.filter((source) => {\n const type = source.getAttribute('type');\n\n if (is.empty(type)) {\n return true;\n }\n\n return support.mime.call(this, type);\n });\n },\n\n // Get quality levels\n getQualityOptions() {\n // Whether we're forcing all options (e.g. for streaming)\n if (this.config.quality.forced) {\n return this.config.quality.options;\n }\n\n // Get sizes from <source> elements\n return html5.getSources\n .call(this)\n .map((source) => Number(source.getAttribute('data-res')))\n .filter(Boolean);\n },\n\n setup() {\n if (!this.isHTML5) {\n return;\n }\n\n const player = this;\n\n // Set speed options from config\n player.options.speed = player.config.speed.options;\n\n // Set aspect ratio if fixed\n if (!is.empty(this.config.ratio)) {\n setAspectRatio.call(player);\n }\n\n // Quality\n Object.defineProperty(player.media, 'quality', {\n get() {\n // Get sources\n const sources = html5.getSources.call(player);\n const source = sources.find((s) => s.getAttribute('src') === player.source);\n\n // Return size, if match is found\n return source && Number(source.getAttribute('data-res'));\n },\n set(input) {\n if (player.quality === input) {\n return;\n }\n\n // If we're using an external handler...\n if (player.config.quality.forced && is.function(player.config.quality.onChange)) {\n player.config.quality.onChange(input);\n } else {\n // Get sources\n const sources = html5.getSources.call(player);\n // Get first match for requested size\n const source = sources.find((s) => Number(s.getAttribute('data-res')) === input);\n\n // No matching source found\n if (!source) {\n return;\n }\n\n // Get current state\n const { currentTime, paused, preload, readyState, playbackRate } = player.media;\n\n // Set new source\n player.media.src = source.getAttribute('src');\n\n // Prevent loading if preload=\"none\" and the current source isn't loaded (#1044)\n if (preload !== 'none' || readyState) {\n // Restore time\n player.once('loadedmetadata', () => {\n player.speed = playbackRate;\n player.currentTime = currentTime;\n\n // Resume playing\n if (!paused) {\n silencePromise(player.play());\n }\n });\n\n // Load new source\n player.media.load();\n }\n }\n\n // Trigger change event\n triggerEvent.call(player, player.media, 'qualitychange', false, {\n quality: input,\n });\n },\n });\n },\n\n // Cancel current network requests\n // See https://github.com/sampotts/plyr/issues/174\n cancelRequests() {\n if (!this.isHTML5) {\n return;\n }\n\n // Remove child sources\n removeElement(html5.getSources.call(this));\n\n // Set blank video src attribute\n // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error\n // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection\n this.media.setAttribute('src', this.config.blankVideo);\n\n // Load the new empty source\n // This will cancel existing requests\n // See https://github.com/sampotts/plyr/issues/174\n this.media.load();\n\n // Debugging\n this.debug.log('Cancelled network requests');\n },\n};\n\nexport default html5;\n","// ==========================================================================\n// String utils\n// ==========================================================================\n\nimport is from './is';\n\n// Generate a random ID\nexport function generateId(prefix) {\n return `${prefix}-${Math.floor(Math.random() * 10000)}`;\n}\n\n// Format string\nexport function format(input, ...args) {\n if (is.empty(input)) {\n return input;\n }\n\n return input.toString().replace(/{(\\d+)}/g, (match, i) => args[i].toString());\n}\n\n// Get percentage\nexport function getPercentage(current, max) {\n if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) {\n return 0;\n }\n\n return ((current / max) * 100).toFixed(2);\n}\n\n// Replace all occurances of a string in a string\nexport const replaceAll = (input = '', find = '', replace = '') =>\n input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\\]/\\\\])/g, '\\\\$1'), 'g'), replace.toString());\n\n// Convert to title case\nexport const toTitleCase = (input = '') =>\n input.toString().replace(/\\w\\S*/g, (text) => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase());\n\n// Convert string to pascalCase\nexport function toPascalCase(input = '') {\n let string = input.toString();\n\n // Convert kebab case\n string = replaceAll(string, '-', ' ');\n\n // Convert snake case\n string = replaceAll(string, '_', ' ');\n\n // Convert to title case\n string = toTitleCase(string);\n\n // Convert to pascal case\n return replaceAll(string, ' ', '');\n}\n\n// Convert string to pascalCase\nexport function toCamelCase(input = '') {\n let string = input.toString();\n\n // Convert to pascal case\n string = toPascalCase(string);\n\n // Convert first character to lowercase\n return string.charAt(0).toLowerCase() + string.slice(1);\n}\n\n// Remove HTML from a string\nexport function stripHTML(source) {\n const fragment = document.createDocumentFragment();\n const element = document.createElement('div');\n fragment.appendChild(element);\n element.innerHTML = source;\n return fragment.firstChild.innerText;\n}\n\n// Like outerHTML, but also works for DocumentFragment\nexport function getHTML(element) {\n const wrapper = document.createElement('div');\n wrapper.appendChild(element);\n return wrapper.innerHTML;\n}\n","// ==========================================================================\n// Plyr internationalization\n// ==========================================================================\n\nimport is from './is';\nimport { getDeep } from './objects';\nimport { replaceAll } from './strings';\n\n// Skip i18n for abbreviations and brand names\nconst resources = {\n pip: 'PIP',\n airplay: 'AirPlay',\n html5: 'HTML5',\n vimeo: 'Vimeo',\n youtube: 'YouTube',\n};\n\nconst i18n = {\n get(key = '', config = {}) {\n if (is.empty(key) || is.empty(config)) {\n return '';\n }\n\n let string = getDeep(config.i18n, key);\n\n if (is.empty(string)) {\n if (Object.keys(resources).includes(key)) {\n return resources[key];\n }\n\n return '';\n }\n\n const replace = {\n '{seektime}': config.seekTime,\n '{title}': config.title,\n };\n\n Object.entries(replace).forEach(([k, v]) => {\n string = replaceAll(string, k, v);\n });\n\n return string;\n },\n};\n\nexport default i18n;\n","// ==========================================================================\n// Plyr storage\n// ==========================================================================\n\nimport is from './utils/is';\nimport { extend } from './utils/objects';\n\nclass Storage {\n constructor(player) {\n this.enabled = player.config.storage.enabled;\n this.key = player.config.storage.key;\n }\n\n // Check for actual support (see if we can use it)\n static get supported() {\n try {\n if (!('localStorage' in window)) {\n return false;\n }\n\n const test = '___test';\n\n // Try to use it (it might be disabled, e.g. user is in private mode)\n // see: https://github.com/sampotts/plyr/issues/131\n window.localStorage.setItem(test, test);\n window.localStorage.removeItem(test);\n\n return true;\n } catch (_) {\n return false;\n }\n }\n\n get = (key) => {\n if (!Storage.supported || !this.enabled) {\n return null;\n }\n\n const store = window.localStorage.getItem(this.key);\n\n if (is.empty(store)) {\n return null;\n }\n\n const json = JSON.parse(store);\n\n return is.string(key) && key.length ? json[key] : json;\n };\n\n set = (object) => {\n // Bail if we don't have localStorage support or it's disabled\n if (!Storage.supported || !this.enabled) {\n return;\n }\n\n // Can only store objectst\n if (!is.object(object)) {\n return;\n }\n\n // Get current storage\n let storage = this.get();\n\n // Default to empty object\n if (is.empty(storage)) {\n storage = {};\n }\n\n // Update the working copy of the values\n extend(storage, object);\n\n // Update storage\n try {\n window.localStorage.setItem(this.key, JSON.stringify(storage));\n } catch (_) {\n // Do nothing\n }\n };\n}\n\nexport default Storage;\n","// ==========================================================================\n// Fetch wrapper\n// Using XHR to avoid issues with older browsers\n// ==========================================================================\n\nexport default function fetch(url, responseType = 'text') {\n return new Promise((resolve, reject) => {\n try {\n const request = new XMLHttpRequest();\n\n // Check for CORS support\n if (!('withCredentials' in request)) {\n return;\n }\n\n request.addEventListener('load', () => {\n if (responseType === 'text') {\n try {\n resolve(JSON.parse(request.responseText));\n } catch (_) {\n resolve(request.responseText);\n }\n } else {\n resolve(request.response);\n }\n });\n\n request.addEventListener('error', () => {\n throw new Error(request.status);\n });\n\n request.open('GET', url, true);\n\n // Set the required response type\n request.responseType = responseType;\n\n request.send();\n } catch (error) {\n reject(error);\n }\n });\n}\n","// ==========================================================================\n// Sprite loader\n// ==========================================================================\n\nimport Storage from '../storage';\nimport fetch from './fetch';\nimport is from './is';\n\n// Load an external SVG sprite\nexport default function loadSprite(url, id) {\n if (!is.string(url)) {\n return;\n }\n\n const prefix = 'cache';\n const hasId = is.string(id);\n let isCached = false;\n const exists = () => document.getElementById(id) !== null;\n\n const update = (container, data) => {\n // eslint-disable-next-line no-param-reassign\n container.innerHTML = data;\n\n // Check again incase of race condition\n if (hasId && exists()) {\n return;\n }\n\n // Inject the SVG to the body\n document.body.insertAdjacentElement('afterbegin', container);\n };\n\n // Only load once if ID set\n if (!hasId || !exists()) {\n const useStorage = Storage.supported;\n // Create container\n const container = document.createElement('div');\n container.setAttribute('hidden', '');\n\n if (hasId) {\n container.setAttribute('id', id);\n }\n\n // Check in cache\n if (useStorage) {\n const cached = window.localStorage.getItem(`${prefix}-${id}`);\n isCached = cached !== null;\n\n if (isCached) {\n const data = JSON.parse(cached);\n update(container, data.content);\n }\n }\n\n // Get the sprite\n fetch(url)\n .then((result) => {\n if (is.empty(result)) {\n return;\n }\n\n if (useStorage) {\n try {\n window.localStorage.setItem(\n `${prefix}-${id}`,\n JSON.stringify({\n content: result,\n }),\n );\n } catch (_) {\n // Do nothing\n }\n }\n\n update(container, result);\n })\n .catch(() => {});\n }\n}\n","// ==========================================================================\n// Time utils\n// ==========================================================================\n\nimport is from './is';\n\n// Time helpers\nexport const getHours = (value) => Math.trunc((value / 60 / 60) % 60, 10);\nexport const getMinutes = (value) => Math.trunc((value / 60) % 60, 10);\nexport const getSeconds = (value) => Math.trunc(value % 60, 10);\n\n// Format time to UI friendly string\nexport function formatTime(time = 0, displayHours = false, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return formatTime(undefined, displayHours, inverted);\n }\n\n // Format time component to add leading zero\n const format = (value) => `0${value}`.slice(-2);\n // Breakdown to hours, mins, secs\n let hours = getHours(time);\n const mins = getMinutes(time);\n const secs = getSeconds(time);\n\n // Do we need to display hours?\n if (displayHours || hours > 0) {\n hours = `${hours}:`;\n } else {\n hours = '';\n }\n\n // Render\n return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`;\n}\n","// ==========================================================================\n// Plyr controls\n// TODO: This needs to be split into smaller files and cleaned up\n// ==========================================================================\n\nimport RangeTouch from 'rangetouch';\n\nimport captions from './captions';\nimport html5 from './html5';\nimport support from './support';\nimport { repaint, transitionEndEvent } from './utils/animation';\nimport { dedupe } from './utils/arrays';\nimport browser from './utils/browser';\nimport {\n createElement,\n emptyElement,\n getAttributesFromSelector,\n getElement,\n getElements,\n hasClass,\n matches,\n removeElement,\n setAttributes,\n setFocus,\n toggleClass,\n toggleHidden,\n} from './utils/elements';\nimport { off, on } from './utils/events';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport loadSprite from './utils/load-sprite';\nimport { extend } from './utils/objects';\nimport { getPercentage, replaceAll, toCamelCase, toTitleCase } from './utils/strings';\nimport { formatTime, getHours } from './utils/time';\n\n// TODO: Don't export a massive object - break down and create class\nconst controls = {\n // Get icon URL\n getIconUrl() {\n const url = new URL(this.config.iconUrl, window.location);\n const host = window.location.host ? window.location.host : window.top.location.host;\n const cors = url.host !== host || (browser.isIE && !window.svg4everybody);\n\n return {\n url: this.config.iconUrl,\n cors,\n };\n },\n\n // Find the UI controls\n findElements() {\n try {\n this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper);\n\n // Buttons\n this.elements.buttons = {\n play: getElements.call(this, this.config.selectors.buttons.play),\n pause: getElement.call(this, this.config.selectors.buttons.pause),\n restart: getElement.call(this, this.config.selectors.buttons.restart),\n rewind: getElement.call(this, this.config.selectors.buttons.rewind),\n fastForward: getElement.call(this, this.config.selectors.buttons.fastForward),\n mute: getElement.call(this, this.config.selectors.buttons.mute),\n pip: getElement.call(this, this.config.selectors.buttons.pip),\n airplay: getElement.call(this, this.config.selectors.buttons.airplay),\n settings: getElement.call(this, this.config.selectors.buttons.settings),\n captions: getElement.call(this, this.config.selectors.buttons.captions),\n fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen),\n };\n\n // Progress\n this.elements.progress = getElement.call(this, this.config.selectors.progress);\n\n // Inputs\n this.elements.inputs = {\n seek: getElement.call(this, this.config.selectors.inputs.seek),\n volume: getElement.call(this, this.config.selectors.inputs.volume),\n };\n\n // Display\n this.elements.display = {\n buffer: getElement.call(this, this.config.selectors.display.buffer),\n currentTime: getElement.call(this, this.config.selectors.display.currentTime),\n duration: getElement.call(this, this.config.selectors.display.duration),\n };\n\n // Seek tooltip\n if (is.element(this.elements.progress)) {\n this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`);\n }\n\n return true;\n } catch (error) {\n // Log it\n this.debug.warn('It looks like there is a problem with your custom controls HTML', error);\n\n // Restore native video controls\n this.toggleNativeControls(true);\n\n return false;\n }\n },\n\n // Create <svg> icon\n createIcon(type, attributes) {\n const namespace = 'http://www.w3.org/2000/svg';\n const iconUrl = controls.getIconUrl.call(this);\n const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`;\n // Create <svg>\n const icon = document.createElementNS(namespace, 'svg');\n setAttributes(\n icon,\n extend(attributes, {\n 'aria-hidden': 'true',\n focusable: 'false',\n }),\n );\n\n // Create the <use> to reference sprite\n const use = document.createElementNS(namespace, 'use');\n const path = `${iconPath}-${type}`;\n\n // Set `href` attributes\n // https://github.com/sampotts/plyr/issues/460\n // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href\n if ('href' in use) {\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path);\n }\n\n // Always set the older attribute even though it's \"deprecated\" (it'll be around for ages)\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path);\n\n // Add <use> to <svg>\n icon.appendChild(use);\n\n return icon;\n },\n\n // Create hidden text label\n createLabel(key, attr = {}) {\n const text = i18n.get(key, this.config);\n const attributes = { ...attr, class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ') };\n\n return createElement('span', attributes, text);\n },\n\n // Create a badge\n createBadge(text) {\n if (is.empty(text)) {\n return null;\n }\n\n const badge = createElement('span', {\n class: this.config.classNames.menu.value,\n });\n\n badge.appendChild(\n createElement(\n 'span',\n {\n class: this.config.classNames.menu.badge,\n },\n text,\n ),\n );\n\n return badge;\n },\n\n // Create a <button>\n createButton(buttonType, attr) {\n const attributes = extend({}, attr);\n let type = toCamelCase(buttonType);\n\n const props = {\n element: 'button',\n toggle: false,\n label: null,\n icon: null,\n labelPressed: null,\n iconPressed: null,\n };\n\n ['element', 'icon', 'label'].forEach((key) => {\n if (Object.keys(attributes).includes(key)) {\n props[key] = attributes[key];\n delete attributes[key];\n }\n });\n\n // Default to 'button' type to prevent form submission\n if (props.element === 'button' && !Object.keys(attributes).includes('type')) {\n attributes.type = 'button';\n }\n\n // Set class name\n if (Object.keys(attributes).includes('class')) {\n if (!attributes.class.split(' ').some((c) => c === this.config.classNames.control)) {\n extend(attributes, {\n class: `${attributes.class} ${this.config.classNames.control}`,\n });\n }\n } else {\n attributes.class = this.config.classNames.control;\n }\n\n // Large play button\n switch (buttonType) {\n case 'play':\n props.toggle = true;\n props.label = 'play';\n props.labelPressed = 'pause';\n props.icon = 'play';\n props.iconPressed = 'pause';\n break;\n\n case 'mute':\n props.toggle = true;\n props.label = 'mute';\n props.labelPressed = 'unmute';\n props.icon = 'volume';\n props.iconPressed = 'muted';\n break;\n\n case 'captions':\n props.toggle = true;\n props.label = 'enableCaptions';\n props.labelPressed = 'disableCaptions';\n props.icon = 'captions-off';\n props.iconPressed = 'captions-on';\n break;\n\n case 'fullscreen':\n props.toggle = true;\n props.label = 'enterFullscreen';\n props.labelPressed = 'exitFullscreen';\n props.icon = 'enter-fullscreen';\n props.iconPressed = 'exit-fullscreen';\n break;\n\n case 'play-large':\n attributes.class += ` ${this.config.classNames.control}--overlaid`;\n type = 'play';\n props.label = 'play';\n props.icon = 'play';\n break;\n\n default:\n if (is.empty(props.label)) {\n props.label = type;\n }\n if (is.empty(props.icon)) {\n props.icon = buttonType;\n }\n }\n\n const button = createElement(props.element);\n\n // Setup toggle icon and labels\n if (props.toggle) {\n // Icon\n button.appendChild(\n controls.createIcon.call(this, props.iconPressed, {\n class: 'icon--pressed',\n }),\n );\n button.appendChild(\n controls.createIcon.call(this, props.icon, {\n class: 'icon--not-pressed',\n }),\n );\n\n // Label/Tooltip\n button.appendChild(\n controls.createLabel.call(this, props.labelPressed, {\n class: 'label--pressed',\n }),\n );\n button.appendChild(\n controls.createLabel.call(this, props.label, {\n class: 'label--not-pressed',\n }),\n );\n } else {\n button.appendChild(controls.createIcon.call(this, props.icon));\n button.appendChild(controls.createLabel.call(this, props.label));\n }\n\n // Merge and set attributes\n extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes));\n setAttributes(button, attributes);\n\n // We have multiple play buttons\n if (type === 'play') {\n if (!is.array(this.elements.buttons[type])) {\n this.elements.buttons[type] = [];\n }\n\n this.elements.buttons[type].push(button);\n } else {\n this.elements.buttons[type] = button;\n }\n\n return button;\n },\n\n // Create an <input type='range'>\n createRange(type, attributes) {\n // Seek input\n const input = createElement(\n 'input',\n extend(\n getAttributesFromSelector(this.config.selectors.inputs[type]),\n {\n type: 'range',\n min: 0,\n max: 100,\n step: 0.01,\n value: 0,\n autocomplete: 'off',\n // A11y fixes for https://github.com/sampotts/plyr/issues/905\n role: 'slider',\n 'aria-label': i18n.get(type, this.config),\n 'aria-valuemin': 0,\n 'aria-valuemax': 100,\n 'aria-valuenow': 0,\n },\n attributes,\n ),\n );\n\n this.elements.inputs[type] = input;\n\n // Set the fill for webkit now\n controls.updateRangeFill.call(this, input);\n\n // Improve support on touch devices\n RangeTouch.setup(input);\n\n return input;\n },\n\n // Create a <progress>\n createProgress(type, attributes) {\n const progress = createElement(\n 'progress',\n extend(\n getAttributesFromSelector(this.config.selectors.display[type]),\n {\n min: 0,\n max: 100,\n value: 0,\n role: 'progressbar',\n 'aria-hidden': true,\n },\n attributes,\n ),\n );\n\n // Create the label inside\n if (type !== 'volume') {\n progress.appendChild(createElement('span', null, '0'));\n\n const suffixKey = {\n played: 'played',\n buffer: 'buffered',\n }[type];\n const suffix = suffixKey ? i18n.get(suffixKey, this.config) : '';\n\n progress.innerText = `% ${suffix.toLowerCase()}`;\n }\n\n this.elements.display[type] = progress;\n\n return progress;\n },\n\n // Create time display\n createTime(type, attrs) {\n const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs);\n\n const container = createElement(\n 'div',\n extend(attributes, {\n class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(),\n 'aria-label': i18n.get(type, this.config),\n }),\n '00:00',\n );\n\n // Reference for updates\n this.elements.display[type] = container;\n\n return container;\n },\n\n // Bind keyboard shortcuts for a menu item\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n bindMenuItemShortcuts(menuItem, type) {\n // Navigate through menus via arrow keys and space\n on.call(\n this,\n menuItem,\n 'keydown keyup',\n (event) => {\n // We only care about space and ⬆️ ⬇️️ ➡️\n if (![32, 38, 39, 40].includes(event.which)) {\n return;\n }\n\n // Prevent play / seek\n event.preventDefault();\n event.stopPropagation();\n\n // We're just here to prevent the keydown bubbling\n if (event.type === 'keydown') {\n return;\n }\n\n const isRadioButton = matches(menuItem, '[role=\"menuitemradio\"]');\n\n // Show the respective menu\n if (!isRadioButton && [32, 39].includes(event.which)) {\n controls.showMenuPanel.call(this, type, true);\n } else {\n let target;\n\n if (event.which !== 32) {\n if (event.which === 40 || (isRadioButton && event.which === 39)) {\n target = menuItem.nextElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.firstElementChild;\n }\n } else {\n target = menuItem.previousElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.lastElementChild;\n }\n }\n\n setFocus.call(this, target, true);\n }\n }\n },\n false,\n );\n\n // Enter will fire a `click` event but we still need to manage focus\n // So we bind to keyup which fires after and set focus here\n on.call(this, menuItem, 'keyup', (event) => {\n if (event.which !== 13) {\n return;\n }\n\n controls.focusFirstMenuItem.call(this, null, true);\n });\n },\n\n // Create a settings menu item\n createMenuItem({ value, list, type, title, badge = null, checked = false }) {\n const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]);\n\n const menuItem = createElement(\n 'button',\n extend(attributes, {\n type: 'button',\n role: 'menuitemradio',\n class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(),\n 'aria-checked': checked,\n value,\n }),\n );\n\n const flex = createElement('span');\n\n // We have to set as HTML incase of special characters\n flex.innerHTML = title;\n\n if (is.element(badge)) {\n flex.appendChild(badge);\n }\n\n menuItem.appendChild(flex);\n\n // Replicate radio button behaviour\n Object.defineProperty(menuItem, 'checked', {\n enumerable: true,\n get() {\n return menuItem.getAttribute('aria-checked') === 'true';\n },\n set(check) {\n // Ensure exclusivity\n if (check) {\n Array.from(menuItem.parentNode.children)\n .filter((node) => matches(node, '[role=\"menuitemradio\"]'))\n .forEach((node) => node.setAttribute('aria-checked', 'false'));\n }\n\n menuItem.setAttribute('aria-checked', check ? 'true' : 'false');\n },\n });\n\n this.listeners.bind(\n menuItem,\n 'click keyup',\n (event) => {\n if (is.keyboardEvent(event) && event.which !== 32) {\n return;\n }\n\n event.preventDefault();\n event.stopPropagation();\n\n menuItem.checked = true;\n\n switch (type) {\n case 'language':\n this.currentTrack = Number(value);\n break;\n\n case 'quality':\n this.quality = value;\n break;\n\n case 'speed':\n this.speed = parseFloat(value);\n break;\n\n default:\n break;\n }\n\n controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event));\n },\n type,\n false,\n );\n\n controls.bindMenuItemShortcuts.call(this, menuItem, type);\n\n list.appendChild(menuItem);\n },\n\n // Format a time for display\n formatTime(time = 0, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return time;\n }\n\n // Always display hours if duration is over an hour\n const forceHours = getHours(this.duration) > 0;\n\n return formatTime(time, forceHours, inverted);\n },\n\n // Update the displayed time\n updateTimeDisplay(target = null, time = 0, inverted = false) {\n // Bail if there's no element to display or the value isn't a number\n if (!is.element(target) || !is.number(time)) {\n return;\n }\n\n // eslint-disable-next-line no-param-reassign\n target.innerText = controls.formatTime(time, inverted);\n },\n\n // Update volume UI and storage\n updateVolume() {\n if (!this.supported.ui) {\n return;\n }\n\n // Update range\n if (is.element(this.elements.inputs.volume)) {\n controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);\n }\n\n // Update mute state\n if (is.element(this.elements.buttons.mute)) {\n this.elements.buttons.mute.pressed = this.muted || this.volume === 0;\n }\n },\n\n // Update seek value and lower fill\n setRange(target, value = 0) {\n if (!is.element(target)) {\n return;\n }\n\n // eslint-disable-next-line\n target.value = value;\n\n // Webkit range fill\n controls.updateRangeFill.call(this, target);\n },\n\n // Update <progress> elements\n updateProgress(event) {\n if (!this.supported.ui || !is.event(event)) {\n return;\n }\n\n let value = 0;\n\n const setProgress = (target, input) => {\n const val = is.number(input) ? input : 0;\n const progress = is.element(target) ? target : this.elements.display.buffer;\n\n // Update value and label\n if (is.element(progress)) {\n progress.value = val;\n\n // Update text label inside\n const label = progress.getElementsByTagName('span')[0];\n if (is.element(label)) {\n label.childNodes[0].nodeValue = val;\n }\n }\n };\n\n if (event) {\n switch (event.type) {\n // Video playing\n case 'timeupdate':\n case 'seeking':\n case 'seeked':\n value = getPercentage(this.currentTime, this.duration);\n\n // Set seek range value only if it's a 'natural' time event\n if (event.type === 'timeupdate') {\n controls.setRange.call(this, this.elements.inputs.seek, value);\n }\n\n break;\n\n // Check buffer status\n case 'playing':\n case 'progress':\n setProgress(this.elements.display.buffer, this.buffered * 100);\n\n break;\n\n default:\n break;\n }\n }\n },\n\n // Webkit polyfill for lower fill range\n updateRangeFill(target) {\n // Get range from event if event passed\n const range = is.event(target) ? target.target : target;\n\n // Needs to be a valid <input type='range'>\n if (!is.element(range) || range.getAttribute('type') !== 'range') {\n return;\n }\n\n // Set aria values for https://github.com/sampotts/plyr/issues/905\n if (matches(range, this.config.selectors.inputs.seek)) {\n range.setAttribute('aria-valuenow', this.currentTime);\n const currentTime = controls.formatTime(this.currentTime);\n const duration = controls.formatTime(this.duration);\n const format = i18n.get('seekLabel', this.config);\n range.setAttribute(\n 'aria-valuetext',\n format.replace('{currentTime}', currentTime).replace('{duration}', duration),\n );\n } else if (matches(range, this.config.selectors.inputs.volume)) {\n const percent = range.value * 100;\n range.setAttribute('aria-valuenow', percent);\n range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`);\n } else {\n range.setAttribute('aria-valuenow', range.value);\n }\n\n // WebKit only\n if (!browser.isWebkit) {\n return;\n }\n\n // Set CSS custom property\n range.style.setProperty('--value', `${(range.value / range.max) * 100}%`);\n },\n\n // Update hover tooltip for seeking\n updateSeekTooltip(event) {\n // Bail if setting not true\n if (\n !this.config.tooltips.seek ||\n !is.element(this.elements.inputs.seek) ||\n !is.element(this.elements.display.seekTooltip) ||\n this.duration === 0\n ) {\n return;\n }\n\n const visible = `${this.config.classNames.tooltip}--visible`;\n const toggle = (show) => toggleClass(this.elements.display.seekTooltip, visible, show);\n\n // Hide on touch\n if (this.touch) {\n toggle(false);\n return;\n }\n\n // Determine percentage, if already visible\n let percent = 0;\n const clientRect = this.elements.progress.getBoundingClientRect();\n\n if (is.event(event)) {\n percent = (100 / clientRect.width) * (event.pageX - clientRect.left);\n } else if (hasClass(this.elements.display.seekTooltip, visible)) {\n percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);\n } else {\n return;\n }\n\n // Set bounds\n if (percent < 0) {\n percent = 0;\n } else if (percent > 100) {\n percent = 100;\n }\n\n // Display the time a click would seek to\n controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, (this.duration / 100) * percent);\n\n // Set position\n this.elements.display.seekTooltip.style.left = `${percent}%`;\n\n // Show/hide the tooltip\n // If the event is a moues in/out and percentage is inside bounds\n if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) {\n toggle(event.type === 'mouseenter');\n }\n },\n\n // Handle time change event\n timeUpdate(event) {\n // Only invert if only one time element is displayed and used for both duration and currentTime\n const invert = !is.element(this.elements.display.duration) && this.config.invertTime;\n\n // Duration\n controls.updateTimeDisplay.call(\n this,\n this.elements.display.currentTime,\n invert ? this.duration - this.currentTime : this.currentTime,\n invert,\n );\n\n // Ignore updates while seeking\n if (event && event.type === 'timeupdate' && this.media.seeking) {\n return;\n }\n\n // Playing progress\n controls.updateProgress.call(this, event);\n },\n\n // Show the duration on metadataloaded or durationchange events\n durationUpdate() {\n // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false\n if (!this.supported.ui || (!this.config.invertTime && this.currentTime)) {\n return;\n }\n\n // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar.\n // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415\n // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062\n // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338\n if (this.duration >= 2 ** 32) {\n toggleHidden(this.elements.display.currentTime, true);\n toggleHidden(this.elements.progress, true);\n return;\n }\n\n // Update ARIA values\n if (is.element(this.elements.inputs.seek)) {\n this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration);\n }\n\n // If there's a spot to display duration\n const hasDuration = is.element(this.elements.display.duration);\n\n // If there's only one time display, display duration there\n if (!hasDuration && this.config.displayDuration && this.paused) {\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);\n }\n\n // If there's a duration element, update content\n if (hasDuration) {\n controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);\n }\n\n // Update the tooltip (if visible)\n controls.updateSeekTooltip.call(this);\n },\n\n // Hide/show a tab\n toggleMenuButton(setting, toggle) {\n toggleHidden(this.elements.settings.buttons[setting], !toggle);\n },\n\n // Update the selected setting\n updateSetting(setting, container, input) {\n const pane = this.elements.settings.panels[setting];\n let value = null;\n let list = container;\n\n if (setting === 'captions') {\n value = this.currentTrack;\n } else {\n value = !is.empty(input) ? input : this[setting];\n\n // Get default\n if (is.empty(value)) {\n value = this.config[setting].default;\n }\n\n // Unsupported value\n if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) {\n this.debug.warn(`Unsupported value of '${value}' for ${setting}`);\n return;\n }\n\n // Disabled value\n if (!this.config[setting].options.includes(value)) {\n this.debug.warn(`Disabled value of '${value}' for ${setting}`);\n return;\n }\n }\n\n // Get the list if we need to\n if (!is.element(list)) {\n list = pane && pane.querySelector('[role=\"menu\"]');\n }\n\n // If there's no list it means it's not been rendered...\n if (!is.element(list)) {\n return;\n }\n\n // Update the label\n const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`);\n label.innerHTML = controls.getLabel.call(this, setting, value);\n\n // Find the radio option and check it\n const target = list && list.querySelector(`[value=\"${value}\"]`);\n\n if (is.element(target)) {\n target.checked = true;\n }\n },\n\n // Translate a value into a nice label\n getLabel(setting, value) {\n switch (setting) {\n case 'speed':\n return value === 1 ? i18n.get('normal', this.config) : `${value}×`;\n\n case 'quality':\n if (is.number(value)) {\n const label = i18n.get(`qualityLabel.${value}`, this.config);\n\n if (!label.length) {\n return `${value}p`;\n }\n\n return label;\n }\n\n return toTitleCase(value);\n\n case 'captions':\n return captions.getLabel.call(this);\n\n default:\n return null;\n }\n },\n\n // Set the quality menu\n setQualityMenu(options) {\n // Menu required\n if (!is.element(this.elements.settings.panels.quality)) {\n return;\n }\n\n const type = 'quality';\n const list = this.elements.settings.panels.quality.querySelector('[role=\"menu\"]');\n\n // Set options if passed and filter based on uniqueness and config\n if (is.array(options)) {\n this.options.quality = dedupe(options).filter((quality) => this.config.quality.options.includes(quality));\n }\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1;\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If we're hiding, nothing more to do\n if (!toggle) {\n return;\n }\n\n // Get the badge HTML for HD, 4K etc\n const getBadge = (quality) => {\n const label = i18n.get(`qualityBadge.${quality}`, this.config);\n\n if (!label.length) {\n return null;\n }\n\n return controls.createBadge.call(this, label);\n };\n\n // Sort options by the config and then render options\n this.options.quality\n .sort((a, b) => {\n const sorting = this.config.quality.options;\n return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1;\n })\n .forEach((quality) => {\n controls.createMenuItem.call(this, {\n value: quality,\n list,\n type,\n title: controls.getLabel.call(this, 'quality', quality),\n badge: getBadge(quality),\n });\n });\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Set the looping options\n /* setLoopMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.loop)) {\n return;\n }\n\n const options = ['start', 'end', 'all', 'reset'];\n const list = this.elements.settings.panels.loop.querySelector('[role=\"menu\"]');\n\n // Show the pane and tab\n toggleHidden(this.elements.settings.buttons.loop, false);\n toggleHidden(this.elements.settings.panels.loop, false);\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.loop.options);\n controls.toggleMenuButton.call(this, 'loop', toggle);\n\n // Empty the menu\n emptyElement(list);\n\n options.forEach(option => {\n const item = createElement('li');\n\n const button = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.loop), {\n type: 'button',\n class: this.config.classNames.control,\n 'data-plyr-loop-action': option,\n }),\n i18n.get(option, this.config)\n );\n\n if (['start', 'end'].includes(option)) {\n const badge = controls.createBadge.call(this, '00:00');\n button.appendChild(badge);\n }\n\n item.appendChild(button);\n list.appendChild(item);\n });\n }, */\n\n // Get current selected caption language\n // TODO: rework this to user the getter in the API?\n\n // Set a list of available captions languages\n setCaptionsMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.captions)) {\n return;\n }\n\n // TODO: Captions or language? Currently it's mixed\n const type = 'captions';\n const list = this.elements.settings.panels.captions.querySelector('[role=\"menu\"]');\n const tracks = captions.getTracks.call(this);\n const toggle = Boolean(tracks.length);\n\n // Toggle the pane and tab\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If there's no captions, bail\n if (!toggle) {\n return;\n }\n\n // Generate options data\n const options = tracks.map((track, value) => ({\n value,\n checked: this.captions.toggled && this.currentTrack === value,\n title: captions.getLabel.call(this, track),\n badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()),\n list,\n type: 'language',\n }));\n\n // Add the \"Disabled\" option to turn off captions\n options.unshift({\n value: -1,\n checked: !this.captions.toggled,\n title: i18n.get('disabled', this.config),\n list,\n type: 'language',\n });\n\n // Generate options\n options.forEach(controls.createMenuItem.bind(this));\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Set a list of available captions languages\n setSpeedMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.speed)) {\n return;\n }\n\n const type = 'speed';\n const list = this.elements.settings.panels.speed.querySelector('[role=\"menu\"]');\n\n // Filter out invalid speeds\n this.options.speed = this.options.speed.filter((o) => o >= this.minimumSpeed && o <= this.maximumSpeed);\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1;\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If we're hiding, nothing more to do\n if (!toggle) {\n return;\n }\n\n // Create items\n this.options.speed.forEach((speed) => {\n controls.createMenuItem.call(this, {\n value: speed,\n list,\n type,\n title: controls.getLabel.call(this, 'speed', speed),\n });\n });\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Check if we need to hide/show the settings menu\n checkMenu() {\n const { buttons } = this.elements.settings;\n const visible = !is.empty(buttons) && Object.values(buttons).some((button) => !button.hidden);\n\n toggleHidden(this.elements.settings.menu, !visible);\n },\n\n // Focus the first menu item in a given (or visible) menu\n focusFirstMenuItem(pane, tabFocus = false) {\n if (this.elements.settings.popup.hidden) {\n return;\n }\n\n let target = pane;\n\n if (!is.element(target)) {\n target = Object.values(this.elements.settings.panels).find((p) => !p.hidden);\n }\n\n const firstItem = target.querySelector('[role^=\"menuitem\"]');\n\n setFocus.call(this, firstItem, tabFocus);\n },\n\n // Show/hide menu\n toggleMenu(input) {\n const { popup } = this.elements.settings;\n const button = this.elements.buttons.settings;\n\n // Menu and button are required\n if (!is.element(popup) || !is.element(button)) {\n return;\n }\n\n // True toggle by default\n const { hidden } = popup;\n let show = hidden;\n\n if (is.boolean(input)) {\n show = input;\n } else if (is.keyboardEvent(input) && input.which === 27) {\n show = false;\n } else if (is.event(input)) {\n // If Plyr is in a shadowDOM, the event target is set to the component, instead of the\n // Element in the shadowDOM. The path, if available, is complete.\n const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target;\n const isMenuItem = popup.contains(target);\n\n // If the click was inside the menu or if the click\n // wasn't the button or menu item and we're trying to\n // show the menu (a doc click shouldn't show the menu)\n if (isMenuItem || (!isMenuItem && input.target !== button && show)) {\n return;\n }\n }\n\n // Set button attributes\n button.setAttribute('aria-expanded', show);\n\n // Show the actual popup\n toggleHidden(popup, !show);\n\n // Add class hook\n toggleClass(this.elements.container, this.config.classNames.menu.open, show);\n\n // Focus the first item if key interaction\n if (show && is.keyboardEvent(input)) {\n controls.focusFirstMenuItem.call(this, null, true);\n } else if (!show && !hidden) {\n // If closing, re-focus the button\n setFocus.call(this, button, is.keyboardEvent(input));\n }\n },\n\n // Get the natural size of a menu panel\n getMenuSize(tab) {\n const clone = tab.cloneNode(true);\n clone.style.position = 'absolute';\n clone.style.opacity = 0;\n clone.removeAttribute('hidden');\n\n // Append to parent so we get the \"real\" size\n tab.parentNode.appendChild(clone);\n\n // Get the sizes before we remove\n const width = clone.scrollWidth;\n const height = clone.scrollHeight;\n\n // Remove from the DOM\n removeElement(clone);\n\n return {\n width,\n height,\n };\n },\n\n // Show a panel in the menu\n showMenuPanel(type = '', tabFocus = false) {\n const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`);\n\n // Nothing to show, bail\n if (!is.element(target)) {\n return;\n }\n\n // Hide all other panels\n const container = target.parentNode;\n const current = Array.from(container.children).find((node) => !node.hidden);\n\n // If we can do fancy animations, we'll animate the height/width\n if (support.transitions && !support.reducedMotion) {\n // Set the current width as a base\n container.style.width = `${current.scrollWidth}px`;\n container.style.height = `${current.scrollHeight}px`;\n\n // Get potential sizes\n const size = controls.getMenuSize.call(this, target);\n\n // Restore auto height/width\n const restore = (event) => {\n // We're only bothered about height and width on the container\n if (event.target !== container || !['width', 'height'].includes(event.propertyName)) {\n return;\n }\n\n // Revert back to auto\n container.style.width = '';\n container.style.height = '';\n\n // Only listen once\n off.call(this, container, transitionEndEvent, restore);\n };\n\n // Listen for the transition finishing and restore auto height/width\n on.call(this, container, transitionEndEvent, restore);\n\n // Set dimensions to target\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n }\n\n // Set attributes on current tab\n toggleHidden(current, true);\n\n // Set attributes on target\n toggleHidden(target, false);\n\n // Focus the first item\n controls.focusFirstMenuItem.call(this, target, tabFocus);\n },\n\n // Set the download URL\n setDownloadUrl() {\n const button = this.elements.buttons.download;\n\n // Bail if no button\n if (!is.element(button)) {\n return;\n }\n\n // Set attribute\n button.setAttribute('href', this.download);\n },\n\n // Build the default HTML\n create(data) {\n const {\n bindMenuItemShortcuts,\n createButton,\n createProgress,\n createRange,\n createTime,\n setQualityMenu,\n setSpeedMenu,\n showMenuPanel,\n } = controls;\n this.elements.controls = null;\n\n // Larger overlaid play button\n if (is.array(this.config.controls) && this.config.controls.includes('play-large')) {\n this.elements.container.appendChild(createButton.call(this, 'play-large'));\n }\n\n // Create the container\n const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper));\n this.elements.controls = container;\n\n // Default item attributes\n const defaultAttributes = { class: 'plyr__controls__item' };\n\n // Loop through controls in order\n dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach((control) => {\n // Restart button\n if (control === 'restart') {\n container.appendChild(createButton.call(this, 'restart', defaultAttributes));\n }\n\n // Rewind button\n if (control === 'rewind') {\n container.appendChild(createButton.call(this, 'rewind', defaultAttributes));\n }\n\n // Play/Pause button\n if (control === 'play') {\n container.appendChild(createButton.call(this, 'play', defaultAttributes));\n }\n\n // Fast forward button\n if (control === 'fast-forward') {\n container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes));\n }\n\n // Progress\n if (control === 'progress') {\n const progressContainer = createElement('div', {\n class: `${defaultAttributes.class} plyr__progress__container`,\n });\n\n const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress));\n\n // Seek range slider\n progress.appendChild(\n createRange.call(this, 'seek', {\n id: `plyr-seek-${data.id}`,\n }),\n );\n\n // Buffer progress\n progress.appendChild(createProgress.call(this, 'buffer'));\n\n // TODO: Add loop display indicator\n\n // Seek tooltip\n if (this.config.tooltips.seek) {\n const tooltip = createElement(\n 'span',\n {\n class: this.config.classNames.tooltip,\n },\n '00:00',\n );\n\n progress.appendChild(tooltip);\n this.elements.display.seekTooltip = tooltip;\n }\n\n this.elements.progress = progress;\n progressContainer.appendChild(this.elements.progress);\n container.appendChild(progressContainer);\n }\n\n // Media current time display\n if (control === 'current-time') {\n container.appendChild(createTime.call(this, 'currentTime', defaultAttributes));\n }\n\n // Media duration display\n if (control === 'duration') {\n container.appendChild(createTime.call(this, 'duration', defaultAttributes));\n }\n\n // Volume controls\n if (control === 'mute' || control === 'volume') {\n let { volume } = this.elements;\n\n // Create the volume container if needed\n if (!is.element(volume) || !container.contains(volume)) {\n volume = createElement(\n 'div',\n extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__volume`.trim(),\n }),\n );\n\n this.elements.volume = volume;\n\n container.appendChild(volume);\n }\n\n // Toggle mute button\n if (control === 'mute') {\n volume.appendChild(createButton.call(this, 'mute'));\n }\n\n // Volume range control\n // Ignored on iOS as it's handled globally\n // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html\n if (control === 'volume' && !browser.isIos) {\n // Set the attributes\n const attributes = {\n max: 1,\n step: 0.05,\n value: this.config.volume,\n };\n\n // Create the volume range slider\n volume.appendChild(\n createRange.call(\n this,\n 'volume',\n extend(attributes, {\n id: `plyr-volume-${data.id}`,\n }),\n ),\n );\n }\n }\n\n // Toggle captions button\n if (control === 'captions') {\n container.appendChild(createButton.call(this, 'captions', defaultAttributes));\n }\n\n // Settings button / menu\n if (control === 'settings' && !is.empty(this.config.settings)) {\n const wrapper = createElement(\n 'div',\n extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__menu`.trim(),\n hidden: '',\n }),\n );\n\n wrapper.appendChild(\n createButton.call(this, 'settings', {\n 'aria-haspopup': true,\n 'aria-controls': `plyr-settings-${data.id}`,\n 'aria-expanded': false,\n }),\n );\n\n const popup = createElement('div', {\n class: 'plyr__menu__container',\n id: `plyr-settings-${data.id}`,\n hidden: '',\n });\n\n const inner = createElement('div');\n\n const home = createElement('div', {\n id: `plyr-settings-${data.id}-home`,\n });\n\n // Create the menu\n const menu = createElement('div', {\n role: 'menu',\n });\n\n home.appendChild(menu);\n inner.appendChild(home);\n this.elements.settings.panels.home = home;\n\n // Build the menu items\n this.config.settings.forEach((type) => {\n // TODO: bundle this with the createMenuItem helper and bindings\n const menuItem = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.settings), {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`,\n role: 'menuitem',\n 'aria-haspopup': true,\n hidden: '',\n }),\n );\n\n // Bind menu shortcuts for keyboard users\n bindMenuItemShortcuts.call(this, menuItem, type);\n\n // Show menu on click\n on.call(this, menuItem, 'click', () => {\n showMenuPanel.call(this, type, false);\n });\n\n const flex = createElement('span', null, i18n.get(type, this.config));\n\n const value = createElement('span', {\n class: this.config.classNames.menu.value,\n });\n\n // Speed contains HTML entities\n value.innerHTML = data[type];\n\n flex.appendChild(value);\n menuItem.appendChild(flex);\n menu.appendChild(menuItem);\n\n // Build the panes\n const pane = createElement('div', {\n id: `plyr-settings-${data.id}-${type}`,\n hidden: '',\n });\n\n // Back button\n const backButton = createElement('button', {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--back`,\n });\n\n // Visible label\n backButton.appendChild(\n createElement(\n 'span',\n {\n 'aria-hidden': true,\n },\n i18n.get(type, this.config),\n ),\n );\n\n // Screen reader label\n backButton.appendChild(\n createElement(\n 'span',\n {\n class: this.config.classNames.hidden,\n },\n i18n.get('menuBack', this.config),\n ),\n );\n\n // Go back via keyboard\n on.call(\n this,\n pane,\n 'keydown',\n (event) => {\n // We only care about <-\n if (event.which !== 37) {\n return;\n }\n\n // Prevent seek\n event.preventDefault();\n event.stopPropagation();\n\n // Show the respective menu\n showMenuPanel.call(this, 'home', true);\n },\n false,\n );\n\n // Go back via button click\n on.call(this, backButton, 'click', () => {\n showMenuPanel.call(this, 'home', false);\n });\n\n // Add to pane\n pane.appendChild(backButton);\n\n // Menu\n pane.appendChild(\n createElement('div', {\n role: 'menu',\n }),\n );\n\n inner.appendChild(pane);\n\n this.elements.settings.buttons[type] = menuItem;\n this.elements.settings.panels[type] = pane;\n });\n\n popup.appendChild(inner);\n wrapper.appendChild(popup);\n container.appendChild(wrapper);\n\n this.elements.settings.popup = popup;\n this.elements.settings.menu = wrapper;\n }\n\n // Picture in picture button\n if (control === 'pip' && support.pip) {\n container.appendChild(createButton.call(this, 'pip', defaultAttributes));\n }\n\n // Airplay button\n if (control === 'airplay' && support.airplay) {\n container.appendChild(createButton.call(this, 'airplay', defaultAttributes));\n }\n\n // Download button\n if (control === 'download') {\n const attributes = extend({}, defaultAttributes, {\n element: 'a',\n href: this.download,\n target: '_blank',\n });\n\n // Set download attribute for HTML5 only\n if (this.isHTML5) {\n attributes.download = '';\n }\n\n const { download } = this.config.urls;\n\n if (!is.url(download) && this.isEmbed) {\n extend(attributes, {\n icon: `logo-${this.provider}`,\n label: this.provider,\n });\n }\n\n container.appendChild(createButton.call(this, 'download', attributes));\n }\n\n // Toggle fullscreen button\n if (control === 'fullscreen') {\n container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes));\n }\n });\n\n // Set available quality levels\n if (this.isHTML5) {\n setQualityMenu.call(this, html5.getQualityOptions.call(this));\n }\n\n setSpeedMenu.call(this);\n\n return container;\n },\n\n // Insert controls\n inject() {\n // Sprite\n if (this.config.loadSprite) {\n const icon = controls.getIconUrl.call(this);\n\n // Only load external sprite using AJAX\n if (icon.cors) {\n loadSprite(icon.url, 'sprite-plyr');\n }\n }\n\n // Create a unique ID\n this.id = Math.floor(Math.random() * 10000);\n\n // Null by default\n let container = null;\n this.elements.controls = null;\n\n // Set template properties\n const props = {\n id: this.id,\n seektime: this.config.seekTime,\n title: this.config.title,\n };\n let update = true;\n\n // If function, run it and use output\n if (is.function(this.config.controls)) {\n this.config.controls = this.config.controls.call(this, props);\n }\n\n // Convert falsy controls to empty array (primarily for empty strings)\n if (!this.config.controls) {\n this.config.controls = [];\n }\n\n if (is.element(this.config.controls) || is.string(this.config.controls)) {\n // HTMLElement or Non-empty string passed as the option\n container = this.config.controls;\n } else {\n // Create controls\n container = controls.create.call(this, {\n id: this.id,\n seektime: this.config.seekTime,\n speed: this.speed,\n quality: this.quality,\n captions: captions.getLabel.call(this),\n // TODO: Looping\n // loop: 'None',\n });\n update = false;\n }\n\n // Replace props with their value\n const replace = (input) => {\n let result = input;\n\n Object.entries(props).forEach(([key, value]) => {\n result = replaceAll(result, `{${key}}`, value);\n });\n\n return result;\n };\n\n // Update markup\n if (update) {\n if (is.string(this.config.controls)) {\n container = replace(container);\n }\n }\n\n // Controls container\n let target;\n\n // Inject to custom location\n if (is.string(this.config.selectors.controls.container)) {\n target = document.querySelector(this.config.selectors.controls.container);\n }\n\n // Inject into the container by default\n if (!is.element(target)) {\n target = this.elements.container;\n }\n\n // Inject controls HTML (needs to be before captions, hence \"afterbegin\")\n const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML';\n target[insertMethod]('afterbegin', container);\n\n // Find the elements if need be\n if (!is.element(this.elements.controls)) {\n controls.findElements.call(this);\n }\n\n // Add pressed property to buttons\n if (!is.empty(this.elements.buttons)) {\n const addProperty = (button) => {\n const className = this.config.classNames.controlPressed;\n Object.defineProperty(button, 'pressed', {\n enumerable: true,\n get() {\n return hasClass(button, className);\n },\n set(pressed = false) {\n toggleClass(button, className, pressed);\n },\n });\n };\n\n // Toggle classname when pressed property is set\n Object.values(this.elements.buttons)\n .filter(Boolean)\n .forEach((button) => {\n if (is.array(button) || is.nodeList(button)) {\n Array.from(button).filter(Boolean).forEach(addProperty);\n } else {\n addProperty(button);\n }\n });\n }\n\n // Edge sometimes doesn't finish the paint so force a repaint\n if (browser.isEdge) {\n repaint(target);\n }\n\n // Setup tooltips\n if (this.config.tooltips.controls) {\n const { classNames, selectors } = this.config;\n const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`;\n const labels = getElements.call(this, selector);\n\n Array.from(labels).forEach((label) => {\n toggleClass(label, this.config.classNames.hidden, false);\n toggleClass(label, this.config.classNames.tooltip, true);\n });\n }\n },\n};\n\nexport default controls;\n","// ==========================================================================\n// URL utils\n// ==========================================================================\n\nimport is from './is';\n\n/**\n * Parse a string to a URL object\n * @param {String} input - the URL to be parsed\n * @param {Boolean} safe - failsafe parsing\n */\nexport function parseUrl(input, safe = true) {\n let url = input;\n\n if (safe) {\n const parser = document.createElement('a');\n parser.href = url;\n url = parser.href;\n }\n\n try {\n return new URL(url);\n } catch (_) {\n return null;\n }\n}\n\n// Convert object to URLSearchParams\nexport function buildUrlParams(input) {\n const params = new URLSearchParams();\n\n if (is.object(input)) {\n Object.entries(input).forEach(([key, value]) => {\n params.set(key, value);\n });\n }\n\n return params;\n}\n","// ==========================================================================\n// Plyr Captions\n// TODO: Create as class\n// ==========================================================================\n\nimport controls from './controls';\nimport support from './support';\nimport { dedupe } from './utils/arrays';\nimport browser from './utils/browser';\nimport {\n createElement,\n emptyElement,\n getAttributesFromSelector,\n insertAfter,\n removeElement,\n toggleClass,\n} from './utils/elements';\nimport { on, triggerEvent } from './utils/events';\nimport fetch from './utils/fetch';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport { getHTML } from './utils/strings';\nimport { parseUrl } from './utils/urls';\n\nconst captions = {\n // Setup captions\n setup() {\n // Requires UI support\n if (!this.supported.ui) {\n return;\n }\n\n // Only Vimeo and HTML5 video supported at this point\n if (!this.isVideo || this.isYouTube || (this.isHTML5 && !support.textTracks)) {\n // Clear menu and hide\n if (\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n this.config.settings.includes('captions')\n ) {\n controls.setCaptionsMenu.call(this);\n }\n\n return;\n }\n\n // Inject the container\n if (!is.element(this.elements.captions)) {\n this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions));\n\n insertAfter(this.elements.captions, this.elements.wrapper);\n }\n\n // Fix IE captions if CORS is used\n // Fetch captions and inject as blobs instead (data URIs not supported!)\n if (browser.isIE && window.URL) {\n const elements = this.media.querySelectorAll('track');\n\n Array.from(elements).forEach((track) => {\n const src = track.getAttribute('src');\n const url = parseUrl(src);\n\n if (\n url !== null &&\n url.hostname !== window.location.href.hostname &&\n ['http:', 'https:'].includes(url.protocol)\n ) {\n fetch(src, 'blob')\n .then((blob) => {\n track.setAttribute('src', window.URL.createObjectURL(blob));\n })\n .catch(() => {\n removeElement(track);\n });\n }\n });\n }\n\n // Get and set initial data\n // The \"preferred\" options are not realized unless / until the wanted language has a match\n // * languages: Array of user's browser languages.\n // * language: The language preferred by user settings or config\n // * active: The state preferred by user settings or config\n // * toggled: The real captions state\n\n const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en'];\n const languages = dedupe(browserLanguages.map((language) => language.split('-')[0]));\n let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase();\n\n // Use first browser language when language is 'auto'\n if (language === 'auto') {\n [language] = languages;\n }\n\n let active = this.storage.get('captions');\n if (!is.boolean(active)) {\n ({ active } = this.config.captions);\n }\n\n Object.assign(this.captions, {\n toggled: false,\n active,\n language,\n languages,\n });\n\n // Watch changes to textTracks and update captions menu\n if (this.isHTML5) {\n const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack';\n on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this));\n }\n\n // Update available languages in list next tick (the event must not be triggered before the listeners)\n setTimeout(captions.update.bind(this), 0);\n },\n\n // Update available language options in settings based on tracks\n update() {\n const tracks = captions.getTracks.call(this, true);\n // Get the wanted language\n const { active, language, meta, currentTrackNode } = this.captions;\n const languageExists = Boolean(tracks.find((track) => track.language === language));\n\n // Handle tracks (add event listener and \"pseudo\"-default)\n if (this.isHTML5 && this.isVideo) {\n tracks\n .filter((track) => !meta.get(track))\n .forEach((track) => {\n this.debug.log('Track added', track);\n\n // Attempt to store if the original dom element was \"default\"\n meta.set(track, {\n default: track.mode === 'showing',\n });\n\n // Turn off native caption rendering to avoid double captions\n // Note: mode='hidden' forces a track to download. To ensure every track\n // isn't downloaded at once, only 'showing' tracks should be reassigned\n // eslint-disable-next-line no-param-reassign\n if (track.mode === 'showing') {\n // eslint-disable-next-line no-param-reassign\n track.mode = 'hidden';\n }\n\n // Add event listener for cue changes\n on.call(this, track, 'cuechange', () => captions.updateCues.call(this));\n });\n }\n\n // Update language first time it matches, or if the previous matching track was removed\n if ((languageExists && this.language !== language) || !tracks.includes(currentTrackNode)) {\n captions.setLanguage.call(this, language);\n captions.toggle.call(this, active && languageExists);\n }\n\n // Enable or disable captions based on track length\n if (this.elements) {\n toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks));\n }\n\n // Update available languages in list\n if (\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n this.config.settings.includes('captions')\n ) {\n controls.setCaptionsMenu.call(this);\n }\n },\n\n // Toggle captions display\n // Used internally for the toggleCaptions method, with the passive option forced to false\n toggle(input, passive = true) {\n // If there's no full support\n if (!this.supported.ui) {\n return;\n }\n\n const { toggled } = this.captions; // Current state\n const activeClass = this.config.classNames.captions.active;\n // Get the next state\n // If the method is called without parameter, toggle based on current value\n const active = is.nullOrUndefined(input) ? !toggled : input;\n\n // Update state and trigger event\n if (active !== toggled) {\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.active = active;\n this.storage.set({ captions: active });\n }\n\n // Force language if the call isn't passive and there is no matching language to toggle to\n if (!this.language && active && !passive) {\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true);\n\n // Override user preferences to avoid switching languages if a matching track is added\n this.captions.language = track.language;\n\n // Set caption, but don't store in localStorage as user preference\n captions.set.call(this, tracks.indexOf(track));\n return;\n }\n\n // Toggle button if it's enabled\n if (this.elements.buttons.captions) {\n this.elements.buttons.captions.pressed = active;\n }\n\n // Add class hook\n toggleClass(this.elements.container, activeClass, active);\n\n this.captions.toggled = active;\n\n // Update settings menu\n controls.updateSetting.call(this, 'captions');\n\n // Trigger event (not used internally)\n triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled');\n }\n\n // Wait for the call stack to clear before setting mode='hidden'\n // on the active track - forcing the browser to download it\n setTimeout(() => {\n if (active && this.captions.toggled) {\n this.captions.currentTrackNode.mode = 'hidden';\n }\n });\n },\n\n // Set captions by track index\n // Used internally for the currentTrack setter with the passive option forced to false\n set(index, passive = true) {\n const tracks = captions.getTracks.call(this);\n\n // Disable captions if setting to -1\n if (index === -1) {\n captions.toggle.call(this, false, passive);\n return;\n }\n\n if (!is.number(index)) {\n this.debug.warn('Invalid caption argument', index);\n return;\n }\n\n if (!(index in tracks)) {\n this.debug.warn('Track not found', index);\n return;\n }\n\n if (this.captions.currentTrack !== index) {\n this.captions.currentTrack = index;\n const track = tracks[index];\n const { language } = track || {};\n\n // Store reference to node for invalidation on remove\n this.captions.currentTrackNode = track;\n\n // Update settings menu\n controls.updateSetting.call(this, 'captions');\n\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.language = language;\n this.storage.set({ language });\n }\n\n // Handle Vimeo captions\n if (this.isVimeo) {\n this.embed.enableTextTrack(language);\n }\n\n // Trigger event\n triggerEvent.call(this, this.media, 'languagechange');\n }\n\n // Show captions\n captions.toggle.call(this, true, passive);\n\n if (this.isHTML5 && this.isVideo) {\n // If we change the active track while a cue is already displayed we need to update it\n captions.updateCues.call(this);\n }\n },\n\n // Set captions by language\n // Used internally for the language setter with the passive option forced to false\n setLanguage(input, passive = true) {\n if (!is.string(input)) {\n this.debug.warn('Invalid language argument', input);\n return;\n }\n // Normalize\n const language = input.toLowerCase();\n this.captions.language = language;\n\n // Set currentTrack\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [language]);\n captions.set.call(this, tracks.indexOf(track), passive);\n },\n\n // Get current valid caption tracks\n // If update is false it will also ignore tracks without metadata\n // This is used to \"freeze\" the language options when captions.update is false\n getTracks(update = false) {\n // Handle media or textTracks missing or null\n const tracks = Array.from((this.media || {}).textTracks || []);\n // For HTML5, use cache instead of current tracks when it exists (if captions.update is false)\n // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata)\n return tracks\n .filter((track) => !this.isHTML5 || update || this.captions.meta.has(track))\n .filter((track) => ['captions', 'subtitles'].includes(track.kind));\n },\n\n // Match tracks based on languages and get the first\n findTrack(languages, force = false) {\n const tracks = captions.getTracks.call(this);\n const sortIsDefault = (track) => Number((this.captions.meta.get(track) || {}).default);\n const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a));\n let track;\n\n languages.every((language) => {\n track = sorted.find((t) => t.language === language);\n return !track; // Break iteration if there is a match\n });\n\n // If no match is found but is required, get first\n return track || (force ? sorted[0] : undefined);\n },\n\n // Get the current track\n getCurrentTrack() {\n return captions.getTracks.call(this)[this.currentTrack];\n },\n\n // Get UI label for track\n getLabel(track) {\n let currentTrack = track;\n\n if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) {\n currentTrack = captions.getCurrentTrack.call(this);\n }\n\n if (is.track(currentTrack)) {\n if (!is.empty(currentTrack.label)) {\n return currentTrack.label;\n }\n\n if (!is.empty(currentTrack.language)) {\n return track.language.toUpperCase();\n }\n\n return i18n.get('enabled', this.config);\n }\n\n return i18n.get('disabled', this.config);\n },\n\n // Update captions using current track's active cues\n // Also optional array argument in case there isn't any track (ex: vimeo)\n updateCues(input) {\n // Requires UI\n if (!this.supported.ui) {\n return;\n }\n\n if (!is.element(this.elements.captions)) {\n this.debug.warn('No captions element to render to');\n return;\n }\n\n // Only accept array or empty input\n if (!is.nullOrUndefined(input) && !Array.isArray(input)) {\n this.debug.warn('updateCues: Invalid input', input);\n return;\n }\n\n let cues = input;\n\n // Get cues from track\n if (!cues) {\n const track = captions.getCurrentTrack.call(this);\n\n cues = Array.from((track || {}).activeCues || [])\n .map((cue) => cue.getCueAsHTML())\n .map(getHTML);\n }\n\n // Set new caption text\n const content = cues.map((cueText) => cueText.trim()).join('\\n');\n const changed = content !== this.elements.captions.innerHTML;\n\n if (changed) {\n // Empty the container and create a new child element\n emptyElement(this.elements.captions);\n const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption));\n caption.innerHTML = content;\n this.elements.captions.appendChild(caption);\n\n // Trigger event\n triggerEvent.call(this, this.media, 'cuechange');\n }\n },\n};\n\nexport default captions;\n","// ==========================================================================\n// Plyr default config\n// ==========================================================================\n\nconst defaults = {\n // Disable\n enabled: true,\n\n // Custom media title\n title: '',\n\n // Logging to console\n debug: false,\n\n // Auto play (if supported)\n autoplay: false,\n\n // Only allow one media playing at once (vimeo only)\n autopause: true,\n\n // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present)\n // TODO: Remove iosNative fullscreen option in favour of this (logic needs work)\n playsinline: true,\n\n // Default time to skip when rewind/fast forward\n seekTime: 10,\n\n // Default volume\n volume: 1,\n muted: false,\n\n // Pass a custom duration\n duration: null,\n\n // Display the media duration on load in the current time position\n // If you have opted to display both duration and currentTime, this is ignored\n displayDuration: true,\n\n // Invert the current time to be a countdown\n invertTime: true,\n\n // Clicking the currentTime inverts it's value to show time left rather than elapsed\n toggleInvert: true,\n\n // Force an aspect ratio\n // The format must be `'w:h'` (e.g. `'16:9'`)\n ratio: null,\n\n // Click video container to play/pause\n clickToPlay: true,\n\n // Auto hide the controls\n hideControls: true,\n\n // Reset to start when playback ended\n resetOnEnd: false,\n\n // Disable the standard context menu\n disableContextMenu: true,\n\n // Sprite (for icons)\n loadSprite: true,\n iconPrefix: 'plyr',\n iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg',\n\n // Blank video (used to prevent errors on source change)\n blankVideo: 'https://cdn.plyr.io/static/blank.mp4',\n\n // Quality default\n quality: {\n default: 576,\n // The options to display in the UI, if available for the source media\n options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240],\n forced: false,\n onChange: null,\n },\n\n // Set loops\n loop: {\n active: false,\n // start: null,\n // end: null,\n },\n\n // Speed default and options to display\n speed: {\n selected: 1,\n // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x)\n options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4],\n },\n\n // Keyboard shortcut settings\n keyboard: {\n focused: true,\n global: false,\n },\n\n // Display tooltips\n tooltips: {\n controls: false,\n seek: true,\n },\n\n // Captions settings\n captions: {\n active: false,\n language: 'auto',\n // Listen to new tracks added after Plyr is initialized.\n // This is needed for streaming captions, but may result in unselectable options\n update: false,\n },\n\n // Fullscreen settings\n fullscreen: {\n enabled: true, // Allow fullscreen?\n fallback: true, // Fallback using full viewport/window\n iosNative: false, // Use the native fullscreen in iOS (disables custom controls)\n // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode\n // Non-ancestors of the player element will be ignored\n // container: null, // defaults to the player element\n },\n\n // Local storage\n storage: {\n enabled: true,\n key: 'plyr',\n },\n\n // Default controls\n controls: [\n 'play-large',\n // 'restart',\n // 'rewind',\n 'play',\n // 'fast-forward',\n 'progress',\n 'current-time',\n // 'duration',\n 'mute',\n 'volume',\n 'captions',\n 'settings',\n 'pip',\n 'airplay',\n // 'download',\n 'fullscreen',\n ],\n settings: ['captions', 'quality', 'speed'],\n\n // Localisation\n i18n: {\n restart: 'Restart',\n rewind: 'Rewind {seektime}s',\n play: 'Play',\n pause: 'Pause',\n fastForward: 'Forward {seektime}s',\n seek: 'Seek',\n seekLabel: '{currentTime} of {duration}',\n played: 'Played',\n buffered: 'Buffered',\n currentTime: 'Current time',\n duration: 'Duration',\n volume: 'Volume',\n mute: 'Mute',\n unmute: 'Unmute',\n enableCaptions: 'Enable captions',\n disableCaptions: 'Disable captions',\n download: 'Download',\n enterFullscreen: 'Enter fullscreen',\n exitFullscreen: 'Exit fullscreen',\n frameTitle: 'Player for {title}',\n captions: 'Captions',\n settings: 'Settings',\n pip: 'PIP',\n menuBack: 'Go back to previous menu',\n speed: 'Speed',\n normal: 'Normal',\n quality: 'Quality',\n loop: 'Loop',\n start: 'Start',\n end: 'End',\n all: 'All',\n reset: 'Reset',\n disabled: 'Disabled',\n enabled: 'Enabled',\n advertisement: 'Ad',\n qualityBadge: {\n 2160: '4K',\n 1440: 'HD',\n 1080: 'HD',\n 720: 'HD',\n 576: 'SD',\n 480: 'SD',\n },\n },\n\n // URLs\n urls: {\n download: null,\n vimeo: {\n sdk: 'https://player.vimeo.com/api/player.js',\n iframe: 'https://player.vimeo.com/video/{0}?{1}',\n api: 'https://vimeo.com/api/oembed.json?url={0}',\n },\n youtube: {\n sdk: 'https://www.youtube.com/iframe_api',\n api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}',\n },\n googleIMA: {\n sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js',\n },\n },\n\n // Custom control listeners\n listeners: {\n seek: null,\n play: null,\n pause: null,\n restart: null,\n rewind: null,\n fastForward: null,\n mute: null,\n volume: null,\n captions: null,\n download: null,\n fullscreen: null,\n pip: null,\n airplay: null,\n speed: null,\n quality: null,\n loop: null,\n language: null,\n },\n\n // Events to watch and bubble\n events: [\n // Events to watch on HTML5 media elements and bubble\n // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events\n 'ended',\n 'progress',\n 'stalled',\n 'playing',\n 'waiting',\n 'canplay',\n 'canplaythrough',\n 'loadstart',\n 'loadeddata',\n 'loadedmetadata',\n 'timeupdate',\n 'volumechange',\n 'play',\n 'pause',\n 'error',\n 'seeking',\n 'seeked',\n 'emptied',\n 'ratechange',\n 'cuechange',\n\n // Custom events\n 'download',\n 'enterfullscreen',\n 'exitfullscreen',\n 'captionsenabled',\n 'captionsdisabled',\n 'languagechange',\n 'controlshidden',\n 'controlsshown',\n 'ready',\n\n // YouTube\n 'statechange',\n\n // Quality\n 'qualitychange',\n\n // Ads\n 'adsloaded',\n 'adscontentpause',\n 'adscontentresume',\n 'adstarted',\n 'adsmidpoint',\n 'adscomplete',\n 'adsallcomplete',\n 'adsimpression',\n 'adsclick',\n ],\n\n // Selectors\n // Change these to match your template if using custom HTML\n selectors: {\n editable: 'input, textarea, select, [contenteditable]',\n container: '.plyr',\n controls: {\n container: null,\n wrapper: '.plyr__controls',\n },\n labels: '[data-plyr]',\n buttons: {\n play: '[data-plyr=\"play\"]',\n pause: '[data-plyr=\"pause\"]',\n restart: '[data-plyr=\"restart\"]',\n rewind: '[data-plyr=\"rewind\"]',\n fastForward: '[data-plyr=\"fast-forward\"]',\n mute: '[data-plyr=\"mute\"]',\n captions: '[data-plyr=\"captions\"]',\n download: '[data-plyr=\"download\"]',\n fullscreen: '[data-plyr=\"fullscreen\"]',\n pip: '[data-plyr=\"pip\"]',\n airplay: '[data-plyr=\"airplay\"]',\n settings: '[data-plyr=\"settings\"]',\n loop: '[data-plyr=\"loop\"]',\n },\n inputs: {\n seek: '[data-plyr=\"seek\"]',\n volume: '[data-plyr=\"volume\"]',\n speed: '[data-plyr=\"speed\"]',\n language: '[data-plyr=\"language\"]',\n quality: '[data-plyr=\"quality\"]',\n },\n display: {\n currentTime: '.plyr__time--current',\n duration: '.plyr__time--duration',\n buffer: '.plyr__progress__buffer',\n loop: '.plyr__progress__loop', // Used later\n volume: '.plyr__volume--display',\n },\n progress: '.plyr__progress',\n captions: '.plyr__captions',\n caption: '.plyr__caption',\n },\n\n // Class hooks added to the player in different states\n classNames: {\n type: 'plyr--{0}',\n provider: 'plyr--{0}',\n video: 'plyr__video-wrapper',\n embed: 'plyr__video-embed',\n videoFixedRatio: 'plyr__video-wrapper--fixed-ratio',\n embedContainer: 'plyr__video-embed__container',\n poster: 'plyr__poster',\n posterEnabled: 'plyr__poster-enabled',\n ads: 'plyr__ads',\n control: 'plyr__control',\n controlPressed: 'plyr__control--pressed',\n playing: 'plyr--playing',\n paused: 'plyr--paused',\n stopped: 'plyr--stopped',\n loading: 'plyr--loading',\n hover: 'plyr--hover',\n tooltip: 'plyr__tooltip',\n cues: 'plyr__cues',\n hidden: 'plyr__sr-only',\n hideControls: 'plyr--hide-controls',\n isIos: 'plyr--is-ios',\n isTouch: 'plyr--is-touch',\n uiSupported: 'plyr--full-ui',\n noTransition: 'plyr--no-transition',\n display: {\n time: 'plyr__time',\n },\n menu: {\n value: 'plyr__menu__value',\n badge: 'plyr__badge',\n open: 'plyr--menu-open',\n },\n captions: {\n enabled: 'plyr--captions-enabled',\n active: 'plyr--captions-active',\n },\n fullscreen: {\n enabled: 'plyr--fullscreen-enabled',\n fallback: 'plyr--fullscreen-fallback',\n },\n pip: {\n supported: 'plyr--pip-supported',\n active: 'plyr--pip-active',\n },\n airplay: {\n supported: 'plyr--airplay-supported',\n active: 'plyr--airplay-active',\n },\n tabFocus: 'plyr__tab-focus',\n previewThumbnails: {\n // Tooltip thumbs\n thumbContainer: 'plyr__preview-thumb',\n thumbContainerShown: 'plyr__preview-thumb--is-shown',\n imageContainer: 'plyr__preview-thumb__image-container',\n timeContainer: 'plyr__preview-thumb__time-container',\n // Scrubbing\n scrubbingContainer: 'plyr__preview-scrubbing',\n scrubbingContainerShown: 'plyr__preview-scrubbing--is-shown',\n },\n },\n\n // Embed attributes\n attributes: {\n embed: {\n provider: 'data-plyr-provider',\n id: 'data-plyr-embed-id',\n hash: 'data-plyr-embed-hash',\n },\n },\n\n // Advertisements plugin\n // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio\n ads: {\n enabled: false,\n publisherId: '',\n tagUrl: '',\n },\n\n // Preview Thumbnails plugin\n previewThumbnails: {\n enabled: false,\n src: '',\n },\n\n // Vimeo plugin\n vimeo: {\n byline: false,\n portrait: false,\n title: false,\n speed: true,\n transparent: false,\n // Custom settings from Plyr\n customControls: true,\n referrerPolicy: null, // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy\n // Whether the owner of the video has a Pro or Business account\n // (which allows us to properly hide controls without CSS hacks, etc)\n premium: false,\n },\n\n // YouTube plugin\n youtube: {\n rel: 0, // No related vids\n showinfo: 0, // Hide info\n iv_load_policy: 3, // Hide annotations\n modestbranding: 1, // Hide logos as much as possible (they still show one in the corner when paused)\n // Custom settings from Plyr\n customControls: true,\n noCookie: false, // Whether to use an alternative version of YouTube without cookies\n },\n};\n\nexport default defaults;\n","// ==========================================================================\n// Plyr states\n// ==========================================================================\n\nexport const pip = {\n active: 'picture-in-picture',\n inactive: 'inline',\n};\n\nexport default { pip };\n","// ==========================================================================\n// Plyr supported types and providers\n// ==========================================================================\n\nexport const providers = {\n html5: 'html5',\n youtube: 'youtube',\n vimeo: 'vimeo',\n};\n\nexport const types = {\n audio: 'audio',\n video: 'video',\n};\n\n/**\n * Get provider by URL\n * @param {String} url\n */\nexport function getProviderByUrl(url) {\n // YouTube\n if (/^(https?:\\/\\/)?(www\\.)?(youtube\\.com|youtube-nocookie\\.com|youtu\\.?be)\\/.+$/.test(url)) {\n return providers.youtube;\n }\n\n // Vimeo\n if (/^https?:\\/\\/player.vimeo.com\\/video\\/\\d{0,9}(?=\\b|\\/)/.test(url)) {\n return providers.vimeo;\n }\n\n return null;\n}\n\nexport default { providers, types };\n","// ==========================================================================\n// Console wrapper\n// ==========================================================================\n\nconst noop = () => {};\n\nexport default class Console {\n constructor(enabled = false) {\n this.enabled = window.console && enabled;\n\n if (this.enabled) {\n this.log('Debugging enabled');\n }\n }\n\n get log() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.log, console) : noop;\n }\n\n get warn() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop;\n }\n\n get error() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.error, console) : noop;\n }\n}\n","// ==========================================================================\n// Fullscreen wrapper\n// https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API#prefixing\n// https://webkit.org/blog/7929/designing-websites-for-iphone-x/\n// ==========================================================================\n\nimport browser from './utils/browser';\nimport { closest, getElements, hasClass, toggleClass } from './utils/elements';\nimport { on, triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\n\nclass Fullscreen {\n constructor(player) {\n // Keep reference to parent\n this.player = player;\n\n // Get prefix\n this.prefix = Fullscreen.prefix;\n this.property = Fullscreen.property;\n\n // Scroll position\n this.scrollPosition = { x: 0, y: 0 };\n\n // Force the use of 'full window/browser' rather than fullscreen\n this.forceFallback = player.config.fullscreen.fallback === 'force';\n\n // Get the fullscreen element\n // Checks container is an ancestor, defaults to null\n this.player.elements.fullscreen =\n player.config.fullscreen.container && closest(this.player.elements.container, player.config.fullscreen.container);\n\n // Register event listeners\n // Handle event (incase user presses escape etc)\n on.call(\n this.player,\n document,\n this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`,\n () => {\n // TODO: Filter for target??\n this.onChange();\n },\n );\n\n // Fullscreen toggle on double click\n on.call(this.player, this.player.elements.container, 'dblclick', (event) => {\n // Ignore double click in controls\n if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) {\n return;\n }\n\n this.player.listeners.proxy(event, this.toggle, 'fullscreen');\n });\n\n // Tap focus when in fullscreen\n on.call(this, this.player.elements.container, 'keydown', (event) => this.trapFocus(event));\n\n // Update the UI\n this.update();\n\n // this.toggle = this.toggle.bind(this);\n }\n\n // Determine if native supported\n static get native() {\n return !!(\n document.fullscreenEnabled ||\n document.webkitFullscreenEnabled ||\n document.mozFullScreenEnabled ||\n document.msFullscreenEnabled\n );\n }\n\n // If we're actually using native\n get usingNative() {\n return Fullscreen.native && !this.forceFallback;\n }\n\n // Get the prefix for handlers\n static get prefix() {\n // No prefix\n if (is.function(document.exitFullscreen)) {\n return '';\n }\n\n // Check for fullscreen support by vendor prefix\n let value = '';\n const prefixes = ['webkit', 'moz', 'ms'];\n\n prefixes.some((pre) => {\n if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) {\n value = pre;\n return true;\n }\n\n return false;\n });\n\n return value;\n }\n\n static get property() {\n return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen';\n }\n\n // Determine if fullscreen is enabled\n get enabled() {\n return (\n (Fullscreen.native || this.player.config.fullscreen.fallback) &&\n this.player.config.fullscreen.enabled &&\n this.player.supported.ui &&\n this.player.isVideo\n );\n }\n\n // Get active state\n get active() {\n if (!this.enabled) {\n return false;\n }\n\n // Fallback using classname\n if (!Fullscreen.native || this.forceFallback) {\n return hasClass(this.target, this.player.config.classNames.fullscreen.fallback);\n }\n\n const element = !this.prefix\n ? this.target.getRootNode().fullscreenElement\n : this.target.getRootNode()[`${this.prefix}${this.property}Element`];\n\n return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target;\n }\n\n // Get target element\n get target() {\n return browser.isIos && this.player.config.fullscreen.iosNative\n ? this.player.media\n : this.player.elements.fullscreen || this.player.elements.container;\n }\n\n onChange = () => {\n if (!this.enabled) {\n return;\n }\n\n // Update toggle button\n const button = this.player.elements.buttons.fullscreen;\n if (is.element(button)) {\n button.pressed = this.active;\n }\n\n // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up\n const target = this.target === this.player.media ? this.target : this.player.elements.container;\n // Trigger an event\n triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true);\n };\n\n toggleFallback = (toggle = false) => {\n // Store or restore scroll position\n if (toggle) {\n this.scrollPosition = {\n x: window.scrollX || 0,\n y: window.scrollY || 0,\n };\n } else {\n window.scrollTo(this.scrollPosition.x, this.scrollPosition.y);\n }\n\n // Toggle scroll\n document.body.style.overflow = toggle ? 'hidden' : '';\n\n // Toggle class hook\n toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle);\n\n // Force full viewport on iPhone X+\n if (browser.isIos) {\n let viewport = document.head.querySelector('meta[name=\"viewport\"]');\n const property = 'viewport-fit=cover';\n\n // Inject the viewport meta if required\n if (!viewport) {\n viewport = document.createElement('meta');\n viewport.setAttribute('name', 'viewport');\n }\n\n // Check if the property already exists\n const hasProperty = is.string(viewport.content) && viewport.content.includes(property);\n\n if (toggle) {\n this.cleanupViewport = !hasProperty;\n\n if (!hasProperty) {\n viewport.content += `,${property}`;\n }\n } else if (this.cleanupViewport) {\n viewport.content = viewport.content\n .split(',')\n .filter((part) => part.trim() !== property)\n .join(',');\n }\n }\n\n // Toggle button and fire events\n this.onChange();\n };\n\n // Trap focus inside container\n trapFocus = (event) => {\n // Bail if iOS, not active, not the tab key\n if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) {\n return;\n }\n\n // Get the current focused element\n const focused = document.activeElement;\n const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]');\n const [first] = focusable;\n const last = focusable[focusable.length - 1];\n\n if (focused === last && !event.shiftKey) {\n // Move focus to first element that can be tabbed if Shift isn't used\n first.focus();\n event.preventDefault();\n } else if (focused === first && event.shiftKey) {\n // Move focus to last element that can be tabbed if Shift is used\n last.focus();\n event.preventDefault();\n }\n };\n\n // Update UI\n update = () => {\n if (this.enabled) {\n let mode;\n\n if (this.forceFallback) {\n mode = 'Fallback (forced)';\n } else if (Fullscreen.native) {\n mode = 'Native';\n } else {\n mode = 'Fallback';\n }\n\n this.player.debug.log(`${mode} fullscreen enabled`);\n } else {\n this.player.debug.log('Fullscreen not supported and fallback disabled');\n }\n\n // Add styling hook to show button\n toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled);\n };\n\n // Make an element fullscreen\n enter = () => {\n if (!this.enabled) {\n return;\n }\n\n // iOS native fullscreen doesn't need the request step\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n if (this.player.isVimeo) {\n this.player.embed.requestFullscreen();\n } else {\n this.target.webkitEnterFullscreen();\n }\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(true);\n } else if (!this.prefix) {\n this.target.requestFullscreen({ navigationUI: 'hide' });\n } else if (!is.empty(this.prefix)) {\n this.target[`${this.prefix}Request${this.property}`]();\n }\n };\n\n // Bail from fullscreen\n exit = () => {\n if (!this.enabled) {\n return;\n }\n\n // iOS native fullscreen\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n this.target.webkitExitFullscreen();\n silencePromise(this.player.play());\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(false);\n } else if (!this.prefix) {\n (document.cancelFullScreen || document.exitFullscreen).call(document);\n } else if (!is.empty(this.prefix)) {\n const action = this.prefix === 'moz' ? 'Cancel' : 'Exit';\n document[`${this.prefix}${action}${this.property}`]();\n }\n };\n\n // Toggle state\n toggle = () => {\n if (!this.active) {\n this.enter();\n } else {\n this.exit();\n }\n };\n}\n\nexport default Fullscreen;\n","// ==========================================================================\n// Load image avoiding xhr/fetch CORS issues\n// Server status can't be obtained this way unfortunately, so this uses \"naturalWidth\" to determine if the image has loaded\n// By default it checks if it is at least 1px, but you can add a second argument to change this\n// ==========================================================================\n\nexport default function loadImage(src, minWidth = 1) {\n return new Promise((resolve, reject) => {\n const image = new Image();\n\n const handler = () => {\n delete image.onload;\n delete image.onerror;\n (image.naturalWidth >= minWidth ? resolve : reject)(image);\n };\n\n Object.assign(image, { onload: handler, onerror: handler, src });\n });\n}\n","// ==========================================================================\n// Plyr UI\n// ==========================================================================\n\nimport captions from './captions';\nimport controls from './controls';\nimport support from './support';\nimport browser from './utils/browser';\nimport { getElement, toggleClass } from './utils/elements';\nimport { ready, triggerEvent } from './utils/events';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport loadImage from './utils/load-image';\n\nconst ui = {\n addStyleHook() {\n toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);\n toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);\n },\n\n // Toggle native HTML5 media controls\n toggleNativeControls(toggle = false) {\n if (toggle && this.isHTML5) {\n this.media.setAttribute('controls', '');\n } else {\n this.media.removeAttribute('controls');\n }\n },\n\n // Setup the UI\n build() {\n // Re-attach media element listeners\n // TODO: Use event bubbling?\n this.listeners.media();\n\n // Don't setup interface if no support\n if (!this.supported.ui) {\n this.debug.warn(`Basic support only for ${this.provider} ${this.type}`);\n\n // Restore native controls\n ui.toggleNativeControls.call(this, true);\n\n // Bail\n return;\n }\n\n // Inject custom controls if not present\n if (!is.element(this.elements.controls)) {\n // Inject custom controls\n controls.inject.call(this);\n\n // Re-attach control listeners\n this.listeners.controls();\n }\n\n // Remove native controls\n ui.toggleNativeControls.call(this);\n\n // Setup captions for HTML5\n if (this.isHTML5) {\n captions.setup.call(this);\n }\n\n // Reset volume\n this.volume = null;\n\n // Reset mute state\n this.muted = null;\n\n // Reset loop state\n this.loop = null;\n\n // Reset quality setting\n this.quality = null;\n\n // Reset speed\n this.speed = null;\n\n // Reset volume display\n controls.updateVolume.call(this);\n\n // Reset time display\n controls.timeUpdate.call(this);\n\n // Reset duration display\n controls.durationUpdate.call(this);\n\n // Update the UI\n ui.checkPlaying.call(this);\n\n // Check for picture-in-picture support\n toggleClass(\n this.elements.container,\n this.config.classNames.pip.supported,\n support.pip && this.isHTML5 && this.isVideo,\n );\n\n // Check for airplay support\n toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5);\n\n // Add iOS class\n toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos);\n\n // Add touch class\n toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch);\n\n // Ready for API calls\n this.ready = true;\n\n // Ready event at end of execution stack\n setTimeout(() => {\n triggerEvent.call(this, this.media, 'ready');\n }, 0);\n\n // Set the title\n ui.setTitle.call(this);\n\n // Assure the poster image is set, if the property was added before the element was created\n if (this.poster) {\n ui.setPoster.call(this, this.poster, false).catch(() => {});\n }\n\n // Manually set the duration if user has overridden it.\n // The event listeners for it doesn't get called if preload is disabled (#701)\n if (this.config.duration) {\n controls.durationUpdate.call(this);\n }\n },\n\n // Setup aria attribute for play and iframe title\n setTitle() {\n // Find the current text\n let label = i18n.get('play', this.config);\n\n // If there's a media title set, use that for the label\n if (is.string(this.config.title) && !is.empty(this.config.title)) {\n label += `, ${this.config.title}`;\n }\n\n // If there's a play button, set label\n Array.from(this.elements.buttons.play || []).forEach((button) => {\n button.setAttribute('aria-label', label);\n });\n\n // Set iframe title\n // https://github.com/sampotts/plyr/issues/124\n if (this.isEmbed) {\n const iframe = getElement.call(this, 'iframe');\n\n if (!is.element(iframe)) {\n return;\n }\n\n // Default to media type\n const title = !is.empty(this.config.title) ? this.config.title : 'video';\n const format = i18n.get('frameTitle', this.config);\n\n iframe.setAttribute('title', format.replace('{title}', title));\n }\n },\n\n // Toggle poster\n togglePoster(enable) {\n toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);\n },\n\n // Set the poster image (async)\n // Used internally for the poster setter, with the passive option forced to false\n setPoster(poster, passive = true) {\n // Don't override if call is passive\n if (passive && this.poster) {\n return Promise.reject(new Error('Poster already set'));\n }\n\n // Set property synchronously to respect the call order\n this.media.setAttribute('data-poster', poster);\n\n // Show the poster\n this.elements.poster.removeAttribute('hidden');\n\n // Wait until ui is ready\n return (\n ready\n .call(this)\n // Load image\n .then(() => loadImage(poster))\n .catch((error) => {\n // Hide poster on error unless it's been set by another call\n if (poster === this.poster) {\n ui.togglePoster.call(this, false);\n }\n // Rethrow\n throw error;\n })\n .then(() => {\n // Prevent race conditions\n if (poster !== this.poster) {\n throw new Error('setPoster cancelled by later call to setPoster');\n }\n })\n .then(() => {\n Object.assign(this.elements.poster.style, {\n backgroundImage: `url('${poster}')`,\n // Reset backgroundSize as well (since it can be set to \"cover\" for padded thumbnails for youtube)\n backgroundSize: '',\n });\n\n ui.togglePoster.call(this, true);\n\n return poster;\n })\n );\n },\n\n // Check playing state\n checkPlaying(event) {\n // Class hooks\n toggleClass(this.elements.container, this.config.classNames.playing, this.playing);\n toggleClass(this.elements.container, this.config.classNames.paused, this.paused);\n toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped);\n\n // Set state\n Array.from(this.elements.buttons.play || []).forEach((target) => {\n Object.assign(target, { pressed: this.playing });\n target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config));\n });\n\n // Only update controls on non timeupdate events\n if (is.event(event) && event.type === 'timeupdate') {\n return;\n }\n\n // Toggle controls\n ui.toggleControls.call(this);\n },\n\n // Check if media is loading\n checkLoading(event) {\n this.loading = ['stalled', 'waiting'].includes(event.type);\n\n // Clear timer\n clearTimeout(this.timers.loading);\n\n // Timer to prevent flicker when seeking\n this.timers.loading = setTimeout(\n () => {\n // Update progress bar loading class state\n toggleClass(this.elements.container, this.config.classNames.loading, this.loading);\n\n // Update controls visibility\n ui.toggleControls.call(this);\n },\n this.loading ? 250 : 0,\n );\n },\n\n // Toggle controls based on state and `force` argument\n toggleControls(force) {\n const { controls: controlsElement } = this.elements;\n\n if (controlsElement && this.config.hideControls) {\n // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.)\n const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now();\n\n // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide\n this.toggleControls(\n Boolean(\n force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek,\n ),\n );\n }\n },\n\n // Migrate any custom properties from the media to the parent\n migrateStyles() {\n // Loop through values (as they are the keys when the object is spread 🤔)\n Object.values({ ...this.media.style })\n // We're only fussed about Plyr specific properties\n .filter((key) => !is.empty(key) && is.string(key) && key.startsWith('--plyr'))\n .forEach((key) => {\n // Set on the container\n this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key));\n\n // Clean up from media element\n this.media.style.removeProperty(key);\n });\n\n // Remove attribute if empty\n if (is.empty(this.media.style)) {\n this.media.removeAttribute('style');\n }\n },\n};\n\nexport default ui;\n","// ==========================================================================\n// Plyr Event Listeners\n// ==========================================================================\n\nimport controls from './controls';\nimport ui from './ui';\nimport { repaint } from './utils/animation';\nimport browser from './utils/browser';\nimport { getElement, getElements, matches, toggleClass } from './utils/elements';\nimport { off, on, once, toggleListener, triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\nimport { getAspectRatio, getViewportSize, supportsCSS } from './utils/style';\n\nclass Listeners {\n constructor(player) {\n this.player = player;\n this.lastKey = null;\n this.focusTimer = null;\n this.lastKeyDown = null;\n\n this.handleKey = this.handleKey.bind(this);\n this.toggleMenu = this.toggleMenu.bind(this);\n this.setTabFocus = this.setTabFocus.bind(this);\n this.firstTouch = this.firstTouch.bind(this);\n }\n\n // Handle key presses\n handleKey(event) {\n const { player } = this;\n const { elements } = player;\n const code = event.keyCode ? event.keyCode : event.which;\n const pressed = event.type === 'keydown';\n const repeat = pressed && code === this.lastKey;\n\n // Bail if a modifier key is set\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {\n return;\n }\n\n // If the event is bubbled from the media element\n // Firefox doesn't get the keycode for whatever reason\n if (!is.number(code)) {\n return;\n }\n\n // Seek by the number keys\n const seekByKey = () => {\n // Divide the max duration into 10th's and times by the number value\n player.currentTime = (player.duration / 10) * (code - 48);\n };\n\n // Handle the key on keydown\n // Reset on keyup\n if (pressed) {\n // Check focused element\n // and if the focused element is not editable (e.g. text input)\n // and any that accept key input http://webaim.org/techniques/keyboard/\n const focused = document.activeElement;\n if (is.element(focused)) {\n const { editable } = player.config.selectors;\n const { seek } = elements.inputs;\n\n if (focused !== seek && matches(focused, editable)) {\n return;\n }\n\n if (event.which === 32 && matches(focused, 'button, [role^=\"menuitem\"]')) {\n return;\n }\n }\n\n // Which keycodes should we prevent default\n const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79];\n\n // If the code is found prevent default (e.g. prevent scrolling for arrows)\n if (preventDefault.includes(code)) {\n event.preventDefault();\n event.stopPropagation();\n }\n\n switch (code) {\n case 48:\n case 49:\n case 50:\n case 51:\n case 52:\n case 53:\n case 54:\n case 55:\n case 56:\n case 57:\n // 0-9\n if (!repeat) {\n seekByKey();\n }\n break;\n\n case 32:\n case 75:\n // Space and K key\n if (!repeat) {\n silencePromise(player.togglePlay());\n }\n break;\n\n case 38:\n // Arrow up\n player.increaseVolume(0.1);\n break;\n\n case 40:\n // Arrow down\n player.decreaseVolume(0.1);\n break;\n\n case 77:\n // M key\n if (!repeat) {\n player.muted = !player.muted;\n }\n break;\n\n case 39:\n // Arrow forward\n player.forward();\n break;\n\n case 37:\n // Arrow back\n player.rewind();\n break;\n\n case 70:\n // F key\n player.fullscreen.toggle();\n break;\n\n case 67:\n // C key\n if (!repeat) {\n player.toggleCaptions();\n }\n break;\n\n case 76:\n // L key\n player.loop = !player.loop;\n break;\n\n /* case 73:\n this.setLoop('start');\n break;\n\n case 76:\n this.setLoop();\n break;\n\n case 79:\n this.setLoop('end');\n break; */\n\n default:\n break;\n }\n\n // Escape is handle natively when in full screen\n // So we only need to worry about non native\n if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) {\n player.fullscreen.toggle();\n }\n\n // Store last code for next cycle\n this.lastKey = code;\n } else {\n this.lastKey = null;\n }\n }\n\n // Toggle menu\n toggleMenu(event) {\n controls.toggleMenu.call(this.player, event);\n }\n\n // Device is touch enabled\n firstTouch = () => {\n const { player } = this;\n const { elements } = player;\n\n player.touch = true;\n\n // Add touch class\n toggleClass(elements.container, player.config.classNames.isTouch, true);\n };\n\n setTabFocus = (event) => {\n const { player } = this;\n const { elements } = player;\n\n clearTimeout(this.focusTimer);\n\n // Ignore any key other than tab\n if (event.type === 'keydown' && event.which !== 9) {\n return;\n }\n\n // Store reference to event timeStamp\n if (event.type === 'keydown') {\n this.lastKeyDown = event.timeStamp;\n }\n\n // Remove current classes\n const removeCurrent = () => {\n const className = player.config.classNames.tabFocus;\n const current = getElements.call(player, `.${className}`);\n toggleClass(current, className, false);\n };\n\n // Determine if a key was pressed to trigger this event\n const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20;\n\n // Ignore focus events if a key was pressed prior\n if (event.type === 'focus' && !wasKeyDown) {\n return;\n }\n\n // Remove all current\n removeCurrent();\n\n // Delay the adding of classname until the focus has changed\n // This event fires before the focusin event\n if (event.type !== 'focusout') {\n this.focusTimer = setTimeout(() => {\n const focused = document.activeElement;\n\n // Ignore if current focus element isn't inside the player\n if (!elements.container.contains(focused)) {\n return;\n }\n\n toggleClass(document.activeElement, player.config.classNames.tabFocus, true);\n }, 10);\n }\n };\n\n // Global window & document listeners\n global = (toggle = true) => {\n const { player } = this;\n\n // Keyboard shortcuts\n if (player.config.keyboard.global) {\n toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false);\n }\n\n // Click anywhere closes menu\n toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle);\n\n // Detect touch by events\n once.call(player, document.body, 'touchstart', this.firstTouch);\n\n // Tab focus detection\n toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true);\n };\n\n // Container listeners\n container = () => {\n const { player } = this;\n const { config, elements, timers } = player;\n\n // Keyboard shortcuts\n if (!config.keyboard.global && config.keyboard.focused) {\n on.call(player, elements.container, 'keydown keyup', this.handleKey, false);\n }\n\n // Toggle controls on mouse events and entering fullscreen\n on.call(\n player,\n elements.container,\n 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen',\n (event) => {\n const { controls: controlsElement } = elements;\n\n // Remove button states for fullscreen\n if (controlsElement && event.type === 'enterfullscreen') {\n controlsElement.pressed = false;\n controlsElement.hover = false;\n }\n\n // Show, then hide after a timeout unless another control event occurs\n const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type);\n let delay = 0;\n\n if (show) {\n ui.toggleControls.call(player, true);\n // Use longer timeout for touch devices\n delay = player.touch ? 3000 : 2000;\n }\n\n // Clear timer\n clearTimeout(timers.controls);\n\n // Set new timer to prevent flicker when seeking\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n },\n );\n\n // Set a gutter for Vimeo\n const setGutter = () => {\n if (!player.isVimeo || player.config.vimeo.premium) {\n return;\n }\n\n const target = elements.wrapper;\n const { active } = player.fullscreen;\n const [videoWidth, videoHeight] = getAspectRatio.call(player);\n const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`);\n\n // If not active, remove styles\n if (!active) {\n if (useNativeAspectRatio) {\n target.style.width = null;\n target.style.height = null;\n } else {\n target.style.maxWidth = null;\n target.style.margin = null;\n }\n return;\n }\n\n // Determine which dimension will overflow and constrain view\n const [viewportWidth, viewportHeight] = getViewportSize();\n const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight;\n\n if (useNativeAspectRatio) {\n target.style.width = overflow ? 'auto' : '100%';\n target.style.height = overflow ? '100%' : 'auto';\n } else {\n target.style.maxWidth = overflow ? `${(viewportHeight / videoHeight) * videoWidth}px` : null;\n target.style.margin = overflow ? '0 auto' : null;\n }\n };\n\n // Handle resizing\n const resized = () => {\n clearTimeout(timers.resized);\n timers.resized = setTimeout(setGutter, 50);\n };\n\n on.call(player, elements.container, 'enterfullscreen exitfullscreen', (event) => {\n const { target } = player.fullscreen;\n\n // Ignore events not from target\n if (target !== elements.container) {\n return;\n }\n\n // If it's not an embed and no ratio specified\n if (!player.isEmbed && is.empty(player.config.ratio)) {\n return;\n }\n\n // Set Vimeo gutter\n setGutter();\n\n // Watch for resizes\n const method = event.type === 'enterfullscreen' ? on : off;\n method.call(player, window, 'resize', resized);\n });\n };\n\n // Listen for media events\n media = () => {\n const { player } = this;\n const { elements } = player;\n\n // Time change on media\n on.call(player, player.media, 'timeupdate seeking seeked', (event) => controls.timeUpdate.call(player, event));\n\n // Display duration\n on.call(player, player.media, 'durationchange loadeddata loadedmetadata', (event) =>\n controls.durationUpdate.call(player, event),\n );\n\n // Handle the media finishing\n on.call(player, player.media, 'ended', () => {\n // Show poster on end\n if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) {\n // Restart\n player.restart();\n\n // Call pause otherwise IE11 will start playing the video again\n player.pause();\n }\n });\n\n // Check for buffer progress\n on.call(player, player.media, 'progress playing seeking seeked', (event) =>\n controls.updateProgress.call(player, event),\n );\n\n // Handle volume changes\n on.call(player, player.media, 'volumechange', (event) => controls.updateVolume.call(player, event));\n\n // Handle play/pause\n on.call(player, player.media, 'playing play pause ended emptied timeupdate', (event) =>\n ui.checkPlaying.call(player, event),\n );\n\n // Loading state\n on.call(player, player.media, 'waiting canplay seeked playing', (event) => ui.checkLoading.call(player, event));\n\n // Click video\n if (player.supported.ui && player.config.clickToPlay && !player.isAudio) {\n // Re-fetch the wrapper\n const wrapper = getElement.call(player, `.${player.config.classNames.video}`);\n\n // Bail if there's no wrapper (this should never happen)\n if (!is.element(wrapper)) {\n return;\n }\n\n // On click play, pause or restart\n on.call(player, elements.container, 'click', (event) => {\n const targets = [elements.container, wrapper];\n\n // Ignore if click if not container or in video wrapper\n if (!targets.includes(event.target) && !wrapper.contains(event.target)) {\n return;\n }\n\n // Touch devices will just show controls (if hidden)\n if (player.touch && player.config.hideControls) {\n return;\n }\n\n if (player.ended) {\n this.proxy(event, player.restart, 'restart');\n this.proxy(\n event,\n () => {\n silencePromise(player.play());\n },\n 'play',\n );\n } else {\n this.proxy(\n event,\n () => {\n silencePromise(player.togglePlay());\n },\n 'play',\n );\n }\n });\n }\n\n // Disable right click\n if (player.supported.ui && player.config.disableContextMenu) {\n on.call(\n player,\n elements.wrapper,\n 'contextmenu',\n (event) => {\n event.preventDefault();\n },\n false,\n );\n }\n\n // Volume change\n on.call(player, player.media, 'volumechange', () => {\n // Save to storage\n player.storage.set({\n volume: player.volume,\n muted: player.muted,\n });\n });\n\n // Speed change\n on.call(player, player.media, 'ratechange', () => {\n // Update UI\n controls.updateSetting.call(player, 'speed');\n\n // Save to storage\n player.storage.set({ speed: player.speed });\n });\n\n // Quality change\n on.call(player, player.media, 'qualitychange', (event) => {\n // Update UI\n controls.updateSetting.call(player, 'quality', null, event.detail.quality);\n });\n\n // Update download link when ready and if quality changes\n on.call(player, player.media, 'ready qualitychange', () => {\n controls.setDownloadUrl.call(player);\n });\n\n // Proxy events to container\n // Bubble up key events for Edge\n const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' ');\n\n on.call(player, player.media, proxyEvents, (event) => {\n let { detail = {} } = event;\n\n // Get error details from media\n if (event.type === 'error') {\n detail = player.media.error;\n }\n\n triggerEvent.call(player, elements.container, event.type, true, detail);\n });\n };\n\n // Run default and custom handlers\n proxy = (event, defaultHandler, customHandlerKey) => {\n const { player } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n let returned = true;\n\n // Execute custom handler\n if (hasCustomHandler) {\n returned = customHandler.call(player, event);\n }\n\n // Only call default handler if not prevented in custom handler\n if (returned !== false && is.function(defaultHandler)) {\n defaultHandler.call(player, event);\n }\n };\n\n // Trigger custom and default handlers\n bind = (element, type, defaultHandler, customHandlerKey, passive = true) => {\n const { player } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n\n on.call(\n player,\n element,\n type,\n (event) => this.proxy(event, defaultHandler, customHandlerKey),\n passive && !hasCustomHandler,\n );\n };\n\n // Listen for control events\n controls = () => {\n const { player } = this;\n const { elements } = player;\n // IE doesn't support input event, so we fallback to change\n const inputEvent = browser.isIE ? 'change' : 'input';\n\n // Play/pause toggle\n if (elements.buttons.play) {\n Array.from(elements.buttons.play).forEach((button) => {\n this.bind(\n button,\n 'click',\n () => {\n silencePromise(player.togglePlay());\n },\n 'play',\n );\n });\n }\n\n // Pause\n this.bind(elements.buttons.restart, 'click', player.restart, 'restart');\n\n // Rewind\n this.bind(\n elements.buttons.rewind,\n 'click',\n () => {\n // Record seek time so we can prevent hiding controls for a few seconds after rewind\n player.lastSeekTime = Date.now();\n player.rewind();\n },\n 'rewind',\n );\n\n // Rewind\n this.bind(\n elements.buttons.fastForward,\n 'click',\n () => {\n // Record seek time so we can prevent hiding controls for a few seconds after fast forward\n player.lastSeekTime = Date.now();\n player.forward();\n },\n 'fastForward',\n );\n\n // Mute toggle\n this.bind(\n elements.buttons.mute,\n 'click',\n () => {\n player.muted = !player.muted;\n },\n 'mute',\n );\n\n // Captions toggle\n this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions());\n\n // Download\n this.bind(\n elements.buttons.download,\n 'click',\n () => {\n triggerEvent.call(player, player.media, 'download');\n },\n 'download',\n );\n\n // Fullscreen toggle\n this.bind(\n elements.buttons.fullscreen,\n 'click',\n () => {\n player.fullscreen.toggle();\n },\n 'fullscreen',\n );\n\n // Picture-in-Picture\n this.bind(\n elements.buttons.pip,\n 'click',\n () => {\n player.pip = 'toggle';\n },\n 'pip',\n );\n\n // Airplay\n this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay');\n\n // Settings menu - click toggle\n this.bind(\n elements.buttons.settings,\n 'click',\n (event) => {\n // Prevent the document click listener closing the menu\n event.stopPropagation();\n event.preventDefault();\n\n controls.toggleMenu.call(player, event);\n },\n null,\n false,\n ); // Can't be passive as we're preventing default\n\n // Settings menu - keyboard toggle\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n this.bind(\n elements.buttons.settings,\n 'keyup',\n (event) => {\n const code = event.which;\n\n // We only care about space and return\n if (![13, 32].includes(code)) {\n return;\n }\n\n // Because return triggers a click anyway, all we need to do is set focus\n if (code === 13) {\n controls.focusFirstMenuItem.call(player, null, true);\n return;\n }\n\n // Prevent scroll\n event.preventDefault();\n\n // Prevent playing video (Firefox)\n event.stopPropagation();\n\n // Toggle menu\n controls.toggleMenu.call(player, event);\n },\n null,\n false, // Can't be passive as we're preventing default\n );\n\n // Escape closes menu\n this.bind(elements.settings.menu, 'keydown', (event) => {\n if (event.which === 27) {\n controls.toggleMenu.call(player, event);\n }\n });\n\n // Set range input alternative \"value\", which matches the tooltip time (#954)\n this.bind(elements.inputs.seek, 'mousedown mousemove', (event) => {\n const rect = elements.progress.getBoundingClientRect();\n const percent = (100 / rect.width) * (event.pageX - rect.left);\n event.currentTarget.setAttribute('seek-value', percent);\n });\n\n // Pause while seeking\n this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', (event) => {\n const seek = event.currentTarget;\n const code = event.keyCode ? event.keyCode : event.which;\n const attribute = 'play-on-seeked';\n\n if (is.keyboardEvent(event) && code !== 39 && code !== 37) {\n return;\n }\n\n // Record seek time so we can prevent hiding controls for a few seconds after seek\n player.lastSeekTime = Date.now();\n\n // Was playing before?\n const play = seek.hasAttribute(attribute);\n // Done seeking\n const done = ['mouseup', 'touchend', 'keyup'].includes(event.type);\n\n // If we're done seeking and it was playing, resume playback\n if (play && done) {\n seek.removeAttribute(attribute);\n silencePromise(player.play());\n } else if (!done && player.playing) {\n seek.setAttribute(attribute, '');\n player.pause();\n }\n });\n\n // Fix range inputs on iOS\n // Super weird iOS bug where after you interact with an <input type=\"range\">,\n // it takes over further interactions on the page. This is a hack\n if (browser.isIos) {\n const inputs = getElements.call(player, 'input[type=\"range\"]');\n Array.from(inputs).forEach((input) => this.bind(input, inputEvent, (event) => repaint(event.target)));\n }\n\n // Seek\n this.bind(\n elements.inputs.seek,\n inputEvent,\n (event) => {\n const seek = event.currentTarget;\n // If it exists, use seek-value instead of \"value\" for consistency with tooltip time (#954)\n let seekTo = seek.getAttribute('seek-value');\n\n if (is.empty(seekTo)) {\n seekTo = seek.value;\n }\n\n seek.removeAttribute('seek-value');\n\n player.currentTime = (seekTo / seek.max) * player.duration;\n },\n 'seek',\n );\n\n // Seek tooltip\n this.bind(elements.progress, 'mouseenter mouseleave mousemove', (event) =>\n controls.updateSeekTooltip.call(player, event),\n );\n\n // Preview thumbnails plugin\n // TODO: Really need to work on some sort of plug-in wide event bus or pub-sub for this\n this.bind(elements.progress, 'mousemove touchmove', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startMove(event);\n }\n });\n\n // Hide thumbnail preview - on mouse click, mouse leave, and video play/seek. All four are required, e.g., for buffering\n this.bind(elements.progress, 'mouseleave touchend click', () => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endMove(false, true);\n }\n });\n\n // Show scrubbing preview\n this.bind(elements.progress, 'mousedown touchstart', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startScrubbing(event);\n }\n });\n\n this.bind(elements.progress, 'mouseup touchend', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endScrubbing(event);\n }\n });\n\n // Polyfill for lower fill in <input type=\"range\"> for webkit\n if (browser.isWebkit) {\n Array.from(getElements.call(player, 'input[type=\"range\"]')).forEach((element) => {\n this.bind(element, 'input', (event) => controls.updateRangeFill.call(player, event.target));\n });\n }\n\n // Current time invert\n // Only if one time element is used for both currentTime and duration\n if (player.config.toggleInvert && !is.element(elements.display.duration)) {\n this.bind(elements.display.currentTime, 'click', () => {\n // Do nothing if we're at the start\n if (player.currentTime === 0) {\n return;\n }\n\n player.config.invertTime = !player.config.invertTime;\n\n controls.timeUpdate.call(player);\n });\n }\n\n // Volume\n this.bind(\n elements.inputs.volume,\n inputEvent,\n (event) => {\n player.volume = event.target.value;\n },\n 'volume',\n );\n\n // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting)\n this.bind(elements.controls, 'mouseenter mouseleave', (event) => {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n });\n\n // Also update controls.hover state for any non-player children of fullscreen element (as above)\n if (elements.fullscreen) {\n Array.from(elements.fullscreen.children)\n .filter((c) => !c.contains(elements.container))\n .forEach((child) => {\n this.bind(child, 'mouseenter mouseleave', (event) => {\n if (elements.controls) {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }\n });\n });\n }\n\n // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting)\n this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', (event) => {\n elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type);\n });\n\n // Show controls when they receive focus (e.g., when using keyboard tab key)\n this.bind(elements.controls, 'focusin', () => {\n const { config, timers } = player;\n\n // Skip transition to prevent focus from scrolling the parent element\n toggleClass(elements.controls, config.classNames.noTransition, true);\n\n // Toggle\n ui.toggleControls.call(player, true);\n\n // Restore transition\n setTimeout(() => {\n toggleClass(elements.controls, config.classNames.noTransition, false);\n }, 0);\n\n // Delay a little more for mouse users\n const delay = this.touch ? 3000 : 4000;\n\n // Clear timer\n clearTimeout(timers.controls);\n\n // Hide again after delay\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n });\n\n // Mouse wheel for volume\n this.bind(\n elements.inputs.volume,\n 'wheel',\n (event) => {\n // Detect \"natural\" scroll - suppored on OS X Safari only\n // Other browsers on OS X will be inverted until support improves\n const inverted = event.webkitDirectionInvertedFromDevice;\n // Get delta from event. Invert if `inverted` is true\n const [x, y] = [event.deltaX, -event.deltaY].map((value) => (inverted ? -value : value));\n // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta)\n const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y);\n\n // Change the volume by 2%\n player.increaseVolume(direction / 50);\n\n // Don't break page scrolling at max and min\n const { volume } = player.media;\n if ((direction === 1 && volume < 1) || (direction === -1 && volume > 0)) {\n event.preventDefault();\n }\n },\n 'volume',\n false,\n );\n };\n}\n\nexport default Listeners;\n","(function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n define([], factory);\n } else if (typeof exports === 'object') {\n module.exports = factory();\n } else {\n root.loadjs = factory();\n }\n}(this, function() {\n/**\n * Global dependencies.\n * @global {Object} document - DOM\n */\n\nvar devnull = function() {},\n bundleIdCache = {},\n bundleResultCache = {},\n bundleCallbackQueue = {};\n\n\n/**\n * Subscribe to bundle load event.\n * @param {string[]} bundleIds - Bundle ids\n * @param {Function} callbackFn - The callback function\n */\nfunction subscribe(bundleIds, callbackFn) {\n // listify\n bundleIds = bundleIds.push ? bundleIds : [bundleIds];\n\n var depsNotFound = [],\n i = bundleIds.length,\n numWaiting = i,\n fn,\n bundleId,\n r,\n q;\n\n // define callback function\n fn = function (bundleId, pathsNotFound) {\n if (pathsNotFound.length) depsNotFound.push(bundleId);\n\n numWaiting--;\n if (!numWaiting) callbackFn(depsNotFound);\n };\n\n // register callback\n while (i--) {\n bundleId = bundleIds[i];\n\n // execute callback if in result cache\n r = bundleResultCache[bundleId];\n if (r) {\n fn(bundleId, r);\n continue;\n }\n\n // add to callback queue\n q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];\n q.push(fn);\n }\n}\n\n\n/**\n * Publish bundle load event.\n * @param {string} bundleId - Bundle id\n * @param {string[]} pathsNotFound - List of files not found\n */\nfunction publish(bundleId, pathsNotFound) {\n // exit if id isn't defined\n if (!bundleId) return;\n\n var q = bundleCallbackQueue[bundleId];\n\n // cache result\n bundleResultCache[bundleId] = pathsNotFound;\n\n // exit if queue is empty\n if (!q) return;\n\n // empty callback queue\n while (q.length) {\n q[0](bundleId, pathsNotFound);\n q.splice(0, 1);\n }\n}\n\n\n/**\n * Execute callbacks.\n * @param {Object or Function} args - The callback args\n * @param {string[]} depsNotFound - List of dependencies not found\n */\nfunction executeCallbacks(args, depsNotFound) {\n // accept function as argument\n if (args.call) args = {success: args};\n\n // success and error callbacks\n if (depsNotFound.length) (args.error || devnull)(depsNotFound);\n else (args.success || devnull)(args);\n}\n\n\n/**\n * Load individual file.\n * @param {string} path - The file path\n * @param {Function} callbackFn - The callback function\n */\nfunction loadFile(path, callbackFn, args, numTries) {\n var doc = document,\n async = args.async,\n maxTries = (args.numRetries || 0) + 1,\n beforeCallbackFn = args.before || devnull,\n pathname = path.replace(/[\\?|#].*$/, ''),\n pathStripped = path.replace(/^(css|img)!/, ''),\n isLegacyIECss,\n e;\n\n numTries = numTries || 0;\n\n if (/(^css!|\\.css$)/.test(pathname)) {\n // css\n e = doc.createElement('link');\n e.rel = 'stylesheet';\n e.href = pathStripped;\n\n // tag IE9+\n isLegacyIECss = 'hideFocus' in e;\n\n // use preload in IE Edge (to detect load errors)\n if (isLegacyIECss && e.relList) {\n isLegacyIECss = 0;\n e.rel = 'preload';\n e.as = 'style';\n }\n } else if (/(^img!|\\.(png|gif|jpg|svg|webp)$)/.test(pathname)) {\n // image\n e = doc.createElement('img');\n e.src = pathStripped; \n } else {\n // javascript\n e = doc.createElement('script');\n e.src = path;\n e.async = async === undefined ? true : async;\n }\n\n e.onload = e.onerror = e.onbeforeload = function (ev) {\n var result = ev.type[0];\n\n // treat empty stylesheets as failures to get around lack of onerror\n // support in IE9-11\n if (isLegacyIECss) {\n try {\n if (!e.sheet.cssText.length) result = 'e';\n } catch (x) {\n // sheets objects created from load errors don't allow access to\n // `cssText` (unless error is Code:18 SecurityError)\n if (x.code != 18) result = 'e';\n }\n }\n\n // handle retries in case of load failure\n if (result == 'e') {\n // increment counter\n numTries += 1;\n\n // exit function and try again\n if (numTries < maxTries) {\n return loadFile(path, callbackFn, args, numTries);\n }\n } else if (e.rel == 'preload' && e.as == 'style') {\n // activate preloaded stylesheets\n return e.rel = 'stylesheet'; // jshint ignore:line\n }\n \n // execute callback\n callbackFn(path, result, ev.defaultPrevented);\n };\n\n // add to document (unless callback returns `false`)\n if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);\n}\n\n\n/**\n * Load multiple files.\n * @param {string[]} paths - The file paths\n * @param {Function} callbackFn - The callback function\n */\nfunction loadFiles(paths, callbackFn, args) {\n // listify paths\n paths = paths.push ? paths : [paths];\n\n var numWaiting = paths.length,\n x = numWaiting,\n pathsNotFound = [],\n fn,\n i;\n\n // define callback function\n fn = function(path, result, defaultPrevented) {\n // handle error\n if (result == 'e') pathsNotFound.push(path);\n\n // handle beforeload event. If defaultPrevented then that means the load\n // will be blocked (ex. Ghostery/ABP on Safari)\n if (result == 'b') {\n if (defaultPrevented) pathsNotFound.push(path);\n else return;\n }\n\n numWaiting--;\n if (!numWaiting) callbackFn(pathsNotFound);\n };\n\n // load scripts\n for (i=0; i < x; i++) loadFile(paths[i], fn, args);\n}\n\n\n/**\n * Initiate script load and register bundle.\n * @param {(string|string[])} paths - The file paths\n * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success\n * callback or (3) object literal with success/error arguments, numRetries,\n * etc.\n * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object\n * literal with success/error arguments, numRetries, etc.\n */\nfunction loadjs(paths, arg1, arg2) {\n var bundleId,\n args;\n\n // bundleId (if string)\n if (arg1 && arg1.trim) bundleId = arg1;\n\n // args (default is {})\n args = (bundleId ? arg2 : arg1) || {};\n\n // throw error if bundle is already defined\n if (bundleId) {\n if (bundleId in bundleIdCache) {\n throw \"LoadJS\";\n } else {\n bundleIdCache[bundleId] = true;\n }\n }\n\n function loadFn(resolve, reject) {\n loadFiles(paths, function (pathsNotFound) {\n // execute callbacks\n executeCallbacks(args, pathsNotFound);\n \n // resolve Promise\n if (resolve) {\n executeCallbacks({success: resolve, error: reject}, pathsNotFound);\n }\n\n // publish bundle load event\n publish(bundleId, pathsNotFound);\n }, args);\n }\n \n if (args.returnPromise) return new Promise(loadFn);\n else loadFn();\n}\n\n\n/**\n * Execute callbacks when dependencies have been satisfied.\n * @param {(string|string[])} deps - List of bundle ids\n * @param {Object} args - success/error arguments\n */\nloadjs.ready = function ready(deps, args) {\n // subscribe to bundle load event\n subscribe(deps, function (depsNotFound) {\n // execute callbacks\n executeCallbacks(args, depsNotFound);\n });\n\n return loadjs;\n};\n\n\n/**\n * Manually satisfy bundle dependencies.\n * @param {string} bundleId - The bundle id\n */\nloadjs.done = function done(bundleId) {\n publish(bundleId, []);\n};\n\n\n/**\n * Reset loadjs dependencies statuses\n */\nloadjs.reset = function reset() {\n bundleIdCache = {};\n bundleResultCache = {};\n bundleCallbackQueue = {};\n};\n\n\n/**\n * Determine if bundle has already been defined\n * @param String} bundleId - The bundle id\n */\nloadjs.isDefined = function isDefined(bundleId) {\n return bundleId in bundleIdCache;\n};\n\n\n// export\nreturn loadjs;\n\n}));\n","// ==========================================================================\n// Load an external script\n// ==========================================================================\n\nimport loadjs from 'loadjs';\n\nexport default function loadScript(url) {\n return new Promise((resolve, reject) => {\n loadjs(url, {\n success: resolve,\n error: reject,\n });\n });\n}\n","// ==========================================================================\n// Vimeo plugin\n// ==========================================================================\n\nimport captions from '../captions';\nimport controls from '../controls';\nimport ui from '../ui';\nimport { createElement, replaceElement, toggleClass } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport loadScript from '../utils/load-script';\nimport { format, stripHTML } from '../utils/strings';\nimport { roundAspectRatio, setAspectRatio } from '../utils/style';\nimport { buildUrlParams } from '../utils/urls';\n\n// Parse Vimeo ID from URL\nfunction parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n if (is.number(Number(url))) {\n return url;\n }\n\n const regex = /^.*(vimeo.com\\/|video\\/)(\\d+).*/;\n return url.match(regex) ? RegExp.$2 : url;\n}\n\n// Try to extract a hash for private videos from the URL\nfunction parseHash(url) {\n /* This regex matches a hexadecimal hash if given in any of these forms:\n * - [https://player.]vimeo.com/video/{id}/{hash}[?params]\n * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms]\n * - [https://player.]vimeo.com/video/{id}?[params]&h={hash}\n * - video/{id}/{hash}\n * If matched, the hash is available in the named group `hash`\n */\n const regex = /^.*(?:vimeo.com\\/|video\\/)(?:\\d+)(?:\\?.*&*h=|\\/)+(?<hash>[\\d,a-f]+)/;\n const found = url.match(regex);\n\n return found ? found.groups.hash : null;\n}\n\n// Set playback state and trigger change (only on actual change)\nfunction assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nconst vimeo = {\n setup() {\n const player = this;\n\n // Add embed class for responsive\n toggleClass(player.elements.wrapper, player.config.classNames.embed, true);\n\n // Set speed options from config\n player.options.speed = player.config.speed.options;\n\n // Set intial ratio\n setAspectRatio.call(player);\n\n // Load the SDK if not already\n if (!is.object(window.Vimeo)) {\n loadScript(player.config.urls.vimeo.sdk)\n .then(() => {\n vimeo.ready.call(player);\n })\n .catch((error) => {\n player.debug.warn('Vimeo SDK (player.js) failed to load', error);\n });\n } else {\n vimeo.ready.call(player);\n }\n },\n\n // API Ready\n ready() {\n const player = this;\n const config = player.config.vimeo;\n const { premium, referrerPolicy, ...frameParams } = config;\n // Get the source URL or ID\n let source = player.media.getAttribute('src');\n let hash = '';\n // Get from <div> if needed\n if (is.empty(source)) {\n source = player.media.getAttribute(player.config.attributes.embed.id);\n // hash can also be set as attribute on the <div>\n hash = player.media.getAttribute(player.config.attributes.embed.hash);\n } else {\n hash = parseHash(source);\n }\n const hashParam = hash ? { h: hash } : {};\n\n // If the owner has a pro or premium account then we can hide controls etc\n if (premium) {\n Object.assign(frameParams, {\n controls: false,\n sidedock: false,\n });\n }\n\n // Get Vimeo params for the iframe\n const params = buildUrlParams({\n loop: player.config.loop.active,\n autoplay: player.autoplay,\n muted: player.muted,\n gesture: 'media',\n playsinline: !this.config.fullscreen.iosNative,\n // hash has to be added to iframe-URL\n ...hashParam,\n ...frameParams,\n });\n\n const id = parseId(source);\n // Build an iframe\n const iframe = createElement('iframe');\n const src = format(player.config.urls.vimeo.iframe, id, params);\n iframe.setAttribute('src', src);\n iframe.setAttribute('allowfullscreen', '');\n iframe.setAttribute(\n 'allow',\n ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; '),\n );\n\n // Set the referrer policy if required\n if (!is.empty(referrerPolicy)) {\n iframe.setAttribute('referrerPolicy', referrerPolicy);\n }\n\n // Inject the package\n if (premium || !config.customControls) {\n iframe.setAttribute('data-poster', player.poster);\n player.media = replaceElement(iframe, player.media);\n } else {\n const wrapper = createElement('div', {\n class: player.config.classNames.embedContainer,\n 'data-poster': player.poster,\n });\n wrapper.appendChild(iframe);\n player.media = replaceElement(wrapper, player.media);\n }\n\n // Get poster image\n if (!config.customControls) {\n fetch(format(player.config.urls.vimeo.api, src)).then((response) => {\n if (is.empty(response) || !response.thumbnail_url) {\n return;\n }\n\n // Set and show poster\n ui.setPoster.call(player, response.thumbnail_url).catch(() => {});\n });\n }\n\n // Setup instance\n // https://github.com/vimeo/player.js\n player.embed = new window.Vimeo.Player(iframe, {\n autopause: player.config.autopause,\n muted: player.muted,\n });\n\n player.media.paused = true;\n player.media.currentTime = 0;\n\n // Disable native text track rendering\n if (player.supported.ui) {\n player.embed.disableTextTrack();\n }\n\n // Create a faux HTML5 API using the Vimeo API\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n return player.embed.play();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n return player.embed.pause();\n };\n\n player.media.stop = () => {\n player.pause();\n player.currentTime = 0;\n };\n\n // Seeking\n let { currentTime } = player.media;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return currentTime;\n },\n set(time) {\n // Vimeo will automatically play on seek if the video hasn't been played before\n\n // Get current paused state and volume etc\n const { embed, media, paused, volume } = player;\n const restorePause = paused && !embed.hasPlayed;\n\n // Set seeking state and trigger event\n media.seeking = true;\n triggerEvent.call(player, media, 'seeking');\n\n // If paused, mute until seek is complete\n Promise.resolve(restorePause && embed.setVolume(0))\n // Seek\n .then(() => embed.setCurrentTime(time))\n // Restore paused\n .then(() => restorePause && embed.pause())\n // Restore volume\n .then(() => restorePause && embed.setVolume(volume))\n .catch(() => {\n // Do nothing\n });\n },\n });\n\n // Playback speed\n let speed = player.config.speed.selected;\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return speed;\n },\n set(input) {\n player.embed\n .setPlaybackRate(input)\n .then(() => {\n speed = input;\n triggerEvent.call(player, player.media, 'ratechange');\n })\n .catch(() => {\n // Cannot set Playback Rate, Video is probably not on Pro account\n player.options.speed = [1];\n });\n },\n });\n\n // Volume\n let { volume } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n set(input) {\n player.embed.setVolume(input).then(() => {\n volume = input;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n },\n });\n\n // Muted\n let { muted } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : false;\n\n player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => {\n muted = toggle;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n },\n });\n\n // Loop\n let { loop } = player.config;\n Object.defineProperty(player.media, 'loop', {\n get() {\n return loop;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : player.config.loop.active;\n\n player.embed.setLoop(toggle).then(() => {\n loop = toggle;\n });\n },\n });\n\n // Source\n let currentSrc;\n player.embed\n .getVideoUrl()\n .then((value) => {\n currentSrc = value;\n controls.setDownloadUrl.call(player);\n })\n .catch((error) => {\n this.debug.warn(error);\n });\n\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return currentSrc;\n },\n });\n\n // Ended\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n },\n });\n\n // Set aspect ratio based on video size\n Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then((dimensions) => {\n const [width, height] = dimensions;\n player.embed.ratio = roundAspectRatio(width, height);\n setAspectRatio.call(this);\n });\n\n // Set autopause\n player.embed.setAutopause(player.config.autopause).then((state) => {\n player.config.autopause = state;\n });\n\n // Get title\n player.embed.getVideoTitle().then((title) => {\n player.config.title = title;\n ui.setTitle.call(this);\n });\n\n // Get current time\n player.embed.getCurrentTime().then((value) => {\n currentTime = value;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n\n // Get duration\n player.embed.getDuration().then((value) => {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n });\n\n // Get captions\n player.embed.getTextTracks().then((tracks) => {\n player.media.textTracks = tracks;\n captions.setup.call(player);\n });\n\n player.embed.on('cuechange', ({ cues = [] }) => {\n const strippedCues = cues.map((cue) => stripHTML(cue.text));\n captions.updateCues.call(player, strippedCues);\n });\n\n player.embed.on('loaded', () => {\n // Assure state and events are updated on autoplay\n player.embed.getPaused().then((paused) => {\n assurePlaybackState.call(player, !paused);\n if (!paused) {\n triggerEvent.call(player, player.media, 'playing');\n }\n });\n\n if (is.element(player.embed.element) && player.supported.ui) {\n const frame = player.embed.element;\n\n // Fix keyboard focus issues\n // https://github.com/sampotts/plyr/issues/317\n frame.setAttribute('tabindex', -1);\n }\n });\n\n player.embed.on('bufferstart', () => {\n triggerEvent.call(player, player.media, 'waiting');\n });\n\n player.embed.on('bufferend', () => {\n triggerEvent.call(player, player.media, 'playing');\n });\n\n player.embed.on('play', () => {\n assurePlaybackState.call(player, true);\n triggerEvent.call(player, player.media, 'playing');\n });\n\n player.embed.on('pause', () => {\n assurePlaybackState.call(player, false);\n });\n\n player.embed.on('timeupdate', (data) => {\n player.media.seeking = false;\n currentTime = data.seconds;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n\n player.embed.on('progress', (data) => {\n player.media.buffered = data.percent;\n triggerEvent.call(player, player.media, 'progress');\n\n // Check all loaded\n if (parseInt(data.percent, 10) === 1) {\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n\n // Get duration as if we do it before load, it gives an incorrect value\n // https://github.com/sampotts/plyr/issues/891\n player.embed.getDuration().then((value) => {\n if (value !== player.media.duration) {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }\n });\n });\n\n player.embed.on('seeked', () => {\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n });\n\n player.embed.on('ended', () => {\n player.media.paused = true;\n triggerEvent.call(player, player.media, 'ended');\n });\n\n player.embed.on('error', (detail) => {\n player.media.error = detail;\n triggerEvent.call(player, player.media, 'error');\n });\n\n // Rebuild UI\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 0);\n }\n },\n};\n\nexport default vimeo;\n","// ==========================================================================\n// YouTube plugin\n// ==========================================================================\n\nimport ui from '../ui';\nimport { createElement, replaceElement, toggleClass } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport loadImage from '../utils/load-image';\nimport loadScript from '../utils/load-script';\nimport { extend } from '../utils/objects';\nimport { format, generateId } from '../utils/strings';\nimport { roundAspectRatio, setAspectRatio } from '../utils/style';\n\n// Parse YouTube ID from URL\nfunction parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n const regex = /^.*(youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=|&v=)([^#&?]*).*/;\n return url.match(regex) ? RegExp.$2 : url;\n}\n\n// Set playback state and trigger change (only on actual change)\nfunction assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nfunction getHost(config) {\n if (config.noCookie) {\n return 'https://www.youtube-nocookie.com';\n }\n\n if (window.location.protocol === 'http:') {\n return 'http://www.youtube.com';\n }\n\n // Use YouTube's default\n return undefined;\n}\n\nconst youtube = {\n setup() {\n // Add embed class for responsive\n toggleClass(this.elements.wrapper, this.config.classNames.embed, true);\n\n // Setup API\n if (is.object(window.YT) && is.function(window.YT.Player)) {\n youtube.ready.call(this);\n } else {\n // Reference current global callback\n const callback = window.onYouTubeIframeAPIReady;\n\n // Set callback to process queue\n window.onYouTubeIframeAPIReady = () => {\n // Call global callback if set\n if (is.function(callback)) {\n callback();\n }\n\n youtube.ready.call(this);\n };\n\n // Load the SDK\n loadScript(this.config.urls.youtube.sdk).catch((error) => {\n this.debug.warn('YouTube API failed to load', error);\n });\n }\n },\n\n // Get the media title\n getTitle(videoId) {\n const url = format(this.config.urls.youtube.api, videoId);\n\n fetch(url)\n .then((data) => {\n if (is.object(data)) {\n const { title, height, width } = data;\n\n // Set title\n this.config.title = title;\n ui.setTitle.call(this);\n\n // Set aspect ratio\n this.embed.ratio = roundAspectRatio(width, height);\n }\n\n setAspectRatio.call(this);\n })\n .catch(() => {\n // Set aspect ratio\n setAspectRatio.call(this);\n });\n },\n\n // API ready\n ready() {\n const player = this;\n const config = player.config.youtube;\n // Ignore already setup (race condition)\n const currentId = player.media && player.media.getAttribute('id');\n if (!is.empty(currentId) && currentId.startsWith('youtube-')) {\n return;\n }\n\n // Get the source URL or ID\n let source = player.media.getAttribute('src');\n\n // Get from <div> if needed\n if (is.empty(source)) {\n source = player.media.getAttribute(this.config.attributes.embed.id);\n }\n\n // Replace the <iframe> with a <div> due to YouTube API issues\n const videoId = parseId(source);\n const id = generateId(player.provider);\n // Replace media element\n const container = createElement('div', { id, 'data-poster': config.customControls ? player.poster : undefined });\n player.media = replaceElement(container, player.media);\n\n // Only load the poster when using custom controls\n if (config.customControls) {\n const posterSrc = (s) => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`;\n\n // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide)\n loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded\n .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3\n .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists\n .then((image) => ui.setPoster.call(player, image.src))\n .then((src) => {\n // If the image is padded, use background-size \"cover\" instead (like youtube does too with their posters)\n if (!src.includes('maxres')) {\n player.elements.poster.style.backgroundSize = 'cover';\n }\n })\n .catch(() => {});\n }\n\n // Setup instance\n // https://developers.google.com/youtube/iframe_api_reference\n player.embed = new window.YT.Player(player.media, {\n videoId,\n host: getHost(config),\n playerVars: extend(\n {},\n {\n // Autoplay\n autoplay: player.config.autoplay ? 1 : 0,\n // iframe interface language\n hl: player.config.hl,\n // Only show controls if not fully supported or opted out\n controls: player.supported.ui && config.customControls ? 0 : 1,\n // Disable keyboard as we handle it\n disablekb: 1,\n // Allow iOS inline playback\n playsinline: !player.config.fullscreen.iosNative ? 1 : 0,\n // Captions are flaky on YouTube\n cc_load_policy: player.captions.active ? 1 : 0,\n cc_lang_pref: player.config.captions.language,\n // Tracking for stats\n widget_referrer: window ? window.location.href : null,\n },\n config,\n ),\n events: {\n onError(event) {\n // YouTube may fire onError twice, so only handle it once\n if (!player.media.error) {\n const code = event.data;\n // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError\n const message =\n {\n 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.',\n 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.',\n 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.',\n 101: 'The owner of the requested video does not allow it to be played in embedded players.',\n 150: 'The owner of the requested video does not allow it to be played in embedded players.',\n }[code] || 'An unknown error occured';\n\n player.media.error = { code, message };\n\n triggerEvent.call(player, player.media, 'error');\n }\n },\n onPlaybackRateChange(event) {\n // Get the instance\n const instance = event.target;\n\n // Get current speed\n player.media.playbackRate = instance.getPlaybackRate();\n\n triggerEvent.call(player, player.media, 'ratechange');\n },\n onReady(event) {\n // Bail if onReady has already been called. See issue #1108\n if (is.function(player.media.play)) {\n return;\n }\n // Get the instance\n const instance = event.target;\n\n // Get the title\n youtube.getTitle.call(player, videoId);\n\n // Create a faux HTML5 API using the YouTube API\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n instance.playVideo();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n instance.pauseVideo();\n };\n\n player.media.stop = () => {\n instance.stopVideo();\n };\n\n player.media.duration = instance.getDuration();\n player.media.paused = true;\n\n // Seeking\n player.media.currentTime = 0;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return Number(instance.getCurrentTime());\n },\n set(time) {\n // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet).\n if (player.paused && !player.embed.hasPlayed) {\n player.embed.mute();\n }\n\n // Set seeking state and trigger event\n player.media.seeking = true;\n triggerEvent.call(player, player.media, 'seeking');\n\n // Seek after events sent\n instance.seekTo(time);\n },\n });\n\n // Playback speed\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return instance.getPlaybackRate();\n },\n set(input) {\n instance.setPlaybackRate(input);\n },\n });\n\n // Volume\n let { volume } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n set(input) {\n volume = input;\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n },\n });\n\n // Muted\n let { muted } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : muted;\n muted = toggle;\n instance[toggle ? 'mute' : 'unMute']();\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n },\n });\n\n // Source\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return instance.getVideoUrl();\n },\n });\n\n // Ended\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n },\n });\n\n // Get available speeds\n const speeds = instance.getAvailablePlaybackRates();\n // Filter based on config\n player.options.speed = speeds.filter((s) => player.config.speed.options.includes(s));\n\n // Set the tabindex to avoid focus entering iframe\n if (player.supported.ui && config.customControls) {\n player.media.setAttribute('tabindex', -1);\n }\n\n triggerEvent.call(player, player.media, 'timeupdate');\n triggerEvent.call(player, player.media, 'durationchange');\n\n // Reset timer\n clearInterval(player.timers.buffering);\n\n // Setup buffering\n player.timers.buffering = setInterval(() => {\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction();\n\n // Trigger progress only when we actually buffer something\n if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) {\n triggerEvent.call(player, player.media, 'progress');\n }\n\n // Set last buffer point\n player.media.lastBuffered = player.media.buffered;\n\n // Bail if we're at 100%\n if (player.media.buffered === 1) {\n clearInterval(player.timers.buffering);\n\n // Trigger event\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n }, 200);\n\n // Rebuild UI\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 50);\n }\n },\n onStateChange(event) {\n // Get the instance\n const instance = event.target;\n\n // Reset timer\n clearInterval(player.timers.playing);\n\n const seeked = player.media.seeking && [1, 2].includes(event.data);\n\n if (seeked) {\n // Unset seeking and fire seeked event\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n }\n\n // Handle events\n // -1 Unstarted\n // 0 Ended\n // 1 Playing\n // 2 Paused\n // 3 Buffering\n // 5 Video cued\n switch (event.data) {\n case -1:\n // Update scrubber\n triggerEvent.call(player, player.media, 'timeupdate');\n\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction();\n triggerEvent.call(player, player.media, 'progress');\n\n break;\n\n case 0:\n assurePlaybackState.call(player, false);\n\n // YouTube doesn't support loop for a single video, so mimick it.\n if (player.media.loop) {\n // YouTube needs a call to `stopVideo` before playing again\n instance.stopVideo();\n instance.playVideo();\n } else {\n triggerEvent.call(player, player.media, 'ended');\n }\n\n break;\n\n case 1:\n // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet)\n if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) {\n player.media.pause();\n } else {\n assurePlaybackState.call(player, true);\n\n triggerEvent.call(player, player.media, 'playing');\n\n // Poll to get playback progress\n player.timers.playing = setInterval(() => {\n triggerEvent.call(player, player.media, 'timeupdate');\n }, 50);\n\n // Check duration again due to YouTube bug\n // https://github.com/sampotts/plyr/issues/374\n // https://code.google.com/p/gdata-issues/issues/detail?id=8690\n if (player.media.duration !== instance.getDuration()) {\n player.media.duration = instance.getDuration();\n triggerEvent.call(player, player.media, 'durationchange');\n }\n }\n\n break;\n\n case 2:\n // Restore audio (YouTube starts playing on seek if the video hasn't been played yet)\n if (!player.muted) {\n player.embed.unMute();\n }\n assurePlaybackState.call(player, false);\n\n break;\n\n case 3:\n // Trigger waiting event to add loading classes to container as the video buffers.\n triggerEvent.call(player, player.media, 'waiting');\n\n break;\n\n default:\n break;\n }\n\n triggerEvent.call(player, player.elements.container, 'statechange', false, {\n code: event.data,\n });\n },\n },\n });\n },\n};\n\nexport default youtube;\n","// ==========================================================================\n// Plyr Media\n// ==========================================================================\n\nimport html5 from './html5';\nimport vimeo from './plugins/vimeo';\nimport youtube from './plugins/youtube';\nimport { createElement, toggleClass, wrap } from './utils/elements';\n\nconst media = {\n // Setup media\n setup() {\n // If there's no media, bail\n if (!this.media) {\n this.debug.warn('No media element found!');\n return;\n }\n\n // Add type class\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true);\n\n // Add provider class\n toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true);\n\n // Add video class for embeds\n // This will require changes if audio embeds are added\n if (this.isEmbed) {\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true);\n }\n\n // Inject the player wrapper\n if (this.isVideo) {\n // Create the wrapper div\n this.elements.wrapper = createElement('div', {\n class: this.config.classNames.video,\n });\n\n // Wrap the video in a container\n wrap(this.media, this.elements.wrapper);\n\n // Poster image container\n this.elements.poster = createElement('div', {\n class: this.config.classNames.poster,\n });\n\n this.elements.wrapper.appendChild(this.elements.poster);\n }\n\n if (this.isHTML5) {\n html5.setup.call(this);\n } else if (this.isYouTube) {\n youtube.setup.call(this);\n } else if (this.isVimeo) {\n vimeo.setup.call(this);\n }\n },\n};\n\nexport default media;\n","// ==========================================================================\n// Advertisement plugin using Google IMA HTML5 SDK\n// Create an account with our ad partner, vi here:\n// https://www.vi.ai/publisher-video-monetization/\n// ==========================================================================\n\n/* global google */\n\nimport { createElement } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport i18n from '../utils/i18n';\nimport is from '../utils/is';\nimport loadScript from '../utils/load-script';\nimport { silencePromise } from '../utils/promise';\nimport { formatTime } from '../utils/time';\nimport { buildUrlParams } from '../utils/urls';\n\nconst destroy = (instance) => {\n // Destroy our adsManager\n if (instance.manager) {\n instance.manager.destroy();\n }\n\n // Destroy our adsManager\n if (instance.elements.displayContainer) {\n instance.elements.displayContainer.destroy();\n }\n\n instance.elements.container.remove();\n};\n\nclass Ads {\n /**\n * Ads constructor.\n * @param {Object} player\n * @return {Ads}\n */\n constructor(player) {\n this.player = player;\n this.config = player.config.ads;\n this.playing = false;\n this.initialized = false;\n this.elements = {\n container: null,\n displayContainer: null,\n };\n this.manager = null;\n this.loader = null;\n this.cuePoints = null;\n this.events = {};\n this.safetyTimer = null;\n this.countdownTimer = null;\n\n // Setup a promise to resolve when the IMA manager is ready\n this.managerPromise = new Promise((resolve, reject) => {\n // The ad is loaded and ready\n this.on('loaded', resolve);\n\n // Ads failed\n this.on('error', reject);\n });\n\n this.load();\n }\n\n get enabled() {\n const { config } = this;\n\n return (\n this.player.isHTML5 &&\n this.player.isVideo &&\n config.enabled &&\n (!is.empty(config.publisherId) || is.url(config.tagUrl))\n );\n }\n\n /**\n * Load the IMA SDK\n */\n load = () => {\n if (!this.enabled) {\n return;\n }\n\n // Check if the Google IMA3 SDK is loaded or load it ourselves\n if (!is.object(window.google) || !is.object(window.google.ima)) {\n loadScript(this.player.config.urls.googleIMA.sdk)\n .then(() => {\n this.ready();\n })\n .catch(() => {\n // Script failed to load or is blocked\n this.trigger('error', new Error('Google IMA SDK failed to load'));\n });\n } else {\n this.ready();\n }\n };\n\n /**\n * Get the ads instance ready\n */\n ready = () => {\n // Double check we're enabled\n if (!this.enabled) {\n destroy(this);\n }\n\n // Start ticking our safety timer. If the whole advertisement\n // thing doesn't resolve within our set time; we bail\n this.startSafetyTimer(12000, 'ready()');\n\n // Clear the safety timer\n this.managerPromise.then(() => {\n this.clearSafetyTimer('onAdsManagerLoaded()');\n });\n\n // Set listeners on the Plyr instance\n this.listeners();\n\n // Setup the IMA SDK\n this.setupIMA();\n };\n\n // Build the tag URL\n get tagUrl() {\n const { config } = this;\n\n if (is.url(config.tagUrl)) {\n return config.tagUrl;\n }\n\n const params = {\n AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',\n AV_CHANNELID: '5a0458dc28a06145e4519d21',\n AV_URL: window.location.hostname,\n cb: Date.now(),\n AV_WIDTH: 640,\n AV_HEIGHT: 480,\n AV_CDIM2: config.publisherId,\n };\n\n const base = 'https://go.aniview.com/api/adserver6/vast/';\n\n return `${base}?${buildUrlParams(params)}`;\n }\n\n /**\n * In order for the SDK to display ads for our video, we need to tell it where to put them,\n * so here we define our ad container. This div is set up to render on top of the video player.\n * Using the code below, we tell the SDK to render ads within that div. We also provide a\n * handle to the content video player - the SDK will poll the current time of our player to\n * properly place mid-rolls. After we create the ad display container, we initialize it. On\n * mobile devices, this initialization is done as the result of a user action.\n */\n setupIMA = () => {\n // Create the container for our advertisements\n this.elements.container = createElement('div', {\n class: this.player.config.classNames.ads,\n });\n\n this.player.elements.container.appendChild(this.elements.container);\n\n // So we can run VPAID2\n google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);\n\n // Set language\n google.ima.settings.setLocale(this.player.config.ads.language);\n\n // Set playback for iOS10+\n google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline);\n\n // We assume the adContainer is the video container of the plyr element that will house the ads\n this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container, this.player.media);\n\n // Create ads loader\n this.loader = new google.ima.AdsLoader(this.elements.displayContainer);\n\n // Listen and respond to ads loaded and error events\n this.loader.addEventListener(\n google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,\n (event) => this.onAdsManagerLoaded(event),\n false,\n );\n this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, (error) => this.onAdError(error), false);\n\n // Request video ads to be pre-loaded\n this.requestAds();\n };\n\n /**\n * Request advertisements\n */\n requestAds = () => {\n const { container } = this.player.elements;\n\n try {\n // Request video ads\n const request = new google.ima.AdsRequest();\n request.adTagUrl = this.tagUrl;\n\n // Specify the linear and nonlinear slot sizes. This helps the SDK\n // to select the correct creative if multiple are returned\n request.linearAdSlotWidth = container.offsetWidth;\n request.linearAdSlotHeight = container.offsetHeight;\n request.nonLinearAdSlotWidth = container.offsetWidth;\n request.nonLinearAdSlotHeight = container.offsetHeight;\n\n // We only overlay ads as we only support video.\n request.forceNonLinearFullSlot = false;\n\n // Mute based on current state\n request.setAdWillPlayMuted(!this.player.muted);\n\n this.loader.requestAds(request);\n } catch (error) {\n this.onAdError(error);\n }\n };\n\n /**\n * Update the ad countdown\n * @param {Boolean} start\n */\n pollCountdown = (start = false) => {\n if (!start) {\n clearInterval(this.countdownTimer);\n this.elements.container.removeAttribute('data-badge-text');\n return;\n }\n\n const update = () => {\n const time = formatTime(Math.max(this.manager.getRemainingTime(), 0));\n const label = `${i18n.get('advertisement', this.player.config)} - ${time}`;\n this.elements.container.setAttribute('data-badge-text', label);\n };\n\n this.countdownTimer = setInterval(update, 100);\n };\n\n /**\n * This method is called whenever the ads are ready inside the AdDisplayContainer\n * @param {Event} adsManagerLoadedEvent\n */\n onAdsManagerLoaded = (event) => {\n // Load could occur after a source change (race condition)\n if (!this.enabled) {\n return;\n }\n\n // Get the ads manager\n const settings = new google.ima.AdsRenderingSettings();\n\n // Tell the SDK to save and restore content video state on our behalf\n settings.restoreCustomPlaybackStateOnAdBreakComplete = true;\n settings.enablePreloading = true;\n\n // The SDK is polling currentTime on the contentPlayback. And needs a duration\n // so it can determine when to start the mid- and post-roll\n this.manager = event.getAdsManager(this.player, settings);\n\n // Get the cue points for any mid-rolls by filtering out the pre- and post-roll\n this.cuePoints = this.manager.getCuePoints();\n\n // Add listeners to the required events\n // Advertisement error events\n this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, (error) => this.onAdError(error));\n\n // Advertisement regular events\n Object.keys(google.ima.AdEvent.Type).forEach((type) => {\n this.manager.addEventListener(google.ima.AdEvent.Type[type], (e) => this.onAdEvent(e));\n });\n\n // Resolve our adsManager\n this.trigger('loaded');\n };\n\n addCuePoints = () => {\n // Add advertisement cue's within the time line if available\n if (!is.empty(this.cuePoints)) {\n this.cuePoints.forEach((cuePoint) => {\n if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {\n const seekElement = this.player.elements.progress;\n\n if (is.element(seekElement)) {\n const cuePercentage = (100 / this.player.duration) * cuePoint;\n const cue = createElement('span', {\n class: this.player.config.classNames.cues,\n });\n\n cue.style.left = `${cuePercentage.toString()}%`;\n seekElement.appendChild(cue);\n }\n }\n });\n }\n };\n\n /**\n * This is where all the event handling takes place. Retrieve the ad from the event. Some\n * events (e.g. ALL_ADS_COMPLETED) don't have the ad object associated\n * https://developers.google.com/interactive-media-ads/docs/sdks/html5/v3/apis#ima.AdEvent.Type\n * @param {Event} event\n */\n onAdEvent = (event) => {\n const { container } = this.player.elements;\n // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)\n // don't have ad object associated\n const ad = event.getAd();\n const adData = event.getAdData();\n\n // Proxy event\n const dispatchEvent = (type) => {\n triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`);\n };\n\n // Bubble the event\n dispatchEvent(event.type);\n\n switch (event.type) {\n case google.ima.AdEvent.Type.LOADED:\n // This is the first event sent for an ad - it is possible to determine whether the\n // ad is a video ad or an overlay\n this.trigger('loaded');\n\n // Start countdown\n this.pollCountdown(true);\n\n if (!ad.isLinear()) {\n // Position AdDisplayContainer correctly for overlay\n ad.width = container.offsetWidth;\n ad.height = container.offsetHeight;\n }\n\n // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex());\n // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset());\n\n break;\n\n case google.ima.AdEvent.Type.STARTED:\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n\n break;\n\n case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:\n // All ads for the current videos are done. We can now request new advertisements\n // in case the video is re-played\n\n // TODO: Example for what happens when a next video in a playlist would be loaded.\n // So here we load a new video when all ads are done.\n // Then we load new ads within a new adsManager. When the video\n // Is started - after - the ads are loaded, then we get ads.\n // You can also easily test cancelling and reloading by running\n // player.ads.cancel() and player.ads.play from the console I guess.\n // this.player.source = {\n // type: 'video',\n // title: 'View From A Blue Moon',\n // sources: [{\n // src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type:\n // 'video/mp4', }], poster:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks:\n // [ { kind: 'captions', label: 'English', srclang: 'en', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',\n // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ],\n // };\n\n // TODO: So there is still this thing where a video should only be allowed to start\n // playing when the IMA SDK is ready or has failed\n\n if (this.player.ended) {\n this.loadAds();\n } else {\n // The SDK won't allow new ads to be called without receiving a contentComplete()\n this.loader.contentComplete();\n }\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:\n // This event indicates the ad has started - the video player can adjust the UI,\n // for example display a pause button and remaining time. Fired when content should\n // be paused. This usually happens right before an ad is about to cover the content\n\n this.pauseContent();\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:\n // This event indicates the ad has finished - the video player can perform\n // appropriate UI actions, such as removing the timer for remaining time detection.\n // Fired when content should be resumed. This usually happens when an ad finishes\n // or collapses\n\n this.pollCountdown();\n\n this.resumeContent();\n\n break;\n\n case google.ima.AdEvent.Type.LOG:\n if (adData.adError) {\n this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);\n }\n\n break;\n\n default:\n break;\n }\n };\n\n /**\n * Any ad error handling comes through here\n * @param {Event} event\n */\n onAdError = (event) => {\n this.cancel();\n this.player.debug.warn('Ads error', event);\n };\n\n /**\n * Setup hooks for Plyr and window events. This ensures\n * the mid- and post-roll launch at the correct time. And\n * resize the advertisement when the player resizes\n */\n listeners = () => {\n const { container } = this.player.elements;\n let time;\n\n this.player.on('canplay', () => {\n this.addCuePoints();\n });\n\n this.player.on('ended', () => {\n this.loader.contentComplete();\n });\n\n this.player.on('timeupdate', () => {\n time = this.player.currentTime;\n });\n\n this.player.on('seeked', () => {\n const seekedTime = this.player.currentTime;\n\n if (is.empty(this.cuePoints)) {\n return;\n }\n\n this.cuePoints.forEach((cuePoint, index) => {\n if (time < cuePoint && cuePoint < seekedTime) {\n this.manager.discardAdBreak();\n this.cuePoints.splice(index, 1);\n }\n });\n });\n\n // Listen to the resizing of the window. And resize ad accordingly\n // TODO: eventually implement ResizeObserver\n window.addEventListener('resize', () => {\n if (this.manager) {\n this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n }\n });\n };\n\n /**\n * Initialize the adsManager and start playing advertisements\n */\n play = () => {\n const { container } = this.player.elements;\n\n if (!this.managerPromise) {\n this.resumeContent();\n }\n\n // Play the requested advertisement whenever the adsManager is ready\n this.managerPromise\n .then(() => {\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n\n // Initialize the container. Must be done via a user action on mobile devices\n this.elements.displayContainer.initialize();\n\n try {\n if (!this.initialized) {\n // Initialize the ads manager. Ad rules playlist will start at this time\n this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n\n // Call play to start showing the ad. Single video and overlay ads will\n // start at this time; the call will be ignored for ad rules\n this.manager.start();\n }\n\n this.initialized = true;\n } catch (adError) {\n // An error may be thrown if there was a problem with the\n // VAST response\n this.onAdError(adError);\n }\n })\n .catch(() => {});\n };\n\n /**\n * Resume our video\n */\n resumeContent = () => {\n // Hide the advertisement container\n this.elements.container.style.zIndex = '';\n\n // Ad is stopped\n this.playing = false;\n\n // Play video\n silencePromise(this.player.media.play());\n };\n\n /**\n * Pause our video\n */\n pauseContent = () => {\n // Show the advertisement container\n this.elements.container.style.zIndex = 3;\n\n // Ad is playing\n this.playing = true;\n\n // Pause our video.\n this.player.media.pause();\n };\n\n /**\n * Destroy the adsManager so we can grab new ads after this. If we don't then we're not\n * allowed to call new ads based on google policies, as they interpret this as an accidental\n * video requests. https://developers.google.com/interactive-\n * media-ads/docs/sdks/android/faq#8\n */\n cancel = () => {\n // Pause our video\n if (this.initialized) {\n this.resumeContent();\n }\n\n // Tell our instance that we're done for now\n this.trigger('error');\n\n // Re-create our adsManager\n this.loadAds();\n };\n\n /**\n * Re-create our adsManager\n */\n loadAds = () => {\n // Tell our adsManager to go bye bye\n this.managerPromise\n .then(() => {\n // Destroy our adsManager\n if (this.manager) {\n this.manager.destroy();\n }\n\n // Re-set our adsManager promises\n this.managerPromise = new Promise((resolve) => {\n this.on('loaded', resolve);\n this.player.debug.log(this.manager);\n });\n // Now that the manager has been destroyed set it to also be un-initialized\n this.initialized = false;\n\n // Now request some new advertisements\n this.requestAds();\n })\n .catch(() => {});\n };\n\n /**\n * Handles callbacks after an ad event was invoked\n * @param {String} event - Event type\n */\n trigger = (event, ...args) => {\n const handlers = this.events[event];\n\n if (is.array(handlers)) {\n handlers.forEach((handler) => {\n if (is.function(handler)) {\n handler.apply(this, args);\n }\n });\n }\n };\n\n /**\n * Add event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n * @return {Ads}\n */\n on = (event, callback) => {\n if (!is.array(this.events[event])) {\n this.events[event] = [];\n }\n\n this.events[event].push(callback);\n\n return this;\n };\n\n /**\n * Setup a safety timer for when the ad network doesn't respond for whatever reason.\n * The advertisement has 12 seconds to get its things together. We stop this timer when the\n * advertisement is playing, or when a user action is required to start, then we clear the\n * timer on ad ready\n * @param {Number} time\n * @param {String} from\n */\n startSafetyTimer = (time, from) => {\n this.player.debug.log(`Safety timer invoked from: ${from}`);\n\n this.safetyTimer = setTimeout(() => {\n this.cancel();\n this.clearSafetyTimer('startSafetyTimer()');\n }, time);\n };\n\n /**\n * Clear our safety timer(s)\n * @param {String} from\n */\n clearSafetyTimer = (from) => {\n if (!is.nullOrUndefined(this.safetyTimer)) {\n this.player.debug.log(`Safety timer cleared from: ${from}`);\n\n clearTimeout(this.safetyTimer);\n this.safetyTimer = null;\n }\n };\n}\n\nexport default Ads;\n","import { createElement } from '../utils/elements';\nimport { once } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport { formatTime } from '../utils/time';\n\n// Arg: vttDataString example: \"WEBVTT\\n\\n1\\n00:00:05.000 --> 00:00:10.000\\n1080p-00001.jpg\"\nconst parseVtt = (vttDataString) => {\n const processedList = [];\n const frames = vttDataString.split(/\\r\\n\\r\\n|\\n\\n|\\r\\r/);\n\n frames.forEach((frame) => {\n const result = {};\n const lines = frame.split(/\\r\\n|\\n|\\r/);\n\n lines.forEach((line) => {\n if (!is.number(result.startTime)) {\n // The line with start and end times on it is the first line of interest\n const matchTimes = line.match(\n /([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})/,\n ); // Note that this currently ignores caption formatting directives that are optionally on the end of this line - fine for non-captions VTT\n\n if (matchTimes) {\n result.startTime =\n Number(matchTimes[1] || 0) * 60 * 60 +\n Number(matchTimes[2]) * 60 +\n Number(matchTimes[3]) +\n Number(`0.${matchTimes[4]}`);\n result.endTime =\n Number(matchTimes[6] || 0) * 60 * 60 +\n Number(matchTimes[7]) * 60 +\n Number(matchTimes[8]) +\n Number(`0.${matchTimes[9]}`);\n }\n } else if (!is.empty(line.trim()) && is.empty(result.text)) {\n // If we already have the startTime, then we're definitely up to the text line(s)\n const lineSplit = line.trim().split('#xywh=');\n [result.text] = lineSplit;\n\n // If there's content in lineSplit[1], then we have sprites. If not, then it's just one frame per image\n if (lineSplit[1]) {\n [result.x, result.y, result.w, result.h] = lineSplit[1].split(',');\n }\n }\n });\n\n if (result.text) {\n processedList.push(result);\n }\n });\n\n return processedList;\n};\n\n/**\n * Preview thumbnails for seek hover and scrubbing\n * Seeking: Hover over the seek bar (desktop only): shows a small preview container above the seek bar\n * 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\n *\n * Notes:\n * - 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\n * - 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\n * - 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\n */\n\nconst fitRatio = (ratio, outer) => {\n const targetRatio = outer.width / outer.height;\n const result = {};\n if (ratio > targetRatio) {\n result.width = outer.width;\n result.height = (1 / ratio) * outer.width;\n } else {\n result.height = outer.height;\n result.width = ratio * outer.height;\n }\n\n return result;\n};\n\nclass PreviewThumbnails {\n /**\n * PreviewThumbnails constructor.\n * @param {Plyr} player\n * @return {PreviewThumbnails}\n */\n constructor(player) {\n this.player = player;\n this.thumbnails = [];\n this.loaded = false;\n this.lastMouseMoveTime = Date.now();\n this.mouseDown = false;\n this.loadedImages = [];\n\n this.elements = {\n thumb: {},\n scrubbing: {},\n };\n\n this.load();\n }\n\n get enabled() {\n return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;\n }\n\n load = () => {\n // Toggle the regular seek tooltip\n if (this.player.elements.display.seekTooltip) {\n this.player.elements.display.seekTooltip.hidden = this.enabled;\n }\n\n if (!this.enabled) {\n return;\n }\n\n this.getThumbnails().then(() => {\n if (!this.enabled) {\n return;\n }\n\n // Render DOM elements\n this.render();\n\n // Check to see if thumb container size was specified manually in CSS\n this.determineContainerAutoSizing();\n\n this.loaded = true;\n });\n };\n\n // Download VTT files and parse them\n getThumbnails = () => {\n return new Promise((resolve) => {\n const { src } = this.player.config.previewThumbnails;\n\n if (is.empty(src)) {\n throw new Error('Missing previewThumbnails.src config attribute');\n }\n\n // Resolve promise\n const sortAndResolve = () => {\n // Sort smallest to biggest (e.g., [120p, 480p, 1080p])\n this.thumbnails.sort((x, y) => x.height - y.height);\n\n this.player.debug.log('Preview thumbnails', this.thumbnails);\n\n resolve();\n };\n\n // Via callback()\n if (is.function(src)) {\n src((thumbnails) => {\n this.thumbnails = thumbnails;\n sortAndResolve();\n });\n }\n // VTT urls\n else {\n // If string, convert into single-element list\n const urls = is.string(src) ? [src] : src;\n // Loop through each src URL. Download and process the VTT file, storing the resulting data in this.thumbnails\n const promises = urls.map((u) => this.getThumbnail(u));\n // Resolve\n Promise.all(promises).then(sortAndResolve);\n }\n });\n };\n\n // Process individual VTT file\n getThumbnail = (url) => {\n return new Promise((resolve) => {\n fetch(url).then((response) => {\n const thumbnail = {\n frames: parseVtt(response),\n height: null,\n urlPrefix: '',\n };\n\n // If the URLs don't start with '/', then we need to set their relative path to be the location of the VTT file\n // If the URLs do start with '/', then they obviously don't need a prefix, so it will remain blank\n // If the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file\n if (\n !thumbnail.frames[0].text.startsWith('/') &&\n !thumbnail.frames[0].text.startsWith('http://') &&\n !thumbnail.frames[0].text.startsWith('https://')\n ) {\n thumbnail.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1);\n }\n\n // Download the first frame, so that we can determine/set the height of this thumbnailsDef\n const tempImage = new Image();\n\n tempImage.onload = () => {\n thumbnail.height = tempImage.naturalHeight;\n thumbnail.width = tempImage.naturalWidth;\n\n this.thumbnails.push(thumbnail);\n\n resolve();\n };\n\n tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;\n });\n });\n };\n\n startMove = (event) => {\n if (!this.loaded) {\n return;\n }\n\n if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {\n return;\n }\n\n // Wait until media has a duration\n if (!this.player.media.duration) {\n return;\n }\n\n if (event.type === 'touchmove') {\n // Calculate seek hover position as approx video seconds\n this.seekTime = this.player.media.duration * (this.player.elements.inputs.seek.value / 100);\n } else {\n // Calculate seek hover position as approx video seconds\n const clientRect = this.player.elements.progress.getBoundingClientRect();\n const percentage = (100 / clientRect.width) * (event.pageX - clientRect.left);\n this.seekTime = this.player.media.duration * (percentage / 100);\n\n if (this.seekTime < 0) {\n // The mousemove fires for 10+px out to the left\n this.seekTime = 0;\n }\n\n if (this.seekTime > this.player.media.duration - 1) {\n // Took 1 second off the duration for safety, because different players can disagree on the real duration of a video\n this.seekTime = this.player.media.duration - 1;\n }\n\n this.mousePosX = event.pageX;\n\n // Set time text inside image container\n this.elements.thumb.time.innerText = formatTime(this.seekTime);\n }\n\n // Download and show image\n this.showImageAtCurrentTime();\n };\n\n endMove = () => {\n this.toggleThumbContainer(false, true);\n };\n\n startScrubbing = (event) => {\n // Only act on left mouse button (0), or touch device (event.button does not exist or is false)\n if (is.nullOrUndefined(event.button) || event.button === false || event.button === 0) {\n this.mouseDown = true;\n\n // Wait until media has a duration\n if (this.player.media.duration) {\n this.toggleScrubbingContainer(true);\n this.toggleThumbContainer(false, true);\n\n // Download and show image\n this.showImageAtCurrentTime();\n }\n }\n };\n\n endScrubbing = () => {\n this.mouseDown = false;\n\n // Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview\n if (Math.ceil(this.lastTime) === Math.ceil(this.player.media.currentTime)) {\n // The video was already seeked/loaded at the chosen time - hide immediately\n this.toggleScrubbingContainer(false);\n } else {\n // The video hasn't seeked yet. Wait for that\n once.call(this.player, this.player.media, 'timeupdate', () => {\n // Re-check mousedown - we might have already started scrubbing again\n if (!this.mouseDown) {\n this.toggleScrubbingContainer(false);\n }\n });\n }\n };\n\n /**\n * Setup hooks for Plyr and window events\n */\n listeners = () => {\n // 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\n this.player.on('play', () => {\n this.toggleThumbContainer(false, true);\n });\n\n this.player.on('seeked', () => {\n this.toggleThumbContainer(false);\n });\n\n this.player.on('timeupdate', () => {\n this.lastTime = this.player.media.currentTime;\n });\n };\n\n /**\n * Create HTML elements for image containers\n */\n render = () => {\n // Create HTML element: plyr__preview-thumbnail-container\n this.elements.thumb.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.thumbContainer,\n });\n\n // Wrapper for the image for styling\n this.elements.thumb.imageContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.imageContainer,\n });\n this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer);\n\n // Create HTML element, parent+span: time text (e.g., 01:32:00)\n const timeContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.timeContainer,\n });\n\n this.elements.thumb.time = createElement('span', {}, '00:00');\n timeContainer.appendChild(this.elements.thumb.time);\n\n this.elements.thumb.container.appendChild(timeContainer);\n\n // Inject the whole thumb\n if (is.element(this.player.elements.progress)) {\n this.player.elements.progress.appendChild(this.elements.thumb.container);\n }\n\n // Create HTML element: plyr__preview-scrubbing-container\n this.elements.scrubbing.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.scrubbingContainer,\n });\n\n this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);\n };\n\n destroy = () => {\n if (this.elements.thumb.container) {\n this.elements.thumb.container.remove();\n }\n if (this.elements.scrubbing.container) {\n this.elements.scrubbing.container.remove();\n }\n };\n\n showImageAtCurrentTime = () => {\n if (this.mouseDown) {\n this.setScrubbingContainerSize();\n } else {\n this.setThumbContainerSizeAndPos();\n }\n\n // Find the desired thumbnail index\n // TODO: Handle a video longer than the thumbs where thumbNum is null\n const thumbNum = this.thumbnails[0].frames.findIndex(\n (frame) => this.seekTime >= frame.startTime && this.seekTime <= frame.endTime,\n );\n const hasThumb = thumbNum >= 0;\n let qualityIndex = 0;\n\n // Show the thumb container if we're not scrubbing\n if (!this.mouseDown) {\n this.toggleThumbContainer(hasThumb);\n }\n\n // No matching thumb found\n if (!hasThumb) {\n return;\n }\n\n // Check to see if we've already downloaded higher quality versions of this image\n this.thumbnails.forEach((thumbnail, index) => {\n if (this.loadedImages.includes(thumbnail.frames[thumbNum].text)) {\n qualityIndex = index;\n }\n });\n\n // Only proceed if either thumbnum or thumbfilename has changed\n if (thumbNum !== this.showingThumb) {\n this.showingThumb = thumbNum;\n this.loadImage(qualityIndex);\n }\n };\n\n // Show the image that's currently specified in this.showingThumb\n loadImage = (qualityIndex = 0) => {\n const thumbNum = this.showingThumb;\n const thumbnail = this.thumbnails[qualityIndex];\n const { urlPrefix } = thumbnail;\n const frame = thumbnail.frames[thumbNum];\n const thumbFilename = thumbnail.frames[thumbNum].text;\n const thumbUrl = urlPrefix + thumbFilename;\n\n if (!this.currentImageElement || this.currentImageElement.dataset.filename !== thumbFilename) {\n // If we're already loading a previous image, remove its onload handler - we don't want it to load after this one\n // Only do this if not using sprites. Without sprites we really want to show as many images as possible, as a best-effort\n if (this.loadingImage && this.usingSprites) {\n this.loadingImage.onload = null;\n }\n\n // We're building and adding a new image. In other implementations of similar functionality (YouTube), background image\n // is instead used. But this causes issues with larger images in Firefox and Safari - switching between background\n // images causes a flicker. Putting a new image over the top does not\n const previewImage = new Image();\n previewImage.src = thumbUrl;\n previewImage.dataset.index = thumbNum;\n previewImage.dataset.filename = thumbFilename;\n this.showingThumbFilename = thumbFilename;\n\n this.player.debug.log(`Loading image: ${thumbUrl}`);\n\n // For some reason, passing the named function directly causes it to execute immediately. So I've wrapped it in an anonymous function...\n previewImage.onload = () => this.showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, true);\n this.loadingImage = previewImage;\n this.removeOldImages(previewImage);\n } else {\n // Update the existing image\n this.showImage(this.currentImageElement, frame, qualityIndex, thumbNum, thumbFilename, false);\n this.currentImageElement.dataset.index = thumbNum;\n this.removeOldImages(this.currentImageElement);\n }\n };\n\n showImage = (previewImage, frame, qualityIndex, thumbNum, thumbFilename, newImage = true) => {\n this.player.debug.log(\n `Showing thumb: ${thumbFilename}. num: ${thumbNum}. qual: ${qualityIndex}. newimg: ${newImage}`,\n );\n this.setImageSizeAndOffset(previewImage, frame);\n\n if (newImage) {\n this.currentImageContainer.appendChild(previewImage);\n this.currentImageElement = previewImage;\n\n if (!this.loadedImages.includes(thumbFilename)) {\n this.loadedImages.push(thumbFilename);\n }\n }\n\n // Preload images before and after the current one\n // Show higher quality of the same frame\n // 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\n this.preloadNearby(thumbNum, true)\n .then(this.preloadNearby(thumbNum, false))\n .then(this.getHigherQuality(qualityIndex, previewImage, frame, thumbFilename));\n };\n\n // Remove all preview images that aren't the designated current image\n removeOldImages = (currentImage) => {\n // Get a list of all images, convert it from a DOM list to an array\n Array.from(this.currentImageContainer.children).forEach((image) => {\n if (image.tagName.toLowerCase() !== 'img') {\n return;\n }\n\n const removeDelay = this.usingSprites ? 500 : 1000;\n\n if (image.dataset.index !== currentImage.dataset.index && !image.dataset.deleting) {\n // 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\n // First set attribute 'deleting' to prevent multi-handling of this on repeat firing of this function\n // eslint-disable-next-line no-param-reassign\n image.dataset.deleting = true;\n\n // This has to be set before the timeout - to prevent issues switching between hover and scrub\n const { currentImageContainer } = this;\n\n setTimeout(() => {\n currentImageContainer.removeChild(image);\n this.player.debug.log(`Removing thumb: ${image.dataset.filename}`);\n }, removeDelay);\n }\n });\n };\n\n // Preload images before and after the current one. Only if the user is still hovering/seeking the same frame\n // This will only preload the lowest quality\n preloadNearby = (thumbNum, forward = true) => {\n return new Promise((resolve) => {\n setTimeout(() => {\n const oldThumbFilename = this.thumbnails[0].frames[thumbNum].text;\n\n if (this.showingThumbFilename === oldThumbFilename) {\n // 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\n let thumbnailsClone;\n if (forward) {\n thumbnailsClone = this.thumbnails[0].frames.slice(thumbNum);\n } else {\n thumbnailsClone = this.thumbnails[0].frames.slice(0, thumbNum).reverse();\n }\n\n let foundOne = false;\n\n thumbnailsClone.forEach((frame) => {\n const newThumbFilename = frame.text;\n\n if (newThumbFilename !== oldThumbFilename) {\n // Found one with a different filename. Make sure it hasn't already been loaded on this page visit\n if (!this.loadedImages.includes(newThumbFilename)) {\n foundOne = true;\n this.player.debug.log(`Preloading thumb filename: ${newThumbFilename}`);\n\n const { urlPrefix } = this.thumbnails[0];\n const thumbURL = urlPrefix + newThumbFilename;\n const previewImage = new Image();\n previewImage.src = thumbURL;\n previewImage.onload = () => {\n this.player.debug.log(`Preloaded thumb filename: ${newThumbFilename}`);\n if (!this.loadedImages.includes(newThumbFilename)) this.loadedImages.push(newThumbFilename);\n\n // We don't resolve until the thumb is loaded\n resolve();\n };\n }\n }\n });\n\n // If there are none to preload then we want to resolve immediately\n if (!foundOne) {\n resolve();\n }\n }\n }, 300);\n });\n };\n\n // If user has been hovering current image for half a second, look for a higher quality one\n getHigherQuality = (currentQualityIndex, previewImage, frame, thumbFilename) => {\n if (currentQualityIndex < this.thumbnails.length - 1) {\n // 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\n let previewImageHeight = previewImage.naturalHeight;\n\n if (this.usingSprites) {\n previewImageHeight = frame.h;\n }\n\n if (previewImageHeight < this.thumbContainerHeight) {\n // Recurse back to the loadImage function - show a higher quality one, but only if the viewer is on this frame for a while\n setTimeout(() => {\n // Make sure the mouse hasn't already moved on and started hovering at another image\n if (this.showingThumbFilename === thumbFilename) {\n this.player.debug.log(`Showing higher quality thumb for: ${thumbFilename}`);\n this.loadImage(currentQualityIndex + 1);\n }\n }, 300);\n }\n }\n };\n\n get currentImageContainer() {\n if (this.mouseDown) {\n return this.elements.scrubbing.container;\n }\n\n return this.elements.thumb.imageContainer;\n }\n\n get usingSprites() {\n return Object.keys(this.thumbnails[0].frames[0]).includes('w');\n }\n\n get thumbAspectRatio() {\n if (this.usingSprites) {\n return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;\n }\n\n return this.thumbnails[0].width / this.thumbnails[0].height;\n }\n\n get thumbContainerHeight() {\n if (this.mouseDown) {\n const { height } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight,\n });\n return height;\n }\n\n // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset)\n if (this.sizeSpecifiedInCSS) {\n return this.elements.thumb.imageContainer.clientHeight;\n }\n\n return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);\n }\n\n get currentImageElement() {\n if (this.mouseDown) {\n return this.currentScrubbingImageElement;\n }\n\n return this.currentThumbnailImageElement;\n }\n\n set currentImageElement(element) {\n if (this.mouseDown) {\n this.currentScrubbingImageElement = element;\n } else {\n this.currentThumbnailImageElement = element;\n }\n }\n\n toggleThumbContainer = (toggle = false, clearShowing = false) => {\n const className = this.player.config.classNames.previewThumbnails.thumbContainerShown;\n this.elements.thumb.container.classList.toggle(className, toggle);\n\n if (!toggle && clearShowing) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n };\n\n toggleScrubbingContainer = (toggle = false) => {\n const className = this.player.config.classNames.previewThumbnails.scrubbingContainerShown;\n this.elements.scrubbing.container.classList.toggle(className, toggle);\n\n if (!toggle) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n };\n\n determineContainerAutoSizing = () => {\n if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) {\n // This will prevent auto sizing in this.setThumbContainerSizeAndPos()\n this.sizeSpecifiedInCSS = true;\n }\n };\n\n // 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\n setThumbContainerSizeAndPos = () => {\n if (!this.sizeSpecifiedInCSS) {\n const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${this.thumbContainerHeight}px`;\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (\n this.elements.thumb.imageContainer.clientHeight > 20 &&\n this.elements.thumb.imageContainer.clientWidth < 20\n ) {\n const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (\n this.elements.thumb.imageContainer.clientHeight < 20 &&\n this.elements.thumb.imageContainer.clientWidth > 20\n ) {\n const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`;\n }\n\n this.setThumbContainerPos();\n };\n\n setThumbContainerPos = () => {\n const seekbarRect = this.player.elements.progress.getBoundingClientRect();\n const plyrRect = this.player.elements.container.getBoundingClientRect();\n const { container } = this.elements.thumb;\n // Find the lowest and highest desired left-position, so we don't slide out the side of the video container\n const minVal = plyrRect.left - seekbarRect.left + 10;\n const maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10;\n // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth\n let previewPos = this.mousePosX - seekbarRect.left - container.clientWidth / 2;\n\n if (previewPos < minVal) {\n previewPos = minVal;\n }\n\n if (previewPos > maxVal) {\n previewPos = maxVal;\n }\n\n container.style.left = `${previewPos}px`;\n };\n\n // Can't use 100% width, in case the video is a different aspect ratio to the video container\n setScrubbingContainerSize = () => {\n const { width, height } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight,\n });\n this.elements.scrubbing.container.style.width = `${width}px`;\n this.elements.scrubbing.container.style.height = `${height}px`;\n };\n\n // Sprites need to be offset to the correct location\n setImageSizeAndOffset = (previewImage, frame) => {\n if (!this.usingSprites) {\n return;\n }\n\n // Find difference between height and preview container height\n const multiplier = this.thumbContainerHeight / frame.h;\n\n // eslint-disable-next-line no-param-reassign\n previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.left = `-${frame.x * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.top = `-${frame.y * multiplier}px`;\n };\n}\n\nexport default PreviewThumbnails;\n","// ==========================================================================\n// Plyr source update\n// ==========================================================================\n\nimport { providers } from './config/types';\nimport html5 from './html5';\nimport media from './media';\nimport PreviewThumbnails from './plugins/preview-thumbnails';\nimport support from './support';\nimport ui from './ui';\nimport { createElement, insertElement, removeElement } from './utils/elements';\nimport is from './utils/is';\nimport { getDeep } from './utils/objects';\n\nconst source = {\n // Add elements to HTML5 media (source, tracks, etc)\n insertElements(type, attributes) {\n if (is.string(attributes)) {\n insertElement(type, this.media, {\n src: attributes,\n });\n } else if (is.array(attributes)) {\n attributes.forEach((attribute) => {\n insertElement(type, this.media, attribute);\n });\n }\n },\n\n // Update source\n // Sources are not checked for support so be careful\n change(input) {\n if (!getDeep(input, 'sources.length')) {\n this.debug.warn('Invalid source format');\n return;\n }\n\n // Cancel current network requests\n html5.cancelRequests.call(this);\n\n // Destroy instance and re-setup\n this.destroy.call(\n this,\n () => {\n // Reset quality options\n this.options.quality = [];\n\n // Remove elements\n removeElement(this.media);\n this.media = null;\n\n // Reset class name\n if (is.element(this.elements.container)) {\n this.elements.container.removeAttribute('class');\n }\n\n // Set the type and provider\n const { sources, type } = input;\n const [{ provider = providers.html5, src }] = sources;\n const tagName = provider === 'html5' ? type : 'div';\n const attributes = provider === 'html5' ? {} : { src };\n\n Object.assign(this, {\n provider,\n type,\n // Check for support\n supported: support.check(type, provider, this.config.playsinline),\n // Create new element\n media: createElement(tagName, attributes),\n });\n\n // Inject the new element\n this.elements.container.appendChild(this.media);\n\n // Autoplay the new source?\n if (is.boolean(input.autoplay)) {\n this.config.autoplay = input.autoplay;\n }\n\n // Set attributes for audio and video\n if (this.isHTML5) {\n if (this.config.crossorigin) {\n this.media.setAttribute('crossorigin', '');\n }\n if (this.config.autoplay) {\n this.media.setAttribute('autoplay', '');\n }\n if (!is.empty(input.poster)) {\n this.poster = input.poster;\n }\n if (this.config.loop.active) {\n this.media.setAttribute('loop', '');\n }\n if (this.config.muted) {\n this.media.setAttribute('muted', '');\n }\n if (this.config.playsinline) {\n this.media.setAttribute('playsinline', '');\n }\n }\n\n // Restore class hook\n ui.addStyleHook.call(this);\n\n // Set new sources for html5\n if (this.isHTML5) {\n source.insertElements.call(this, 'source', sources);\n }\n\n // Set video title\n this.config.title = input.title;\n\n // Set up from scratch\n media.setup.call(this);\n\n // HTML5 stuff\n if (this.isHTML5) {\n // Setup captions\n if (Object.keys(input).includes('tracks')) {\n source.insertElements.call(this, 'track', input.tracks);\n }\n }\n\n // If HTML5 or embed but not fully supported, setupInterface and call ready now\n if (this.isHTML5 || (this.isEmbed && !this.supported.ui)) {\n // Setup interface\n ui.build.call(this);\n }\n\n // Load HTML5 sources\n if (this.isHTML5) {\n this.media.load();\n }\n\n // Update previewThumbnails config & reload plugin\n if (!is.empty(input.previewThumbnails)) {\n Object.assign(this.config.previewThumbnails, input.previewThumbnails);\n\n // Cleanup previewThumbnails plugin if it was loaded\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n // Create new instance if it is still enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n // Update the fullscreen support\n this.fullscreen.update();\n },\n true,\n );\n },\n};\n\nexport default source;\n","// ==========================================================================\n// Plyr\n// plyr.js v3.6.12\n// https://github.com/sampotts/plyr\n// License: The MIT License (MIT)\n// ==========================================================================\n\nimport captions from './captions';\nimport defaults from './config/defaults';\nimport { pip } from './config/states';\nimport { getProviderByUrl, providers, types } from './config/types';\nimport Console from './console';\nimport controls from './controls';\nimport Fullscreen from './fullscreen';\nimport html5 from './html5';\nimport Listeners from './listeners';\nimport media from './media';\nimport Ads from './plugins/ads';\nimport PreviewThumbnails from './plugins/preview-thumbnails';\nimport source from './source';\nimport Storage from './storage';\nimport support from './support';\nimport ui from './ui';\nimport { closest } from './utils/arrays';\nimport { createElement, hasClass, removeElement, replaceElement, toggleClass, wrap } from './utils/elements';\nimport { off, on, once, triggerEvent, unbindListeners } from './utils/events';\nimport is from './utils/is';\nimport loadSprite from './utils/load-sprite';\nimport { clamp } from './utils/numbers';\nimport { cloneDeep, extend } from './utils/objects';\nimport { silencePromise } from './utils/promise';\nimport { getAspectRatio, reduceAspectRatio, setAspectRatio, validateAspectRatio } from './utils/style';\nimport { parseUrl } from './utils/urls';\n\n// Private properties\n// TODO: Use a WeakMap for private globals\n// const globals = new WeakMap();\n\n// Plyr instance\nclass Plyr {\n constructor(target, options) {\n this.timers = {};\n\n // State\n this.ready = false;\n this.loading = false;\n this.failed = false;\n\n // Touch device\n this.touch = support.touch;\n\n // Set the media element\n this.media = target;\n\n // String selector passed\n if (is.string(this.media)) {\n this.media = document.querySelectorAll(this.media);\n }\n\n // jQuery, NodeList or Array passed, use first element\n if ((window.jQuery && this.media instanceof jQuery) || is.nodeList(this.media) || is.array(this.media)) {\n // eslint-disable-next-line\n this.media = this.media[0];\n }\n\n // Set config\n this.config = extend(\n {},\n defaults,\n Plyr.defaults,\n options || {},\n (() => {\n try {\n return JSON.parse(this.media.getAttribute('data-plyr-config'));\n } catch (_) {\n return {};\n }\n })(),\n );\n\n // Elements cache\n this.elements = {\n container: null,\n fullscreen: null,\n captions: null,\n buttons: {},\n display: {},\n progress: {},\n inputs: {},\n settings: {\n popup: null,\n menu: null,\n panels: {},\n buttons: {},\n },\n };\n\n // Captions\n this.captions = {\n active: null,\n currentTrack: -1,\n meta: new WeakMap(),\n };\n\n // Fullscreen\n this.fullscreen = {\n active: false,\n };\n\n // Options\n this.options = {\n speed: [],\n quality: [],\n };\n\n // Debugging\n // TODO: move to globals\n this.debug = new Console(this.config.debug);\n\n // Log config options and support\n this.debug.log('Config', this.config);\n this.debug.log('Support', support);\n\n // We need an element to setup\n if (is.nullOrUndefined(this.media) || !is.element(this.media)) {\n this.debug.error('Setup failed: no suitable element passed');\n return;\n }\n\n // Bail if the element is initialized\n if (this.media.plyr) {\n this.debug.warn('Target already setup');\n return;\n }\n\n // Bail if not enabled\n if (!this.config.enabled) {\n this.debug.error('Setup failed: disabled by config');\n return;\n }\n\n // Bail if disabled or no basic support\n // You may want to disable certain UAs etc\n if (!support.check().api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n // Cache original element state for .destroy()\n const clone = this.media.cloneNode(true);\n clone.autoplay = false;\n this.elements.original = clone;\n\n // Set media type based on tag or data attribute\n // Supported: video, audio, vimeo, youtube\n const type = this.media.tagName.toLowerCase();\n // Embed properties\n let iframe = null;\n let url = null;\n\n // Different setup based on type\n switch (type) {\n case 'div':\n // Find the frame\n iframe = this.media.querySelector('iframe');\n\n // <iframe> type\n if (is.element(iframe)) {\n // Detect provider\n url = parseUrl(iframe.getAttribute('src'));\n this.provider = getProviderByUrl(url.toString());\n\n // Rework elements\n this.elements.container = this.media;\n this.media = iframe;\n\n // Reset classname\n this.elements.container.className = '';\n\n // Get attributes from URL and set config\n if (url.search.length) {\n const truthy = ['1', 'true'];\n\n if (truthy.includes(url.searchParams.get('autoplay'))) {\n this.config.autoplay = true;\n }\n if (truthy.includes(url.searchParams.get('loop'))) {\n this.config.loop.active = true;\n }\n\n // TODO: replace fullscreen.iosNative with this playsinline config option\n // YouTube requires the playsinline in the URL\n if (this.isYouTube) {\n this.config.playsinline = truthy.includes(url.searchParams.get('playsinline'));\n this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language?\n } else {\n this.config.playsinline = true;\n }\n }\n } else {\n // <div> with attributes\n this.provider = this.media.getAttribute(this.config.attributes.embed.provider);\n\n // Remove attribute\n this.media.removeAttribute(this.config.attributes.embed.provider);\n }\n\n // Unsupported or missing provider\n if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) {\n this.debug.error('Setup failed: Invalid provider');\n return;\n }\n\n // Audio will come later for external providers\n this.type = types.video;\n\n break;\n\n case 'video':\n case 'audio':\n this.type = type;\n this.provider = providers.html5;\n\n // Get config from attributes\n if (this.media.hasAttribute('crossorigin')) {\n this.config.crossorigin = true;\n }\n if (this.media.hasAttribute('autoplay')) {\n this.config.autoplay = true;\n }\n if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) {\n this.config.playsinline = true;\n }\n if (this.media.hasAttribute('muted')) {\n this.config.muted = true;\n }\n if (this.media.hasAttribute('loop')) {\n this.config.loop.active = true;\n }\n\n break;\n\n default:\n this.debug.error('Setup failed: unsupported type');\n return;\n }\n\n // Check for support again but with type\n this.supported = support.check(this.type, this.provider, this.config.playsinline);\n\n // If no support for even API, bail\n if (!this.supported.api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n this.eventListeners = [];\n\n // Create listeners\n this.listeners = new Listeners(this);\n\n // Setup local storage for user settings\n this.storage = new Storage(this);\n\n // Store reference\n this.media.plyr = this;\n\n // Wrap media\n if (!is.element(this.elements.container)) {\n this.elements.container = createElement('div', { tabindex: 0 });\n wrap(this.media, this.elements.container);\n }\n\n // Migrate custom properties from media to container (so they work 😉)\n ui.migrateStyles.call(this);\n\n // Add style hook\n ui.addStyleHook.call(this);\n\n // Setup media\n media.setup.call(this);\n\n // Listen for events if debugging\n if (this.config.debug) {\n on.call(this, this.elements.container, this.config.events.join(' '), (event) => {\n this.debug.log(`event: ${event.type}`);\n });\n }\n\n // Setup fullscreen\n this.fullscreen = new Fullscreen(this);\n\n // Setup interface\n // If embed but not fully supported, build interface now to avoid flash of controls\n if (this.isHTML5 || (this.isEmbed && !this.supported.ui)) {\n ui.build.call(this);\n }\n\n // Container listeners\n this.listeners.container();\n\n // Global listeners\n this.listeners.global();\n\n // Setup ads if provided\n if (this.config.ads.enabled) {\n this.ads = new Ads(this);\n }\n\n // Autoplay if required\n if (this.isHTML5 && this.config.autoplay) {\n this.once('canplay', () => silencePromise(this.play()));\n }\n\n // Seek time will be recorded (in listeners.js) so we can prevent hiding controls for a few seconds after seek\n this.lastSeekTime = 0;\n\n // Setup preview thumbnails if enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n // ---------------------------------------\n // API\n // ---------------------------------------\n\n /**\n * Types and provider helpers\n */\n get isHTML5() {\n return this.provider === providers.html5;\n }\n\n get isEmbed() {\n return this.isYouTube || this.isVimeo;\n }\n\n get isYouTube() {\n return this.provider === providers.youtube;\n }\n\n get isVimeo() {\n return this.provider === providers.vimeo;\n }\n\n get isVideo() {\n return this.type === types.video;\n }\n\n get isAudio() {\n return this.type === types.audio;\n }\n\n /**\n * Play the media, or play the advertisement (if they are not blocked)\n */\n play = () => {\n if (!is.function(this.media.play)) {\n return null;\n }\n\n // Intecept play with ads\n if (this.ads && this.ads.enabled) {\n this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play()));\n }\n\n // Return the promise (for HTML5)\n return this.media.play();\n };\n\n /**\n * Pause the media\n */\n pause = () => {\n if (!this.playing || !is.function(this.media.pause)) {\n return null;\n }\n\n return this.media.pause();\n };\n\n /**\n * Get playing state\n */\n get playing() {\n return Boolean(this.ready && !this.paused && !this.ended);\n }\n\n /**\n * Get paused state\n */\n get paused() {\n return Boolean(this.media.paused);\n }\n\n /**\n * Get stopped state\n */\n get stopped() {\n return Boolean(this.paused && this.currentTime === 0);\n }\n\n /**\n * Get ended state\n */\n get ended() {\n return Boolean(this.media.ended);\n }\n\n /**\n * Toggle playback based on current status\n * @param {Boolean} input\n */\n togglePlay = (input) => {\n // Toggle based on current state if nothing passed\n const toggle = is.boolean(input) ? input : !this.playing;\n\n if (toggle) {\n return this.play();\n }\n\n return this.pause();\n };\n\n /**\n * Stop playback\n */\n stop = () => {\n if (this.isHTML5) {\n this.pause();\n this.restart();\n } else if (is.function(this.media.stop)) {\n this.media.stop();\n }\n };\n\n /**\n * Restart playback\n */\n restart = () => {\n this.currentTime = 0;\n };\n\n /**\n * Rewind\n * @param {Number} seekTime - how far to rewind in seconds. Defaults to the config.seekTime\n */\n rewind = (seekTime) => {\n this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime;\n };\n\n /**\n * Fast forward\n * @param {Number} seekTime - how far to fast forward in seconds. Defaults to the config.seekTime\n */\n forward = (seekTime) => {\n this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime;\n };\n\n /**\n * Seek to a time\n * @param {Number} input - where to seek to in seconds. Defaults to 0 (the start)\n */\n set currentTime(input) {\n // Bail if media duration isn't available yet\n if (!this.duration) {\n return;\n }\n\n // Validate input\n const inputIsValid = is.number(input) && input > 0;\n\n // Set\n this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0;\n\n // Logging\n this.debug.log(`Seeking to ${this.currentTime} seconds`);\n }\n\n /**\n * Get current time\n */\n get currentTime() {\n return Number(this.media.currentTime);\n }\n\n /**\n * Get buffered\n */\n get buffered() {\n const { buffered } = this.media;\n\n // YouTube / Vimeo return a float between 0-1\n if (is.number(buffered)) {\n return buffered;\n }\n\n // HTML5\n // TODO: Handle buffered chunks of the media\n // (i.e. seek to another section buffers only that section)\n if (buffered && buffered.length && this.duration > 0) {\n return buffered.end(0) / this.duration;\n }\n\n return 0;\n }\n\n /**\n * Get seeking status\n */\n get seeking() {\n return Boolean(this.media.seeking);\n }\n\n /**\n * Get the duration of the current media\n */\n get duration() {\n // Faux duration set via config\n const fauxDuration = parseFloat(this.config.duration);\n // Media duration can be NaN or Infinity before the media has loaded\n const realDuration = (this.media || {}).duration;\n const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration;\n\n // If config duration is funky, use regular duration\n return fauxDuration || duration;\n }\n\n /**\n * Set the player volume\n * @param {Number} value - must be between 0 and 1. Defaults to the value from local storage and config.volume if not set in storage\n */\n set volume(value) {\n let volume = value;\n const max = 1;\n const min = 0;\n\n if (is.string(volume)) {\n volume = Number(volume);\n }\n\n // Load volume from storage if no value specified\n if (!is.number(volume)) {\n volume = this.storage.get('volume');\n }\n\n // Use config if all else fails\n if (!is.number(volume)) {\n ({ volume } = this.config);\n }\n\n // Maximum is volumeMax\n if (volume > max) {\n volume = max;\n }\n // Minimum is volumeMin\n if (volume < min) {\n volume = min;\n }\n\n // Update config\n this.config.volume = volume;\n\n // Set the player volume\n this.media.volume = volume;\n\n // If muted, and we're increasing volume manually, reset muted state\n if (!is.empty(value) && this.muted && volume > 0) {\n this.muted = false;\n }\n }\n\n /**\n * Get the current player volume\n */\n get volume() {\n return Number(this.media.volume);\n }\n\n /**\n * Increase volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n increaseVolume = (step) => {\n const volume = this.media.muted ? 0 : this.volume;\n this.volume = volume + (is.number(step) ? step : 0);\n };\n\n /**\n * Decrease volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n decreaseVolume = (step) => {\n this.increaseVolume(-step);\n };\n\n /**\n * Set muted state\n * @param {Boolean} mute\n */\n set muted(mute) {\n let toggle = mute;\n\n // Load muted state from storage\n if (!is.boolean(toggle)) {\n toggle = this.storage.get('muted');\n }\n\n // Use config if all else fails\n if (!is.boolean(toggle)) {\n toggle = this.config.muted;\n }\n\n // Update config\n this.config.muted = toggle;\n\n // Set mute on the player\n this.media.muted = toggle;\n }\n\n /**\n * Get current muted state\n */\n get muted() {\n return Boolean(this.media.muted);\n }\n\n /**\n * Check if the media has audio\n */\n get hasAudio() {\n // Assume yes for all non HTML5 (as we can't tell...)\n if (!this.isHTML5) {\n return true;\n }\n\n if (this.isAudio) {\n return true;\n }\n\n // Get audio tracks\n return (\n Boolean(this.media.mozHasAudio) ||\n Boolean(this.media.webkitAudioDecodedByteCount) ||\n Boolean(this.media.audioTracks && this.media.audioTracks.length)\n );\n }\n\n /**\n * Set playback speed\n * @param {Number} speed - the speed of playback (0.5-2.0)\n */\n set speed(input) {\n let speed = null;\n\n if (is.number(input)) {\n speed = input;\n }\n\n if (!is.number(speed)) {\n speed = this.storage.get('speed');\n }\n\n if (!is.number(speed)) {\n speed = this.config.speed.selected;\n }\n\n // Clamp to min/max\n const { minimumSpeed: min, maximumSpeed: max } = this;\n speed = clamp(speed, min, max);\n\n // Update config\n this.config.speed.selected = speed;\n\n // Set media speed\n setTimeout(() => {\n if (this.media) {\n this.media.playbackRate = speed;\n }\n }, 0);\n }\n\n /**\n * Get current playback speed\n */\n get speed() {\n return Number(this.media.playbackRate);\n }\n\n /**\n * Get the minimum allowed speed\n */\n get minimumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.min(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 0.5;\n }\n\n // https://stackoverflow.com/a/32320020/1191319\n return 0.0625;\n }\n\n /**\n * Get the maximum allowed speed\n */\n get maximumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.max(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 2;\n }\n\n // https://stackoverflow.com/a/32320020/1191319\n return 16;\n }\n\n /**\n * Set playback quality\n * Currently HTML5 & YouTube only\n * @param {Number} input - Quality level\n */\n set quality(input) {\n const config = this.config.quality;\n const options = this.options.quality;\n\n if (!options.length) {\n return;\n }\n\n let quality = [\n !is.empty(input) && Number(input),\n this.storage.get('quality'),\n config.selected,\n config.default,\n ].find(is.number);\n\n let updateStorage = true;\n\n if (!options.includes(quality)) {\n const value = closest(options, quality);\n this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`);\n quality = value;\n\n // Don't update storage if quality is not supported\n updateStorage = false;\n }\n\n // Update config\n config.selected = quality;\n\n // Set quality\n this.media.quality = quality;\n\n // Save to storage\n if (updateStorage) {\n this.storage.set({ quality });\n }\n }\n\n /**\n * Get current quality level\n */\n get quality() {\n return this.media.quality;\n }\n\n /**\n * Toggle loop\n * TODO: Finish fancy new logic. Set the indicator on load as user may pass loop as config\n * @param {Boolean} input - Whether to loop or not\n */\n set loop(input) {\n const toggle = is.boolean(input) ? input : this.config.loop.active;\n this.config.loop.active = toggle;\n this.media.loop = toggle;\n\n // Set default to be a true toggle\n /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle';\n\n switch (type) {\n case 'start':\n if (this.config.loop.end && this.config.loop.end <= this.currentTime) {\n this.config.loop.end = null;\n }\n this.config.loop.start = this.currentTime;\n // this.config.loop.indicator.start = this.elements.display.played.value;\n break;\n\n case 'end':\n if (this.config.loop.start >= this.currentTime) {\n return this;\n }\n this.config.loop.end = this.currentTime;\n // this.config.loop.indicator.end = this.elements.display.played.value;\n break;\n\n case 'all':\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n this.config.loop.indicator.start = 0;\n this.config.loop.indicator.end = 100;\n break;\n\n case 'toggle':\n if (this.config.loop.active) {\n this.config.loop.start = 0;\n this.config.loop.end = null;\n } else {\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n }\n break;\n\n default:\n this.config.loop.start = 0;\n this.config.loop.end = null;\n break;\n } */\n }\n\n /**\n * Get current loop state\n */\n get loop() {\n return Boolean(this.media.loop);\n }\n\n /**\n * Set new media source\n * @param {Object} input - The new source object (see docs)\n */\n set source(input) {\n source.change.call(this, input);\n }\n\n /**\n * Get current source\n */\n get source() {\n return this.media.currentSrc;\n }\n\n /**\n * Get a download URL (either source or custom)\n */\n get download() {\n const { download } = this.config.urls;\n\n return is.url(download) ? download : this.source;\n }\n\n /**\n * Set the download URL\n */\n set download(input) {\n if (!is.url(input)) {\n return;\n }\n\n this.config.urls.download = input;\n\n controls.setDownloadUrl.call(this);\n }\n\n /**\n * Set the poster image for a video\n * @param {String} input - the URL for the new poster image\n */\n set poster(input) {\n if (!this.isVideo) {\n this.debug.warn('Poster can only be set for video');\n return;\n }\n\n ui.setPoster.call(this, input, false).catch(() => {});\n }\n\n /**\n * Get the current poster image\n */\n get poster() {\n if (!this.isVideo) {\n return null;\n }\n\n return this.media.getAttribute('poster') || this.media.getAttribute('data-poster');\n }\n\n /**\n * Get the current aspect ratio in use\n */\n get ratio() {\n if (!this.isVideo) {\n return null;\n }\n\n const ratio = reduceAspectRatio(getAspectRatio.call(this));\n\n return is.array(ratio) ? ratio.join(':') : ratio;\n }\n\n /**\n * Set video aspect ratio\n */\n set ratio(input) {\n if (!this.isVideo) {\n this.debug.warn('Aspect ratio can only be set for video');\n return;\n }\n\n if (!is.string(input) || !validateAspectRatio(input)) {\n this.debug.error(`Invalid aspect ratio specified (${input})`);\n return;\n }\n\n this.config.ratio = reduceAspectRatio(input);\n\n setAspectRatio.call(this);\n }\n\n /**\n * Set the autoplay state\n * @param {Boolean} input - Whether to autoplay or not\n */\n set autoplay(input) {\n const toggle = is.boolean(input) ? input : this.config.autoplay;\n this.config.autoplay = toggle;\n }\n\n /**\n * Get the current autoplay state\n */\n get autoplay() {\n return Boolean(this.config.autoplay);\n }\n\n /**\n * Toggle captions\n * @param {Boolean} input - Whether to enable captions\n */\n toggleCaptions(input) {\n captions.toggle.call(this, input, false);\n }\n\n /**\n * Set the caption track by index\n * @param {Number} - Caption index\n */\n set currentTrack(input) {\n captions.set.call(this, input, false);\n captions.setup();\n }\n\n /**\n * Get the current caption track index (-1 if disabled)\n */\n get currentTrack() {\n const { toggled, currentTrack } = this.captions;\n return toggled ? currentTrack : -1;\n }\n\n /**\n * Set the wanted language for captions\n * Since tracks can be added later it won't update the actual caption track until there is a matching track\n * @param {String} - Two character ISO language code (e.g. EN, FR, PT, etc)\n */\n set language(input) {\n captions.setLanguage.call(this, input, false);\n }\n\n /**\n * Get the current track's language\n */\n get language() {\n return (captions.getCurrentTrack.call(this) || {}).language;\n }\n\n /**\n * Toggle picture-in-picture playback on WebKit/MacOS\n * TODO: update player with state, support, enabled\n * TODO: detect outside changes\n */\n set pip(input) {\n // Bail if no support\n if (!support.pip) {\n return;\n }\n\n // Toggle based on current state if not passed\n const toggle = is.boolean(input) ? input : !this.pip;\n\n // Toggle based on current state\n // Safari\n if (is.function(this.media.webkitSetPresentationMode)) {\n this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive);\n }\n\n // Chrome\n if (is.function(this.media.requestPictureInPicture)) {\n if (!this.pip && toggle) {\n this.media.requestPictureInPicture();\n } else if (this.pip && !toggle) {\n document.exitPictureInPicture();\n }\n }\n }\n\n /**\n * Get the current picture-in-picture state\n */\n get pip() {\n if (!support.pip) {\n return null;\n }\n\n // Safari\n if (!is.empty(this.media.webkitPresentationMode)) {\n return this.media.webkitPresentationMode === pip.active;\n }\n\n // Chrome\n return this.media === document.pictureInPictureElement;\n }\n\n /**\n * Sets the preview thubmnails for the current source\n */\n setPreviewThumbnails(thumbnailSource) {\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n Object.assign(this.config.previewThumbnails, thumbnailSource);\n\n // Create new instance if it is still enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n /**\n * Trigger the airplay dialog\n * TODO: update player with state, support, enabled\n */\n airplay = () => {\n // Show dialog if supported\n if (support.airplay) {\n this.media.webkitShowPlaybackTargetPicker();\n }\n };\n\n /**\n * Toggle the player controls\n * @param {Boolean} [toggle] - Whether to show the controls\n */\n toggleControls = (toggle) => {\n // Don't toggle if missing UI support or if it's audio\n if (this.supported.ui && !this.isAudio) {\n // Get state before change\n const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls);\n // Negate the argument if not undefined since adding the class to hides the controls\n const force = typeof toggle === 'undefined' ? undefined : !toggle;\n // Apply and get updated state\n const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force);\n\n // Close menu\n if (\n hiding &&\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n !is.empty(this.config.settings)\n ) {\n controls.toggleMenu.call(this, false);\n }\n\n // Trigger event on change\n if (hiding !== isHidden) {\n const eventName = hiding ? 'controlshidden' : 'controlsshown';\n triggerEvent.call(this, this.media, eventName);\n }\n\n return !hiding;\n }\n\n return false;\n };\n\n /**\n * Add event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n on = (event, callback) => {\n on.call(this, this.elements.container, event, callback);\n };\n\n /**\n * Add event listeners once\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n once = (event, callback) => {\n once.call(this, this.elements.container, event, callback);\n };\n\n /**\n * Remove event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n off = (event, callback) => {\n off(this.elements.container, event, callback);\n };\n\n /**\n * Destroy an instance\n * Event listeners are removed when elements are removed\n * http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory\n * @param {Function} callback - Callback for when destroy is complete\n * @param {Boolean} soft - Whether it's a soft destroy (for source changes etc)\n */\n destroy = (callback, soft = false) => {\n if (!this.ready) {\n return;\n }\n\n const done = () => {\n // Reset overflow (incase destroyed while in fullscreen)\n document.body.style.overflow = '';\n\n // GC for embed\n this.embed = null;\n\n // If it's a soft destroy, make minimal changes\n if (soft) {\n if (Object.keys(this.elements).length) {\n // Remove elements\n removeElement(this.elements.buttons.play);\n removeElement(this.elements.captions);\n removeElement(this.elements.controls);\n removeElement(this.elements.wrapper);\n\n // Clear for GC\n this.elements.buttons.play = null;\n this.elements.captions = null;\n this.elements.controls = null;\n this.elements.wrapper = null;\n }\n\n // Callback\n if (is.function(callback)) {\n callback();\n }\n } else {\n // Unbind listeners\n unbindListeners.call(this);\n\n // Cancel current network requests\n html5.cancelRequests.call(this);\n\n // Replace the container with the original element provided\n replaceElement(this.elements.original, this.elements.container);\n\n // Event\n triggerEvent.call(this, this.elements.original, 'destroyed', true);\n\n // Callback\n if (is.function(callback)) {\n callback.call(this.elements.original);\n }\n\n // Reset state\n this.ready = false;\n\n // Clear for garbage collection\n setTimeout(() => {\n this.elements = null;\n this.media = null;\n }, 200);\n }\n };\n\n // Stop playback\n this.stop();\n\n // Clear timeouts\n clearTimeout(this.timers.loading);\n clearTimeout(this.timers.controls);\n clearTimeout(this.timers.resized);\n\n // Provider specific stuff\n if (this.isHTML5) {\n // Restore native video controls\n ui.toggleNativeControls.call(this, true);\n\n // Clean up\n done();\n } else if (this.isYouTube) {\n // Clear timers\n clearInterval(this.timers.buffering);\n clearInterval(this.timers.playing);\n\n // Destroy YouTube API\n if (this.embed !== null && is.function(this.embed.destroy)) {\n this.embed.destroy();\n }\n\n // Clean up\n done();\n } else if (this.isVimeo) {\n // Destroy Vimeo API\n // then clean up (wait, to prevent postmessage errors)\n if (this.embed !== null) {\n this.embed.unload().then(done);\n }\n\n // Vimeo does not always return\n setTimeout(done, 200);\n }\n };\n\n /**\n * Check for support for a mime type (HTML5 only)\n * @param {String} type - Mime type\n */\n supports = (type) => support.mime.call(this, type);\n\n /**\n * Check for support\n * @param {String} type - Player type (audio/video)\n * @param {String} provider - Provider (html5/youtube/vimeo)\n * @param {Boolean} inline - Where player has `playsinline` sttribute\n */\n static supported(type, provider, inline) {\n return support.check(type, provider, inline);\n }\n\n /**\n * Load an SVG sprite into the page\n * @param {String} url - URL for the SVG sprite\n * @param {String} [id] - Unique ID\n */\n static loadSprite(url, id) {\n return loadSprite(url, id);\n }\n\n /**\n * Setup multiple instances\n * @param {*} selector\n * @param {Object} options\n */\n static setup(selector, options = {}) {\n let targets = null;\n\n if (is.string(selector)) {\n targets = Array.from(document.querySelectorAll(selector));\n } else if (is.nodeList(selector)) {\n targets = Array.from(selector);\n } else if (is.array(selector)) {\n targets = selector.filter(is.element);\n }\n\n if (is.empty(targets)) {\n return null;\n }\n\n return targets.map((t) => new Plyr(t, options));\n }\n}\n\nPlyr.defaults = cloneDeep(defaults);\n\nexport default Plyr;\n","/**\n * Returns a number whose value is limited to the given range.\n *\n * Example: limit the output of this computation to between 0 and 255\n * (x * 255).clamp(0, 255)\n *\n * @param {Number} input\n * @param {Number} min The lower boundary of the output range\n * @param {Number} max The upper boundary of the output range\n * @returns A number in the range [min, max]\n * @type Number\n */\nexport function clamp(input = 0, min = 0, max = 255) {\n return Math.min(Math.max(input, min), max);\n}\n\nexport default { clamp };\n"]}
\ No newline at end of file diff --git a/extlib/plyr/plyr.min.mjs b/extlib/plyr/plyr.min.mjs new file mode 100644 index 00000000..b548c059 --- /dev/null +++ b/extlib/plyr/plyr.min.mjs @@ -0,0 +1 @@ +function _defineProperty$1(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}function _createClass(e,t,i){return t&&_defineProperties(e.prototype,t),i&&_defineProperties(e,i),e}function _defineProperty(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function ownKeys(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(i),!0).forEach((function(t){_defineProperty(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ownKeys(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}var defaults$1={addCSS:!0,thumbWidth:15,watch:!0};function matches$1(e,t){return function(){return Array.from(document.querySelectorAll(t)).includes(this)}.call(e,t)}function trigger(e,t){if(e&&t){var i=new Event(t,{bubbles:!0});e.dispatchEvent(i)}}var getConstructor$1=function(e){return null!=e?e.constructor:null},instanceOf$1=function(e,t){return!!(e&&t&&e instanceof t)},isNullOrUndefined$1=function(e){return null==e},isObject$1=function(e){return getConstructor$1(e)===Object},isNumber$1=function(e){return getConstructor$1(e)===Number&&!Number.isNaN(e)},isString$1=function(e){return getConstructor$1(e)===String},isBoolean$1=function(e){return getConstructor$1(e)===Boolean},isFunction$1=function(e){return getConstructor$1(e)===Function},isArray$1=function(e){return Array.isArray(e)},isNodeList$1=function(e){return instanceOf$1(e,NodeList)},isElement$1=function(e){return instanceOf$1(e,Element)},isEvent$1=function(e){return instanceOf$1(e,Event)},isEmpty$1=function(e){return isNullOrUndefined$1(e)||(isString$1(e)||isArray$1(e)||isNodeList$1(e))&&!e.length||isObject$1(e)&&!Object.keys(e).length},is$1={nullOrUndefined:isNullOrUndefined$1,object:isObject$1,number:isNumber$1,string:isString$1,boolean:isBoolean$1,function:isFunction$1,array:isArray$1,nodeList:isNodeList$1,element:isElement$1,event:isEvent$1,empty:isEmpty$1};function getDecimalPlaces(e){var t="".concat(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0}function round(e,t){if(1>t){var i=getDecimalPlaces(t);return parseFloat(e.toFixed(i))}return Math.round(e/t)*t}var RangeTouch=function(){function e(t,i){_classCallCheck(this,e),is$1.element(t)?this.element=t:is$1.string(t)&&(this.element=document.querySelector(t)),is$1.element(this.element)&&is$1.empty(this.element.rangeTouch)&&(this.config=_objectSpread2({},defaults$1,{},i),this.init())}return _createClass(e,[{key:"init",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect="none",this.element.style.webKitUserSelect="none",this.element.style.touchAction="manipulation"),this.listeners(!0),this.element.rangeTouch=this)}},{key:"destroy",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect="",this.element.style.webKitUserSelect="",this.element.style.touchAction=""),this.listeners(!1),this.element.rangeTouch=null)}},{key:"listeners",value:function(e){var t=this,i=e?"addEventListener":"removeEventListener";["touchstart","touchmove","touchend"].forEach((function(e){t.element[i](e,(function(e){return t.set(e)}),!1)}))}},{key:"get",value:function(t){if(!e.enabled||!is$1.event(t))return null;var i,s=t.target,n=t.changedTouches[0],r=parseFloat(s.getAttribute("min"))||0,a=parseFloat(s.getAttribute("max"))||100,o=parseFloat(s.getAttribute("step"))||1,l=s.getBoundingClientRect(),c=100/l.width*(this.config.thumbWidth/2)/100;return 0>(i=100/l.width*(n.clientX-l.left))?i=0:100<i&&(i=100),50>i?i-=(100-2*i)*c:50<i&&(i+=2*(i-50)*c),r+round(i/100*(a-r),o)}},{key:"set",value:function(t){e.enabled&&is$1.event(t)&&!t.target.disabled&&(t.preventDefault(),t.target.value=this.get(t),trigger(t.target,"touchend"===t.type?"change":"input"))}}],[{key:"setup",value:function(t){var i=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},s=null;if(is$1.empty(t)||is$1.string(t)?s=Array.from(document.querySelectorAll(is$1.string(t)?t:'input[type="range"]')):is$1.element(t)?s=[t]:is$1.nodeList(t)?s=Array.from(t):is$1.array(t)&&(s=t.filter(is$1.element)),is$1.empty(s))return null;var n=_objectSpread2({},defaults$1,{},i);if(is$1.string(t)&&n.watch){var r=new MutationObserver((function(i){Array.from(i).forEach((function(i){Array.from(i.addedNodes).forEach((function(i){is$1.element(i)&&matches$1(i,t)&&new e(i,n)}))}))}));r.observe(document.body,{childList:!0,subtree:!0})}return s.map((function(t){return new e(t,i)}))}},{key:"enabled",get:function(){return"ontouchstart"in document.documentElement}}]),e}();const getConstructor=e=>null!=e?e.constructor:null,instanceOf=(e,t)=>Boolean(e&&t&&e instanceof t),isNullOrUndefined=e=>null==e,isObject=e=>getConstructor(e)===Object,isNumber=e=>getConstructor(e)===Number&&!Number.isNaN(e),isString=e=>getConstructor(e)===String,isBoolean=e=>getConstructor(e)===Boolean,isFunction=e=>getConstructor(e)===Function,isArray=e=>Array.isArray(e),isWeakMap=e=>instanceOf(e,WeakMap),isNodeList=e=>instanceOf(e,NodeList),isTextNode=e=>getConstructor(e)===Text,isEvent=e=>instanceOf(e,Event),isKeyboardEvent=e=>instanceOf(e,KeyboardEvent),isCue=e=>instanceOf(e,window.TextTrackCue)||instanceOf(e,window.VTTCue),isTrack=e=>instanceOf(e,TextTrack)||!isNullOrUndefined(e)&&isString(e.kind),isPromise=e=>instanceOf(e,Promise)&&isFunction(e.then),isElement=e=>null!==e&&"object"==typeof e&&1===e.nodeType&&"object"==typeof e.style&&"object"==typeof e.ownerDocument,isEmpty=e=>isNullOrUndefined(e)||(isString(e)||isArray(e)||isNodeList(e))&&!e.length||isObject(e)&&!Object.keys(e).length,isUrl=e=>{if(instanceOf(e,window.URL))return!0;if(!isString(e))return!1;let t=e;e.startsWith("http://")&&e.startsWith("https://")||(t=`http://${e}`);try{return!isEmpty(new URL(t).hostname)}catch(e){return!1}};var is={nullOrUndefined:isNullOrUndefined,object:isObject,number:isNumber,string:isString,boolean:isBoolean,function:isFunction,array:isArray,weakMap:isWeakMap,nodeList:isNodeList,element:isElement,textNode:isTextNode,event:isEvent,keyboardEvent:isKeyboardEvent,cue:isCue,track:isTrack,promise:isPromise,url:isUrl,empty:isEmpty};const transitionEndEvent=(()=>{const e=document.createElement("span"),t={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},i=Object.keys(t).find((t=>void 0!==e.style[t]));return!!is.string(i)&&t[i]})();function repaint(e,t){setTimeout((()=>{try{e.hidden=!0,e.offsetHeight,e.hidden=!1}catch(e){}}),t)}const browser={isIE:Boolean(window.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:"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1||/(iPad|iPhone|iPod)/gi.test(navigator.platform)};function cloneDeep(e){return JSON.parse(JSON.stringify(e))}function getDeep(e,t){return t.split(".").reduce(((e,t)=>e&&e[t]),e)}function extend(e={},...t){if(!t.length)return e;const i=t.shift();return is.object(i)?(Object.keys(i).forEach((t=>{is.object(i[t])?(Object.keys(e).includes(t)||Object.assign(e,{[t]:{}}),extend(e[t],i[t])):Object.assign(e,{[t]:i[t]})})),extend(e,...t)):e}function wrap(e,t){const i=e.length?e:[e];Array.from(i).reverse().forEach(((e,i)=>{const s=i>0?t.cloneNode(!0):t,n=e.parentNode,r=e.nextSibling;s.appendChild(e),r?n.insertBefore(s,r):n.appendChild(s)}))}function setAttributes(e,t){is.element(e)&&!is.empty(t)&&Object.entries(t).filter((([,e])=>!is.nullOrUndefined(e))).forEach((([t,i])=>e.setAttribute(t,i)))}function createElement(e,t,i){const s=document.createElement(e);return is.object(t)&&setAttributes(s,t),is.string(i)&&(s.innerText=i),s}function insertAfter(e,t){is.element(e)&&is.element(t)&&t.parentNode.insertBefore(e,t.nextSibling)}function insertElement(e,t,i,s){is.element(t)&&t.appendChild(createElement(e,i,s))}function removeElement(e){is.nodeList(e)||is.array(e)?Array.from(e).forEach(removeElement):is.element(e)&&is.element(e.parentNode)&&e.parentNode.removeChild(e)}function emptyElement(e){if(!is.element(e))return;let{length:t}=e.childNodes;for(;t>0;)e.removeChild(e.lastChild),t-=1}function replaceElement(e,t){return is.element(t)&&is.element(t.parentNode)&&is.element(e)?(t.parentNode.replaceChild(e,t),e):null}function getAttributesFromSelector(e,t){if(!is.string(e)||is.empty(e))return{};const i={},s=extend({},t);return e.split(",").forEach((e=>{const t=e.trim(),n=t.replace(".",""),r=t.replace(/[[\]]/g,"").split("="),[a]=r,o=r.length>1?r[1].replace(/["']/g,""):"";switch(t.charAt(0)){case".":is.string(s.class)?i.class=`${s.class} ${n}`:i.class=n;break;case"#":i.id=t.replace("#","");break;case"[":i[a]=o}})),extend(s,i)}function toggleHidden(e,t){if(!is.element(e))return;let i=t;is.boolean(i)||(i=!e.hidden),e.hidden=i}function toggleClass(e,t,i){if(is.nodeList(e))return Array.from(e).map((e=>toggleClass(e,t,i)));if(is.element(e)){let s="toggle";return void 0!==i&&(s=i?"add":"remove"),e.classList[s](t),e.classList.contains(t)}return!1}function hasClass(e,t){return is.element(e)&&e.classList.contains(t)}function matches(e,t){const{prototype:i}=Element;return(i.matches||i.webkitMatchesSelector||i.mozMatchesSelector||i.msMatchesSelector||function(){return Array.from(document.querySelectorAll(t)).includes(this)}).call(e,t)}function closest$1(e,t){const{prototype:i}=Element;return(i.closest||function(){let e=this;do{if(matches.matches(e,t))return e;e=e.parentElement||e.parentNode}while(null!==e&&1===e.nodeType);return null}).call(e,t)}function getElements(e){return this.elements.container.querySelectorAll(e)}function getElement(e){return this.elements.container.querySelector(e)}function setFocus(e=null,t=!1){is.element(e)&&(e.focus({preventScroll:!0}),t&&toggleClass(e,this.config.classNames.tabFocus))}const defaultCodecs={"audio/ogg":"vorbis","audio/wav":"1","video/webm":"vp8, vorbis","video/mp4":"avc1.42E01E, mp4a.40.2","video/ogg":"theora"},support={audio:"canPlayType"in document.createElement("audio"),video:"canPlayType"in document.createElement("video"),check(e,t,i){const s=browser.isIPhone&&i&&support.playsinline,n=support[e]||"html5"!==t;return{api:n,ui:n&&support.rangeInput&&("video"!==e||!browser.isIPhone||s)}},pip:!(browser.isIPhone||!is.function(createElement("video").webkitSetPresentationMode)&&(!document.pictureInPictureEnabled||createElement("video").disablePictureInPicture)),airplay:is.function(window.WebKitPlaybackTargetAvailabilityEvent),playsinline:"playsInline"in document.createElement("video"),mime(e){if(is.empty(e))return!1;const[t]=e.split("/");let i=e;if(!this.isHTML5||t!==this.type)return!1;Object.keys(defaultCodecs).includes(i)&&(i+=`; codecs="${defaultCodecs[e]}"`);try{return Boolean(i&&this.media.canPlayType(i).replace(/no/,""))}catch(e){return!1}},textTracks:"textTracks"in document.createElement("video"),rangeInput:(()=>{const e=document.createElement("input");return e.type="range","range"===e.type})(),touch:"ontouchstart"in document.documentElement,transitions:!1!==transitionEndEvent,reducedMotion:"matchMedia"in window&&window.matchMedia("(prefers-reduced-motion)").matches},supportsPassiveListeners=(()=>{let e=!1;try{const t=Object.defineProperty({},"passive",{get:()=>(e=!0,null)});window.addEventListener("test",null,t),window.removeEventListener("test",null,t)}catch(e){}return e})();function toggleListener(e,t,i,s=!1,n=!0,r=!1){if(!e||!("addEventListener"in e)||is.empty(t)||!is.function(i))return;const a=t.split(" ");let o=r;supportsPassiveListeners&&(o={passive:n,capture:r}),a.forEach((t=>{this&&this.eventListeners&&s&&this.eventListeners.push({element:e,type:t,callback:i,options:o}),e[s?"addEventListener":"removeEventListener"](t,i,o)}))}function on(e,t="",i,s=!0,n=!1){toggleListener.call(this,e,t,i,!0,s,n)}function off(e,t="",i,s=!0,n=!1){toggleListener.call(this,e,t,i,!1,s,n)}function once(e,t="",i,s=!0,n=!1){const r=(...a)=>{off(e,t,r,s,n),i.apply(this,a)};toggleListener.call(this,e,t,r,!0,s,n)}function triggerEvent(e,t="",i=!1,s={}){if(!is.element(e)||is.empty(t))return;const n=new CustomEvent(t,{bubbles:i,detail:{...s,plyr:this}});e.dispatchEvent(n)}function unbindListeners(){this&&this.eventListeners&&(this.eventListeners.forEach((e=>{const{element:t,type:i,callback:s,options:n}=e;t.removeEventListener(i,s,n)})),this.eventListeners=[])}function ready(){return new Promise((e=>this.ready?setTimeout(e,0):on.call(this,this.elements.container,"ready",e))).then((()=>{}))}function silencePromise(e){is.promise(e)&&e.then(null,(()=>{}))}function dedupe(e){return is.array(e)?e.filter(((t,i)=>e.indexOf(t)===i)):e}function closest(e,t){return is.array(e)&&e.length?e.reduce(((e,i)=>Math.abs(i-t)<Math.abs(e-t)?i:e)):null}function supportsCSS(e){return!(!window||!window.CSS)&&window.CSS.supports(e)}const standardRatios=[[1,1],[4,3],[3,4],[5,4],[4,5],[3,2],[2,3],[16,10],[10,16],[16,9],[9,16],[21,9],[9,21],[32,9],[9,32]].reduce(((e,[t,i])=>({...e,[t/i]:[t,i]})),{});function validateAspectRatio(e){if(!(is.array(e)||is.string(e)&&e.includes(":")))return!1;return(is.array(e)?e:e.split(":")).map(Number).every(is.number)}function reduceAspectRatio(e){if(!is.array(e)||!e.every(is.number))return null;const[t,i]=e,s=(e,t)=>0===t?e:s(t,e%t),n=s(t,i);return[t/n,i/n]}function getAspectRatio(e){const t=e=>validateAspectRatio(e)?e.split(":").map(Number):null;let i=t(e);if(null===i&&(i=t(this.config.ratio)),null===i&&!is.empty(this.embed)&&is.array(this.embed.ratio)&&({ratio:i}=this.embed),null===i&&this.isHTML5){const{videoWidth:e,videoHeight:t}=this.media;i=[e,t]}return reduceAspectRatio(i)}function setAspectRatio(e){if(!this.isVideo)return{};const{wrapper:t}=this.elements,i=getAspectRatio.call(this,e);if(!is.array(i))return{};const[s,n]=reduceAspectRatio(i),r=100/s*n;if(supportsCSS(`aspect-ratio: ${s}/${n}`)?t.style.aspectRatio=`${s}/${n}`:t.style.paddingBottom=`${r}%`,this.isVimeo&&!this.config.vimeo.premium&&this.supported.ui){const e=100/this.media.offsetWidth*parseInt(window.getComputedStyle(this.media).paddingBottom,10),i=(e-r)/(e/50);this.fullscreen.active?t.style.paddingBottom=null:this.media.style.transform=`translateY(-${i}%)`}else this.isHTML5&&t.classList.add(this.config.classNames.videoFixedRatio);return{padding:r,ratio:i}}function roundAspectRatio(e,t,i=.05){const s=e/t,n=closest(Object.keys(standardRatios),s);return Math.abs(n-s)<=i?standardRatios[n]:[e,t]}function getViewportSize(){return[Math.max(document.documentElement.clientWidth||0,window.innerWidth||0),Math.max(document.documentElement.clientHeight||0,window.innerHeight||0)]}const html5={getSources(){if(!this.isHTML5)return[];return Array.from(this.media.querySelectorAll("source")).filter((e=>{const t=e.getAttribute("type");return!!is.empty(t)||support.mime.call(this,t)}))},getQualityOptions(){return this.config.quality.forced?this.config.quality.options:html5.getSources.call(this).map((e=>Number(e.getAttribute("data-res")))).filter(Boolean)},setup(){if(!this.isHTML5)return;const e=this;e.options.speed=e.config.speed.options,is.empty(this.config.ratio)||setAspectRatio.call(e),Object.defineProperty(e.media,"quality",{get(){const t=html5.getSources.call(e).find((t=>t.getAttribute("src")===e.source));return t&&Number(t.getAttribute("data-res"))},set(t){if(e.quality!==t){if(e.config.quality.forced&&is.function(e.config.quality.onChange))e.config.quality.onChange(t);else{const i=html5.getSources.call(e).find((e=>Number(e.getAttribute("data-res"))===t));if(!i)return;const{currentTime:s,paused:n,preload:r,readyState:a,playbackRate:o}=e.media;e.media.src=i.getAttribute("src"),("none"!==r||a)&&(e.once("loadedmetadata",(()=>{e.speed=o,e.currentTime=s,n||silencePromise(e.play())})),e.media.load())}triggerEvent.call(e,e.media,"qualitychange",!1,{quality:t})}}})},cancelRequests(){this.isHTML5&&(removeElement(html5.getSources.call(this)),this.media.setAttribute("src",this.config.blankVideo),this.media.load(),this.debug.log("Cancelled network requests"))}};function generateId(e){return`${e}-${Math.floor(1e4*Math.random())}`}function format(e,...t){return is.empty(e)?e:e.toString().replace(/{(\d+)}/g,((e,i)=>t[i].toString()))}function getPercentage(e,t){return 0===e||0===t||Number.isNaN(e)||Number.isNaN(t)?0:(e/t*100).toFixed(2)}const replaceAll=(e="",t="",i="")=>e.replace(new RegExp(t.toString().replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1"),"g"),i.toString()),toTitleCase=(e="")=>e.toString().replace(/\w\S*/g,(e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()));function toPascalCase(e=""){let t=e.toString();return t=replaceAll(t,"-"," "),t=replaceAll(t,"_"," "),t=toTitleCase(t),replaceAll(t," ","")}function toCamelCase(e=""){let t=e.toString();return t=toPascalCase(t),t.charAt(0).toLowerCase()+t.slice(1)}function stripHTML(e){const t=document.createDocumentFragment(),i=document.createElement("div");return t.appendChild(i),i.innerHTML=e,t.firstChild.innerText}function getHTML(e){const t=document.createElement("div");return t.appendChild(e),t.innerHTML}const resources={pip:"PIP",airplay:"AirPlay",html5:"HTML5",vimeo:"Vimeo",youtube:"YouTube"},i18n={get(e="",t={}){if(is.empty(e)||is.empty(t))return"";let i=getDeep(t.i18n,e);if(is.empty(i))return Object.keys(resources).includes(e)?resources[e]:"";const s={"{seektime}":t.seekTime,"{title}":t.title};return Object.entries(s).forEach((([e,t])=>{i=replaceAll(i,e,t)})),i}};class Storage{constructor(e){_defineProperty$1(this,"get",(e=>{if(!Storage.supported||!this.enabled)return null;const t=window.localStorage.getItem(this.key);if(is.empty(t))return null;const i=JSON.parse(t);return is.string(e)&&e.length?i[e]:i})),_defineProperty$1(this,"set",(e=>{if(!Storage.supported||!this.enabled)return;if(!is.object(e))return;let t=this.get();is.empty(t)&&(t={}),extend(t,e);try{window.localStorage.setItem(this.key,JSON.stringify(t))}catch(e){}})),this.enabled=e.config.storage.enabled,this.key=e.config.storage.key}static get supported(){try{if(!("localStorage"in window))return!1;const e="___test";return window.localStorage.setItem(e,e),window.localStorage.removeItem(e),!0}catch(e){return!1}}}function fetch(e,t="text"){return new Promise(((i,s)=>{try{const s=new XMLHttpRequest;if(!("withCredentials"in s))return;s.addEventListener("load",(()=>{if("text"===t)try{i(JSON.parse(s.responseText))}catch(e){i(s.responseText)}else i(s.response)})),s.addEventListener("error",(()=>{throw new Error(s.status)})),s.open("GET",e,!0),s.responseType=t,s.send()}catch(e){s(e)}}))}function loadSprite(e,t){if(!is.string(e))return;const i=is.string(t);let s=!1;const n=()=>null!==document.getElementById(t),r=(e,t)=>{e.innerHTML=t,i&&n()||document.body.insertAdjacentElement("afterbegin",e)};if(!i||!n()){const n=Storage.supported,a=document.createElement("div");if(a.setAttribute("hidden",""),i&&a.setAttribute("id",t),n){const e=window.localStorage.getItem(`cache-${t}`);if(s=null!==e,s){const t=JSON.parse(e);r(a,t.content)}}fetch(e).then((e=>{if(!is.empty(e)){if(n)try{window.localStorage.setItem(`cache-${t}`,JSON.stringify({content:e}))}catch(e){}r(a,e)}})).catch((()=>{}))}}const getHours=e=>Math.trunc(e/60/60%60,10),getMinutes=e=>Math.trunc(e/60%60,10),getSeconds=e=>Math.trunc(e%60,10);function formatTime(e=0,t=!1,i=!1){if(!is.number(e))return formatTime(void 0,t,i);const s=e=>`0${e}`.slice(-2);let n=getHours(e);const r=(a=e,Math.trunc(a/60%60,10));var a;const o=getSeconds(e);return n=t||n>0?`${n}:`:"",`${i&&e>0?"-":""}${n}${s(r)}:${s(o)}`}const controls={getIconUrl(){const e=new URL(this.config.iconUrl,window.location),t=window.location.host?window.location.host:window.top.location.host,i=e.host!==t||browser.isIE&&!window.svg4everybody;return{url:this.config.iconUrl,cors:i}},findElements(){try{return this.elements.controls=getElement.call(this,this.config.selectors.controls.wrapper),this.elements.buttons={play:getElements.call(this,this.config.selectors.buttons.play),pause:getElement.call(this,this.config.selectors.buttons.pause),restart:getElement.call(this,this.config.selectors.buttons.restart),rewind:getElement.call(this,this.config.selectors.buttons.rewind),fastForward:getElement.call(this,this.config.selectors.buttons.fastForward),mute:getElement.call(this,this.config.selectors.buttons.mute),pip:getElement.call(this,this.config.selectors.buttons.pip),airplay:getElement.call(this,this.config.selectors.buttons.airplay),settings:getElement.call(this,this.config.selectors.buttons.settings),captions:getElement.call(this,this.config.selectors.buttons.captions),fullscreen:getElement.call(this,this.config.selectors.buttons.fullscreen)},this.elements.progress=getElement.call(this,this.config.selectors.progress),this.elements.inputs={seek:getElement.call(this,this.config.selectors.inputs.seek),volume:getElement.call(this,this.config.selectors.inputs.volume)},this.elements.display={buffer:getElement.call(this,this.config.selectors.display.buffer),currentTime:getElement.call(this,this.config.selectors.display.currentTime),duration:getElement.call(this,this.config.selectors.display.duration)},is.element(this.elements.progress)&&(this.elements.display.seekTooltip=this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`)),!0}catch(e){return this.debug.warn("It looks like there is a problem with your custom controls HTML",e),this.toggleNativeControls(!0),!1}},createIcon(e,t){const i="http://www.w3.org/2000/svg",s=controls.getIconUrl.call(this),n=`${s.cors?"":s.url}#${this.config.iconPrefix}`,r=document.createElementNS(i,"svg");setAttributes(r,extend(t,{"aria-hidden":"true",focusable:"false"}));const a=document.createElementNS(i,"use"),o=`${n}-${e}`;return"href"in a&&a.setAttributeNS("http://www.w3.org/1999/xlink","href",o),a.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",o),r.appendChild(a),r},createLabel(e,t={}){const i=i18n.get(e,this.config);return createElement("span",{...t,class:[t.class,this.config.classNames.hidden].filter(Boolean).join(" ")},i)},createBadge(e){if(is.empty(e))return null;const t=createElement("span",{class:this.config.classNames.menu.value});return t.appendChild(createElement("span",{class:this.config.classNames.menu.badge},e)),t},createButton(e,t){const i=extend({},t);let s=toCamelCase(e);const n={element:"button",toggle:!1,label:null,icon:null,labelPressed:null,iconPressed:null};switch(["element","icon","label"].forEach((e=>{Object.keys(i).includes(e)&&(n[e]=i[e],delete i[e])})),"button"!==n.element||Object.keys(i).includes("type")||(i.type="button"),Object.keys(i).includes("class")?i.class.split(" ").some((e=>e===this.config.classNames.control))||extend(i,{class:`${i.class} ${this.config.classNames.control}`}):i.class=this.config.classNames.control,e){case"play":n.toggle=!0,n.label="play",n.labelPressed="pause",n.icon="play",n.iconPressed="pause";break;case"mute":n.toggle=!0,n.label="mute",n.labelPressed="unmute",n.icon="volume",n.iconPressed="muted";break;case"captions":n.toggle=!0,n.label="enableCaptions",n.labelPressed="disableCaptions",n.icon="captions-off",n.iconPressed="captions-on";break;case"fullscreen":n.toggle=!0,n.label="enterFullscreen",n.labelPressed="exitFullscreen",n.icon="enter-fullscreen",n.iconPressed="exit-fullscreen";break;case"play-large":i.class+=` ${this.config.classNames.control}--overlaid`,s="play",n.label="play",n.icon="play";break;default:is.empty(n.label)&&(n.label=s),is.empty(n.icon)&&(n.icon=e)}const r=createElement(n.element);return n.toggle?(r.appendChild(controls.createIcon.call(this,n.iconPressed,{class:"icon--pressed"})),r.appendChild(controls.createIcon.call(this,n.icon,{class:"icon--not-pressed"})),r.appendChild(controls.createLabel.call(this,n.labelPressed,{class:"label--pressed"})),r.appendChild(controls.createLabel.call(this,n.label,{class:"label--not-pressed"}))):(r.appendChild(controls.createIcon.call(this,n.icon)),r.appendChild(controls.createLabel.call(this,n.label))),extend(i,getAttributesFromSelector(this.config.selectors.buttons[s],i)),setAttributes(r,i),"play"===s?(is.array(this.elements.buttons[s])||(this.elements.buttons[s]=[]),this.elements.buttons[s].push(r)):this.elements.buttons[s]=r,r},createRange(e,t){const i=createElement("input",extend(getAttributesFromSelector(this.config.selectors.inputs[e]),{type:"range",min:0,max:100,step:.01,value:0,autocomplete:"off",role:"slider","aria-label":i18n.get(e,this.config),"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":0},t));return this.elements.inputs[e]=i,controls.updateRangeFill.call(this,i),RangeTouch.setup(i),i},createProgress(e,t){const i=createElement("progress",extend(getAttributesFromSelector(this.config.selectors.display[e]),{min:0,max:100,value:0,role:"progressbar","aria-hidden":!0},t));if("volume"!==e){i.appendChild(createElement("span",null,"0"));const t={played:"played",buffer:"buffered"}[e],s=t?i18n.get(t,this.config):"";i.innerText=`% ${s.toLowerCase()}`}return this.elements.display[e]=i,i},createTime(e,t){const i=getAttributesFromSelector(this.config.selectors.display[e],t),s=createElement("div",extend(i,{class:`${i.class?i.class:""} ${this.config.classNames.display.time} `.trim(),"aria-label":i18n.get(e,this.config)}),"00:00");return this.elements.display[e]=s,s},bindMenuItemShortcuts(e,t){on.call(this,e,"keydown keyup",(i=>{if(![32,38,39,40].includes(i.which))return;if(i.preventDefault(),i.stopPropagation(),"keydown"===i.type)return;const s=matches(e,'[role="menuitemradio"]');if(!s&&[32,39].includes(i.which))controls.showMenuPanel.call(this,t,!0);else{let t;32!==i.which&&(40===i.which||s&&39===i.which?(t=e.nextElementSibling,is.element(t)||(t=e.parentNode.firstElementChild)):(t=e.previousElementSibling,is.element(t)||(t=e.parentNode.lastElementChild)),setFocus.call(this,t,!0))}}),!1),on.call(this,e,"keyup",(e=>{13===e.which&&controls.focusFirstMenuItem.call(this,null,!0)}))},createMenuItem({value:e,list:t,type:i,title:s,badge:n=null,checked:r=!1}){const a=getAttributesFromSelector(this.config.selectors.inputs[i]),o=createElement("button",extend(a,{type:"button",role:"menuitemradio",class:`${this.config.classNames.control} ${a.class?a.class:""}`.trim(),"aria-checked":r,value:e})),l=createElement("span");l.innerHTML=s,is.element(n)&&l.appendChild(n),o.appendChild(l),Object.defineProperty(o,"checked",{enumerable:!0,get:()=>"true"===o.getAttribute("aria-checked"),set(e){e&&Array.from(o.parentNode.children).filter((e=>matches(e,'[role="menuitemradio"]'))).forEach((e=>e.setAttribute("aria-checked","false"))),o.setAttribute("aria-checked",e?"true":"false")}}),this.listeners.bind(o,"click keyup",(t=>{if(!is.keyboardEvent(t)||32===t.which){switch(t.preventDefault(),t.stopPropagation(),o.checked=!0,i){case"language":this.currentTrack=Number(e);break;case"quality":this.quality=e;break;case"speed":this.speed=parseFloat(e)}controls.showMenuPanel.call(this,"home",is.keyboardEvent(t))}}),i,!1),controls.bindMenuItemShortcuts.call(this,o,i),t.appendChild(o)},formatTime(e=0,t=!1){if(!is.number(e))return e;return formatTime(e,getHours(this.duration)>0,t)},updateTimeDisplay(e=null,t=0,i=!1){is.element(e)&&is.number(t)&&(e.innerText=controls.formatTime(t,i))},updateVolume(){this.supported.ui&&(is.element(this.elements.inputs.volume)&&controls.setRange.call(this,this.elements.inputs.volume,this.muted?0:this.volume),is.element(this.elements.buttons.mute)&&(this.elements.buttons.mute.pressed=this.muted||0===this.volume))},setRange(e,t=0){is.element(e)&&(e.value=t,controls.updateRangeFill.call(this,e))},updateProgress(e){if(!this.supported.ui||!is.event(e))return;let t=0;const i=(e,t)=>{const i=is.number(t)?t:0,s=is.element(e)?e:this.elements.display.buffer;if(is.element(s)){s.value=i;const e=s.getElementsByTagName("span")[0];is.element(e)&&(e.childNodes[0].nodeValue=i)}};if(e)switch(e.type){case"timeupdate":case"seeking":case"seeked":t=getPercentage(this.currentTime,this.duration),"timeupdate"===e.type&&controls.setRange.call(this,this.elements.inputs.seek,t);break;case"playing":case"progress":i(this.elements.display.buffer,100*this.buffered)}},updateRangeFill(e){const t=is.event(e)?e.target:e;if(is.element(t)&&"range"===t.getAttribute("type")){if(matches(t,this.config.selectors.inputs.seek)){t.setAttribute("aria-valuenow",this.currentTime);const e=controls.formatTime(this.currentTime),i=controls.formatTime(this.duration),s=i18n.get("seekLabel",this.config);t.setAttribute("aria-valuetext",s.replace("{currentTime}",e).replace("{duration}",i))}else if(matches(t,this.config.selectors.inputs.volume)){const e=100*t.value;t.setAttribute("aria-valuenow",e),t.setAttribute("aria-valuetext",`${e.toFixed(1)}%`)}else t.setAttribute("aria-valuenow",t.value);browser.isWebkit&&t.style.setProperty("--value",t.value/t.max*100+"%")}},updateSeekTooltip(e){if(!this.config.tooltips.seek||!is.element(this.elements.inputs.seek)||!is.element(this.elements.display.seekTooltip)||0===this.duration)return;const t=`${this.config.classNames.tooltip}--visible`,i=e=>toggleClass(this.elements.display.seekTooltip,t,e);if(this.touch)return void i(!1);let s=0;const n=this.elements.progress.getBoundingClientRect();if(is.event(e))s=100/n.width*(e.pageX-n.left);else{if(!hasClass(this.elements.display.seekTooltip,t))return;s=parseFloat(this.elements.display.seekTooltip.style.left,10)}s<0?s=0:s>100&&(s=100),controls.updateTimeDisplay.call(this,this.elements.display.seekTooltip,this.duration/100*s),this.elements.display.seekTooltip.style.left=`${s}%`,is.event(e)&&["mouseenter","mouseleave"].includes(e.type)&&i("mouseenter"===e.type)},timeUpdate(e){const t=!is.element(this.elements.display.duration)&&this.config.invertTime;controls.updateTimeDisplay.call(this,this.elements.display.currentTime,t?this.duration-this.currentTime:this.currentTime,t),e&&"timeupdate"===e.type&&this.media.seeking||controls.updateProgress.call(this,e)},durationUpdate(){if(!this.supported.ui||!this.config.invertTime&&this.currentTime)return;if(this.duration>=2**32)return toggleHidden(this.elements.display.currentTime,!0),void toggleHidden(this.elements.progress,!0);is.element(this.elements.inputs.seek)&&this.elements.inputs.seek.setAttribute("aria-valuemax",this.duration);const e=is.element(this.elements.display.duration);!e&&this.config.displayDuration&&this.paused&&controls.updateTimeDisplay.call(this,this.elements.display.currentTime,this.duration),e&&controls.updateTimeDisplay.call(this,this.elements.display.duration,this.duration),controls.updateSeekTooltip.call(this)},toggleMenuButton(e,t){toggleHidden(this.elements.settings.buttons[e],!t)},updateSetting(e,t,i){const s=this.elements.settings.panels[e];let n=null,r=t;if("captions"===e)n=this.currentTrack;else{if(n=is.empty(i)?this[e]:i,is.empty(n)&&(n=this.config[e].default),!is.empty(this.options[e])&&!this.options[e].includes(n))return void this.debug.warn(`Unsupported value of '${n}' for ${e}`);if(!this.config[e].options.includes(n))return void this.debug.warn(`Disabled value of '${n}' for ${e}`)}if(is.element(r)||(r=s&&s.querySelector('[role="menu"]')),!is.element(r))return;this.elements.settings.buttons[e].querySelector(`.${this.config.classNames.menu.value}`).innerHTML=controls.getLabel.call(this,e,n);const a=r&&r.querySelector(`[value="${n}"]`);is.element(a)&&(a.checked=!0)},getLabel(e,t){switch(e){case"speed":return 1===t?i18n.get("normal",this.config):`${t}×`;case"quality":if(is.number(t)){const e=i18n.get(`qualityLabel.${t}`,this.config);return e.length?e:`${t}p`}return toTitleCase(t);case"captions":return captions.getLabel.call(this);default:return null}},setQualityMenu(e){if(!is.element(this.elements.settings.panels.quality))return;const t="quality",i=this.elements.settings.panels.quality.querySelector('[role="menu"]');is.array(e)&&(this.options.quality=dedupe(e).filter((e=>this.config.quality.options.includes(e))));const s=!is.empty(this.options.quality)&&this.options.quality.length>1;if(controls.toggleMenuButton.call(this,t,s),emptyElement(i),controls.checkMenu.call(this),!s)return;const n=e=>{const t=i18n.get(`qualityBadge.${e}`,this.config);return t.length?controls.createBadge.call(this,t):null};this.options.quality.sort(((e,t)=>{const i=this.config.quality.options;return i.indexOf(e)>i.indexOf(t)?1:-1})).forEach((e=>{controls.createMenuItem.call(this,{value:e,list:i,type:t,title:controls.getLabel.call(this,"quality",e),badge:n(e)})})),controls.updateSetting.call(this,t,i)},setCaptionsMenu(){if(!is.element(this.elements.settings.panels.captions))return;const e="captions",t=this.elements.settings.panels.captions.querySelector('[role="menu"]'),i=captions.getTracks.call(this),s=Boolean(i.length);if(controls.toggleMenuButton.call(this,e,s),emptyElement(t),controls.checkMenu.call(this),!s)return;const n=i.map(((e,i)=>({value:i,checked:this.captions.toggled&&this.currentTrack===i,title:captions.getLabel.call(this,e),badge:e.language&&controls.createBadge.call(this,e.language.toUpperCase()),list:t,type:"language"})));n.unshift({value:-1,checked:!this.captions.toggled,title:i18n.get("disabled",this.config),list:t,type:"language"}),n.forEach(controls.createMenuItem.bind(this)),controls.updateSetting.call(this,e,t)},setSpeedMenu(){if(!is.element(this.elements.settings.panels.speed))return;const e="speed",t=this.elements.settings.panels.speed.querySelector('[role="menu"]');this.options.speed=this.options.speed.filter((e=>e>=this.minimumSpeed&&e<=this.maximumSpeed));const i=!is.empty(this.options.speed)&&this.options.speed.length>1;controls.toggleMenuButton.call(this,e,i),emptyElement(t),controls.checkMenu.call(this),i&&(this.options.speed.forEach((i=>{controls.createMenuItem.call(this,{value:i,list:t,type:e,title:controls.getLabel.call(this,"speed",i)})})),controls.updateSetting.call(this,e,t))},checkMenu(){const{buttons:e}=this.elements.settings,t=!is.empty(e)&&Object.values(e).some((e=>!e.hidden));toggleHidden(this.elements.settings.menu,!t)},focusFirstMenuItem(e,t=!1){if(this.elements.settings.popup.hidden)return;let i=e;is.element(i)||(i=Object.values(this.elements.settings.panels).find((e=>!e.hidden)));const s=i.querySelector('[role^="menuitem"]');setFocus.call(this,s,t)},toggleMenu(e){const{popup:t}=this.elements.settings,i=this.elements.buttons.settings;if(!is.element(t)||!is.element(i))return;const{hidden:s}=t;let n=s;if(is.boolean(e))n=e;else if(is.keyboardEvent(e)&&27===e.which)n=!1;else if(is.event(e)){const s=is.function(e.composedPath)?e.composedPath()[0]:e.target,r=t.contains(s);if(r||!r&&e.target!==i&&n)return}i.setAttribute("aria-expanded",n),toggleHidden(t,!n),toggleClass(this.elements.container,this.config.classNames.menu.open,n),n&&is.keyboardEvent(e)?controls.focusFirstMenuItem.call(this,null,!0):n||s||setFocus.call(this,i,is.keyboardEvent(e))},getMenuSize(e){const t=e.cloneNode(!0);t.style.position="absolute",t.style.opacity=0,t.removeAttribute("hidden"),e.parentNode.appendChild(t);const i=t.scrollWidth,s=t.scrollHeight;return removeElement(t),{width:i,height:s}},showMenuPanel(e="",t=!1){const i=this.elements.container.querySelector(`#plyr-settings-${this.id}-${e}`);if(!is.element(i))return;const s=i.parentNode,n=Array.from(s.children).find((e=>!e.hidden));if(support.transitions&&!support.reducedMotion){s.style.width=`${n.scrollWidth}px`,s.style.height=`${n.scrollHeight}px`;const e=controls.getMenuSize.call(this,i),t=e=>{e.target===s&&["width","height"].includes(e.propertyName)&&(s.style.width="",s.style.height="",off.call(this,s,transitionEndEvent,t))};on.call(this,s,transitionEndEvent,t),s.style.width=`${e.width}px`,s.style.height=`${e.height}px`}toggleHidden(n,!0),toggleHidden(i,!1),controls.focusFirstMenuItem.call(this,i,t)},setDownloadUrl(){const e=this.elements.buttons.download;is.element(e)&&e.setAttribute("href",this.download)},create(e){const{bindMenuItemShortcuts:t,createButton:i,createProgress:s,createRange:n,createTime:r,setQualityMenu:a,setSpeedMenu:o,showMenuPanel:l}=controls;this.elements.controls=null,is.array(this.config.controls)&&this.config.controls.includes("play-large")&&this.elements.container.appendChild(i.call(this,"play-large"));const c=createElement("div",getAttributesFromSelector(this.config.selectors.controls.wrapper));this.elements.controls=c;const u={class:"plyr__controls__item"};return dedupe(is.array(this.config.controls)?this.config.controls:[]).forEach((a=>{if("restart"===a&&c.appendChild(i.call(this,"restart",u)),"rewind"===a&&c.appendChild(i.call(this,"rewind",u)),"play"===a&&c.appendChild(i.call(this,"play",u)),"fast-forward"===a&&c.appendChild(i.call(this,"fast-forward",u)),"progress"===a){const t=createElement("div",{class:`${u.class} plyr__progress__container`}),i=createElement("div",getAttributesFromSelector(this.config.selectors.progress));if(i.appendChild(n.call(this,"seek",{id:`plyr-seek-${e.id}`})),i.appendChild(s.call(this,"buffer")),this.config.tooltips.seek){const e=createElement("span",{class:this.config.classNames.tooltip},"00:00");i.appendChild(e),this.elements.display.seekTooltip=e}this.elements.progress=i,t.appendChild(this.elements.progress),c.appendChild(t)}if("current-time"===a&&c.appendChild(r.call(this,"currentTime",u)),"duration"===a&&c.appendChild(r.call(this,"duration",u)),"mute"===a||"volume"===a){let{volume:t}=this.elements;if(is.element(t)&&c.contains(t)||(t=createElement("div",extend({},u,{class:`${u.class} plyr__volume`.trim()})),this.elements.volume=t,c.appendChild(t)),"mute"===a&&t.appendChild(i.call(this,"mute")),"volume"===a&&!browser.isIos){const i={max:1,step:.05,value:this.config.volume};t.appendChild(n.call(this,"volume",extend(i,{id:`plyr-volume-${e.id}`})))}}if("captions"===a&&c.appendChild(i.call(this,"captions",u)),"settings"===a&&!is.empty(this.config.settings)){const s=createElement("div",extend({},u,{class:`${u.class} plyr__menu`.trim(),hidden:""}));s.appendChild(i.call(this,"settings",{"aria-haspopup":!0,"aria-controls":`plyr-settings-${e.id}`,"aria-expanded":!1}));const n=createElement("div",{class:"plyr__menu__container",id:`plyr-settings-${e.id}`,hidden:""}),r=createElement("div"),a=createElement("div",{id:`plyr-settings-${e.id}-home`}),o=createElement("div",{role:"menu"});a.appendChild(o),r.appendChild(a),this.elements.settings.panels.home=a,this.config.settings.forEach((i=>{const s=createElement("button",extend(getAttributesFromSelector(this.config.selectors.buttons.settings),{type:"button",class:`${this.config.classNames.control} ${this.config.classNames.control}--forward`,role:"menuitem","aria-haspopup":!0,hidden:""}));t.call(this,s,i),on.call(this,s,"click",(()=>{l.call(this,i,!1)}));const n=createElement("span",null,i18n.get(i,this.config)),a=createElement("span",{class:this.config.classNames.menu.value});a.innerHTML=e[i],n.appendChild(a),s.appendChild(n),o.appendChild(s);const c=createElement("div",{id:`plyr-settings-${e.id}-${i}`,hidden:""}),u=createElement("button",{type:"button",class:`${this.config.classNames.control} ${this.config.classNames.control}--back`});u.appendChild(createElement("span",{"aria-hidden":!0},i18n.get(i,this.config))),u.appendChild(createElement("span",{class:this.config.classNames.hidden},i18n.get("menuBack",this.config))),on.call(this,c,"keydown",(e=>{37===e.which&&(e.preventDefault(),e.stopPropagation(),l.call(this,"home",!0))}),!1),on.call(this,u,"click",(()=>{l.call(this,"home",!1)})),c.appendChild(u),c.appendChild(createElement("div",{role:"menu"})),r.appendChild(c),this.elements.settings.buttons[i]=s,this.elements.settings.panels[i]=c})),n.appendChild(r),s.appendChild(n),c.appendChild(s),this.elements.settings.popup=n,this.elements.settings.menu=s}if("pip"===a&&support.pip&&c.appendChild(i.call(this,"pip",u)),"airplay"===a&&support.airplay&&c.appendChild(i.call(this,"airplay",u)),"download"===a){const e=extend({},u,{element:"a",href:this.download,target:"_blank"});this.isHTML5&&(e.download="");const{download:t}=this.config.urls;!is.url(t)&&this.isEmbed&&extend(e,{icon:`logo-${this.provider}`,label:this.provider}),c.appendChild(i.call(this,"download",e))}"fullscreen"===a&&c.appendChild(i.call(this,"fullscreen",u))})),this.isHTML5&&a.call(this,html5.getQualityOptions.call(this)),o.call(this),c},inject(){if(this.config.loadSprite){const e=controls.getIconUrl.call(this);e.cors&&loadSprite(e.url,"sprite-plyr")}this.id=Math.floor(1e4*Math.random());let e=null;this.elements.controls=null;const t={id:this.id,seektime:this.config.seekTime,title:this.config.title};let i=!0;is.function(this.config.controls)&&(this.config.controls=this.config.controls.call(this,t)),this.config.controls||(this.config.controls=[]),is.element(this.config.controls)||is.string(this.config.controls)?e=this.config.controls:(e=controls.create.call(this,{id:this.id,seektime:this.config.seekTime,speed:this.speed,quality:this.quality,captions:captions.getLabel.call(this)}),i=!1);let s;i&&is.string(this.config.controls)&&(e=(e=>{let i=e;return Object.entries(t).forEach((([e,t])=>{i=replaceAll(i,`{${e}}`,t)})),i})(e)),is.string(this.config.selectors.controls.container)&&(s=document.querySelector(this.config.selectors.controls.container)),is.element(s)||(s=this.elements.container);if(s[is.element(e)?"insertAdjacentElement":"insertAdjacentHTML"]("afterbegin",e),is.element(this.elements.controls)||controls.findElements.call(this),!is.empty(this.elements.buttons)){const e=e=>{const t=this.config.classNames.controlPressed;Object.defineProperty(e,"pressed",{enumerable:!0,get:()=>hasClass(e,t),set(i=!1){toggleClass(e,t,i)}})};Object.values(this.elements.buttons).filter(Boolean).forEach((t=>{is.array(t)||is.nodeList(t)?Array.from(t).filter(Boolean).forEach(e):e(t)}))}if(browser.isEdge&&repaint(s),this.config.tooltips.controls){const{classNames:e,selectors:t}=this.config,i=`${t.controls.wrapper} ${t.labels} .${e.hidden}`,s=getElements.call(this,i);Array.from(s).forEach((e=>{toggleClass(e,this.config.classNames.hidden,!1),toggleClass(e,this.config.classNames.tooltip,!0)}))}}};function parseUrl(e,t=!0){let i=e;if(t){const e=document.createElement("a");e.href=i,i=e.href}try{return new URL(i)}catch(e){return null}}function buildUrlParams(e){const t=new URLSearchParams;return is.object(e)&&Object.entries(e).forEach((([e,i])=>{t.set(e,i)})),t}const captions={setup(){if(!this.supported.ui)return;if(!this.isVideo||this.isYouTube||this.isHTML5&&!support.textTracks)return void(is.array(this.config.controls)&&this.config.controls.includes("settings")&&this.config.settings.includes("captions")&&controls.setCaptionsMenu.call(this));if(is.element(this.elements.captions)||(this.elements.captions=createElement("div",getAttributesFromSelector(this.config.selectors.captions)),insertAfter(this.elements.captions,this.elements.wrapper)),browser.isIE&&window.URL){const e=this.media.querySelectorAll("track");Array.from(e).forEach((e=>{const t=e.getAttribute("src"),i=parseUrl(t);null!==i&&i.hostname!==window.location.href.hostname&&["http:","https:"].includes(i.protocol)&&fetch(t,"blob").then((t=>{e.setAttribute("src",window.URL.createObjectURL(t))})).catch((()=>{removeElement(e)}))}))}const e=dedupe((navigator.languages||[navigator.language||navigator.userLanguage||"en"]).map((e=>e.split("-")[0])));let t=(this.storage.get("language")||this.config.captions.language||"auto").toLowerCase();"auto"===t&&([t]=e);let i=this.storage.get("captions");if(is.boolean(i)||({active:i}=this.config.captions),Object.assign(this.captions,{toggled:!1,active:i,language:t,languages:e}),this.isHTML5){const e=this.config.captions.update?"addtrack removetrack":"removetrack";on.call(this,this.media.textTracks,e,captions.update.bind(this))}setTimeout(captions.update.bind(this),0)},update(){const e=captions.getTracks.call(this,!0),{active:t,language:i,meta:s,currentTrackNode:n}=this.captions,r=Boolean(e.find((e=>e.language===i)));this.isHTML5&&this.isVideo&&e.filter((e=>!s.get(e))).forEach((e=>{this.debug.log("Track added",e),s.set(e,{default:"showing"===e.mode}),"showing"===e.mode&&(e.mode="hidden"),on.call(this,e,"cuechange",(()=>captions.updateCues.call(this)))})),(r&&this.language!==i||!e.includes(n))&&(captions.setLanguage.call(this,i),captions.toggle.call(this,t&&r)),this.elements&&toggleClass(this.elements.container,this.config.classNames.captions.enabled,!is.empty(e)),is.array(this.config.controls)&&this.config.controls.includes("settings")&&this.config.settings.includes("captions")&&controls.setCaptionsMenu.call(this)},toggle(e,t=!0){if(!this.supported.ui)return;const{toggled:i}=this.captions,s=this.config.classNames.captions.active,n=is.nullOrUndefined(e)?!i:e;if(n!==i){if(t||(this.captions.active=n,this.storage.set({captions:n})),!this.language&&n&&!t){const e=captions.getTracks.call(this),t=captions.findTrack.call(this,[this.captions.language,...this.captions.languages],!0);return this.captions.language=t.language,void captions.set.call(this,e.indexOf(t))}this.elements.buttons.captions&&(this.elements.buttons.captions.pressed=n),toggleClass(this.elements.container,s,n),this.captions.toggled=n,controls.updateSetting.call(this,"captions"),triggerEvent.call(this,this.media,n?"captionsenabled":"captionsdisabled")}setTimeout((()=>{n&&this.captions.toggled&&(this.captions.currentTrackNode.mode="hidden")}))},set(e,t=!0){const i=captions.getTracks.call(this);if(-1!==e)if(is.number(e))if(e in i){if(this.captions.currentTrack!==e){this.captions.currentTrack=e;const s=i[e],{language:n}=s||{};this.captions.currentTrackNode=s,controls.updateSetting.call(this,"captions"),t||(this.captions.language=n,this.storage.set({language:n})),this.isVimeo&&this.embed.enableTextTrack(n),triggerEvent.call(this,this.media,"languagechange")}captions.toggle.call(this,!0,t),this.isHTML5&&this.isVideo&&captions.updateCues.call(this)}else this.debug.warn("Track not found",e);else this.debug.warn("Invalid caption argument",e);else captions.toggle.call(this,!1,t)},setLanguage(e,t=!0){if(!is.string(e))return void this.debug.warn("Invalid language argument",e);const i=e.toLowerCase();this.captions.language=i;const s=captions.getTracks.call(this),n=captions.findTrack.call(this,[i]);captions.set.call(this,s.indexOf(n),t)},getTracks(e=!1){return Array.from((this.media||{}).textTracks||[]).filter((t=>!this.isHTML5||e||this.captions.meta.has(t))).filter((e=>["captions","subtitles"].includes(e.kind)))},findTrack(e,t=!1){const i=captions.getTracks.call(this),s=e=>Number((this.captions.meta.get(e)||{}).default),n=Array.from(i).sort(((e,t)=>s(t)-s(e)));let r;return e.every((e=>(r=n.find((t=>t.language===e)),!r))),r||(t?n[0]:void 0)},getCurrentTrack(){return captions.getTracks.call(this)[this.currentTrack]},getLabel(e){let t=e;return!is.track(t)&&support.textTracks&&this.captions.toggled&&(t=captions.getCurrentTrack.call(this)),is.track(t)?is.empty(t.label)?is.empty(t.language)?i18n.get("enabled",this.config):e.language.toUpperCase():t.label:i18n.get("disabled",this.config)},updateCues(e){if(!this.supported.ui)return;if(!is.element(this.elements.captions))return void this.debug.warn("No captions element to render to");if(!is.nullOrUndefined(e)&&!Array.isArray(e))return void this.debug.warn("updateCues: Invalid input",e);let t=e;if(!t){const e=captions.getCurrentTrack.call(this);t=Array.from((e||{}).activeCues||[]).map((e=>e.getCueAsHTML())).map(getHTML)}const i=t.map((e=>e.trim())).join("\n");if(i!==this.elements.captions.innerHTML){emptyElement(this.elements.captions);const e=createElement("span",getAttributesFromSelector(this.config.selectors.caption));e.innerHTML=i,this.elements.captions.appendChild(e),triggerEvent.call(this,this.media,"cuechange")}}},defaults={enabled:!0,title:"",debug:!1,autoplay:!1,autopause:!0,playsinline:!0,seekTime:10,volume:1,muted:!1,duration:null,displayDuration:!0,invertTime:!0,toggleInvert:!0,ratio:null,clickToPlay:!0,hideControls:!0,resetOnEnd:!1,disableContextMenu:!0,loadSprite:!0,iconPrefix:"plyr",iconUrl:"https://cdn.plyr.io/3.6.12/plyr.svg",blankVideo:"https://cdn.plyr.io/static/blank.mp4",quality:{default:576,options:[4320,2880,2160,1440,1080,720,576,480,360,240],forced:!1,onChange:null},loop:{active:!1},speed:{selected:1,options:[.5,.75,1,1.25,1.5,1.75,2,4]},keyboard:{focused:!0,global:!1},tooltips:{controls:!1,seek:!0},captions:{active:!1,language:"auto",update:!1},fullscreen:{enabled:!0,fallback:!0,iosNative:!1},storage:{enabled:!0,key:"plyr"},controls:["play-large","play","progress","current-time","mute","volume","captions","settings","pip","airplay","fullscreen"],settings:["captions","quality","speed"],i18n:{restart:"Restart",rewind:"Rewind {seektime}s",play:"Play",pause:"Pause",fastForward:"Forward {seektime}s",seek:"Seek",seekLabel:"{currentTime} of {duration}",played:"Played",buffered:"Buffered",currentTime:"Current time",duration:"Duration",volume:"Volume",mute:"Mute",unmute:"Unmute",enableCaptions:"Enable captions",disableCaptions:"Disable captions",download:"Download",enterFullscreen:"Enter fullscreen",exitFullscreen:"Exit fullscreen",frameTitle:"Player for {title}",captions:"Captions",settings:"Settings",pip:"PIP",menuBack:"Go back to previous menu",speed:"Speed",normal:"Normal",quality:"Quality",loop:"Loop",start:"Start",end:"End",all:"All",reset:"Reset",disabled:"Disabled",enabled:"Enabled",advertisement:"Ad",qualityBadge:{2160:"4K",1440:"HD",1080:"HD",720:"HD",576:"SD",480:"SD"}},urls:{download:null,vimeo:{sdk:"https://player.vimeo.com/api/player.js",iframe:"https://player.vimeo.com/video/{0}?{1}",api:"https://vimeo.com/api/oembed.json?url={0}"},youtube:{sdk:"https://www.youtube.com/iframe_api",api:"https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}"},googleIMA:{sdk:"https://imasdk.googleapis.com/js/sdkloader/ima3.js"}},listeners:{seek:null,play:null,pause:null,restart:null,rewind:null,fastForward:null,mute:null,volume:null,captions:null,download:null,fullscreen:null,pip:null,airplay:null,speed:null,quality:null,loop:null,language:null},events:["ended","progress","stalled","playing","waiting","canplay","canplaythrough","loadstart","loadeddata","loadedmetadata","timeupdate","volumechange","play","pause","error","seeking","seeked","emptied","ratechange","cuechange","download","enterfullscreen","exitfullscreen","captionsenabled","captionsdisabled","languagechange","controlshidden","controlsshown","ready","statechange","qualitychange","adsloaded","adscontentpause","adscontentresume","adstarted","adsmidpoint","adscomplete","adsallcomplete","adsimpression","adsclick"],selectors:{editable:"input, textarea, select, [contenteditable]",container:".plyr",controls:{container:null,wrapper:".plyr__controls"},labels:"[data-plyr]",buttons:{play:'[data-plyr="play"]',pause:'[data-plyr="pause"]',restart:'[data-plyr="restart"]',rewind:'[data-plyr="rewind"]',fastForward:'[data-plyr="fast-forward"]',mute:'[data-plyr="mute"]',captions:'[data-plyr="captions"]',download:'[data-plyr="download"]',fullscreen:'[data-plyr="fullscreen"]',pip:'[data-plyr="pip"]',airplay:'[data-plyr="airplay"]',settings:'[data-plyr="settings"]',loop:'[data-plyr="loop"]'},inputs:{seek:'[data-plyr="seek"]',volume:'[data-plyr="volume"]',speed:'[data-plyr="speed"]',language:'[data-plyr="language"]',quality:'[data-plyr="quality"]'},display:{currentTime:".plyr__time--current",duration:".plyr__time--duration",buffer:".plyr__progress__buffer",loop:".plyr__progress__loop",volume:".plyr__volume--display"},progress:".plyr__progress",captions:".plyr__captions",caption:".plyr__caption"},classNames:{type:"plyr--{0}",provider:"plyr--{0}",video:"plyr__video-wrapper",embed:"plyr__video-embed",videoFixedRatio:"plyr__video-wrapper--fixed-ratio",embedContainer:"plyr__video-embed__container",poster:"plyr__poster",posterEnabled:"plyr__poster-enabled",ads:"plyr__ads",control:"plyr__control",controlPressed:"plyr__control--pressed",playing:"plyr--playing",paused:"plyr--paused",stopped:"plyr--stopped",loading:"plyr--loading",hover:"plyr--hover",tooltip:"plyr__tooltip",cues:"plyr__cues",hidden:"plyr__sr-only",hideControls:"plyr--hide-controls",isIos:"plyr--is-ios",isTouch:"plyr--is-touch",uiSupported:"plyr--full-ui",noTransition:"plyr--no-transition",display:{time:"plyr__time"},menu:{value:"plyr__menu__value",badge:"plyr__badge",open:"plyr--menu-open"},captions:{enabled:"plyr--captions-enabled",active:"plyr--captions-active"},fullscreen:{enabled:"plyr--fullscreen-enabled",fallback:"plyr--fullscreen-fallback"},pip:{supported:"plyr--pip-supported",active:"plyr--pip-active"},airplay:{supported:"plyr--airplay-supported",active:"plyr--airplay-active"},tabFocus:"plyr__tab-focus",previewThumbnails:{thumbContainer:"plyr__preview-thumb",thumbContainerShown:"plyr__preview-thumb--is-shown",imageContainer:"plyr__preview-thumb__image-container",timeContainer:"plyr__preview-thumb__time-container",scrubbingContainer:"plyr__preview-scrubbing",scrubbingContainerShown:"plyr__preview-scrubbing--is-shown"}},attributes:{embed:{provider:"data-plyr-provider",id:"data-plyr-embed-id",hash:"data-plyr-embed-hash"}},ads:{enabled:!1,publisherId:"",tagUrl:""},previewThumbnails:{enabled:!1,src:""},vimeo:{byline:!1,portrait:!1,title:!1,speed:!0,transparent:!1,customControls:!0,referrerPolicy:null,premium:!1},youtube:{rel:0,showinfo:0,iv_load_policy:3,modestbranding:1,customControls:!0,noCookie:!1}},pip={active:"picture-in-picture",inactive:"inline"},providers={html5:"html5",youtube:"youtube",vimeo:"vimeo"},types={audio:"audio",video:"video"};function getProviderByUrl(e){return/^(https?:\/\/)?(www\.)?(youtube\.com|youtube-nocookie\.com|youtu\.?be)\/.+$/.test(e)?providers.youtube:/^https?:\/\/player.vimeo.com\/video\/\d{0,9}(?=\b|\/)/.test(e)?providers.vimeo:null}const noop=()=>{};class Console{constructor(e=!1){this.enabled=window.console&&e,this.enabled&&this.log("Debugging enabled")}get log(){return this.enabled?Function.prototype.bind.call(console.log,console):noop}get warn(){return this.enabled?Function.prototype.bind.call(console.warn,console):noop}get error(){return this.enabled?Function.prototype.bind.call(console.error,console):noop}}class Fullscreen{constructor(e){_defineProperty$1(this,"onChange",(()=>{if(!this.enabled)return;const e=this.player.elements.buttons.fullscreen;is.element(e)&&(e.pressed=this.active);const t=this.target===this.player.media?this.target:this.player.elements.container;triggerEvent.call(this.player,t,this.active?"enterfullscreen":"exitfullscreen",!0)})),_defineProperty$1(this,"toggleFallback",((e=!1)=>{if(e?this.scrollPosition={x:window.scrollX||0,y:window.scrollY||0}:window.scrollTo(this.scrollPosition.x,this.scrollPosition.y),document.body.style.overflow=e?"hidden":"",toggleClass(this.target,this.player.config.classNames.fullscreen.fallback,e),browser.isIos){let t=document.head.querySelector('meta[name="viewport"]');const i="viewport-fit=cover";t||(t=document.createElement("meta"),t.setAttribute("name","viewport"));const s=is.string(t.content)&&t.content.includes(i);e?(this.cleanupViewport=!s,s||(t.content+=`,${i}`)):this.cleanupViewport&&(t.content=t.content.split(",").filter((e=>e.trim()!==i)).join(","))}this.onChange()})),_defineProperty$1(this,"trapFocus",(e=>{if(browser.isIos||!this.active||"Tab"!==e.key||9!==e.keyCode)return;const t=document.activeElement,i=getElements.call(this.player,"a[href], button:not(:disabled), input:not(:disabled), [tabindex]"),[s]=i,n=i[i.length-1];t!==n||e.shiftKey?t===s&&e.shiftKey&&(n.focus(),e.preventDefault()):(s.focus(),e.preventDefault())})),_defineProperty$1(this,"update",(()=>{if(this.enabled){let e;e=this.forceFallback?"Fallback (forced)":Fullscreen.native?"Native":"Fallback",this.player.debug.log(`${e} fullscreen enabled`)}else this.player.debug.log("Fullscreen not supported and fallback disabled");toggleClass(this.player.elements.container,this.player.config.classNames.fullscreen.enabled,this.enabled)})),_defineProperty$1(this,"enter",(()=>{this.enabled&&(browser.isIos&&this.player.config.fullscreen.iosNative?this.player.isVimeo?this.player.embed.requestFullscreen():this.target.webkitEnterFullscreen():!Fullscreen.native||this.forceFallback?this.toggleFallback(!0):this.prefix?is.empty(this.prefix)||this.target[`${this.prefix}Request${this.property}`]():this.target.requestFullscreen({navigationUI:"hide"}))})),_defineProperty$1(this,"exit",(()=>{if(this.enabled)if(browser.isIos&&this.player.config.fullscreen.iosNative)this.target.webkitExitFullscreen(),silencePromise(this.player.play());else if(!Fullscreen.native||this.forceFallback)this.toggleFallback(!1);else if(this.prefix){if(!is.empty(this.prefix)){const e="moz"===this.prefix?"Cancel":"Exit";document[`${this.prefix}${e}${this.property}`]()}}else(document.cancelFullScreen||document.exitFullscreen).call(document)})),_defineProperty$1(this,"toggle",(()=>{this.active?this.exit():this.enter()})),this.player=e,this.prefix=Fullscreen.prefix,this.property=Fullscreen.property,this.scrollPosition={x:0,y:0},this.forceFallback="force"===e.config.fullscreen.fallback,this.player.elements.fullscreen=e.config.fullscreen.container&&closest$1(this.player.elements.container,e.config.fullscreen.container),on.call(this.player,document,"ms"===this.prefix?"MSFullscreenChange":`${this.prefix}fullscreenchange`,(()=>{this.onChange()})),on.call(this.player,this.player.elements.container,"dblclick",(e=>{is.element(this.player.elements.controls)&&this.player.elements.controls.contains(e.target)||this.player.listeners.proxy(e,this.toggle,"fullscreen")})),on.call(this,this.player.elements.container,"keydown",(e=>this.trapFocus(e))),this.update()}static get native(){return!!(document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled)}get usingNative(){return Fullscreen.native&&!this.forceFallback}static get prefix(){if(is.function(document.exitFullscreen))return"";let e="";return["webkit","moz","ms"].some((t=>!(!is.function(document[`${t}ExitFullscreen`])&&!is.function(document[`${t}CancelFullScreen`]))&&(e=t,!0))),e}static get property(){return"moz"===this.prefix?"FullScreen":"Fullscreen"}get enabled(){return(Fullscreen.native||this.player.config.fullscreen.fallback)&&this.player.config.fullscreen.enabled&&this.player.supported.ui&&this.player.isVideo}get active(){if(!this.enabled)return!1;if(!Fullscreen.native||this.forceFallback)return hasClass(this.target,this.player.config.classNames.fullscreen.fallback);const e=this.prefix?this.target.getRootNode()[`${this.prefix}${this.property}Element`]:this.target.getRootNode().fullscreenElement;return e&&e.shadowRoot?e===this.target.getRootNode().host:e===this.target}get target(){return browser.isIos&&this.player.config.fullscreen.iosNative?this.player.media:this.player.elements.fullscreen||this.player.elements.container}}function loadImage(e,t=1){return new Promise(((i,s)=>{const n=new Image,r=()=>{delete n.onload,delete n.onerror,(n.naturalWidth>=t?i:s)(n)};Object.assign(n,{onload:r,onerror:r,src:e})}))}const ui={addStyleHook(){toggleClass(this.elements.container,this.config.selectors.container.replace(".",""),!0),toggleClass(this.elements.container,this.config.classNames.uiSupported,this.supported.ui)},toggleNativeControls(e=!1){e&&this.isHTML5?this.media.setAttribute("controls",""):this.media.removeAttribute("controls")},build(){if(this.listeners.media(),!this.supported.ui)return this.debug.warn(`Basic support only for ${this.provider} ${this.type}`),void ui.toggleNativeControls.call(this,!0);is.element(this.elements.controls)||(controls.inject.call(this),this.listeners.controls()),ui.toggleNativeControls.call(this),this.isHTML5&&captions.setup.call(this),this.volume=null,this.muted=null,this.loop=null,this.quality=null,this.speed=null,controls.updateVolume.call(this),controls.timeUpdate.call(this),controls.durationUpdate.call(this),ui.checkPlaying.call(this),toggleClass(this.elements.container,this.config.classNames.pip.supported,support.pip&&this.isHTML5&&this.isVideo),toggleClass(this.elements.container,this.config.classNames.airplay.supported,support.airplay&&this.isHTML5),toggleClass(this.elements.container,this.config.classNames.isIos,browser.isIos),toggleClass(this.elements.container,this.config.classNames.isTouch,this.touch),this.ready=!0,setTimeout((()=>{triggerEvent.call(this,this.media,"ready")}),0),ui.setTitle.call(this),this.poster&&ui.setPoster.call(this,this.poster,!1).catch((()=>{})),this.config.duration&&controls.durationUpdate.call(this)},setTitle(){let e=i18n.get("play",this.config);if(is.string(this.config.title)&&!is.empty(this.config.title)&&(e+=`, ${this.config.title}`),Array.from(this.elements.buttons.play||[]).forEach((t=>{t.setAttribute("aria-label",e)})),this.isEmbed){const e=getElement.call(this,"iframe");if(!is.element(e))return;const t=is.empty(this.config.title)?"video":this.config.title,i=i18n.get("frameTitle",this.config);e.setAttribute("title",i.replace("{title}",t))}},togglePoster(e){toggleClass(this.elements.container,this.config.classNames.posterEnabled,e)},setPoster(e,t=!0){return t&&this.poster?Promise.reject(new Error("Poster already set")):(this.media.setAttribute("data-poster",e),this.elements.poster.removeAttribute("hidden"),ready.call(this).then((()=>loadImage(e))).catch((t=>{throw e===this.poster&&ui.togglePoster.call(this,!1),t})).then((()=>{if(e!==this.poster)throw new Error("setPoster cancelled by later call to setPoster")})).then((()=>(Object.assign(this.elements.poster.style,{backgroundImage:`url('${e}')`,backgroundSize:""}),ui.togglePoster.call(this,!0),e))))},checkPlaying(e){toggleClass(this.elements.container,this.config.classNames.playing,this.playing),toggleClass(this.elements.container,this.config.classNames.paused,this.paused),toggleClass(this.elements.container,this.config.classNames.stopped,this.stopped),Array.from(this.elements.buttons.play||[]).forEach((e=>{Object.assign(e,{pressed:this.playing}),e.setAttribute("aria-label",i18n.get(this.playing?"pause":"play",this.config))})),is.event(e)&&"timeupdate"===e.type||ui.toggleControls.call(this)},checkLoading(e){this.loading=["stalled","waiting"].includes(e.type),clearTimeout(this.timers.loading),this.timers.loading=setTimeout((()=>{toggleClass(this.elements.container,this.config.classNames.loading,this.loading),ui.toggleControls.call(this)}),this.loading?250:0)},toggleControls(e){const{controls:t}=this.elements;if(t&&this.config.hideControls){const i=this.touch&&this.lastSeekTime+2e3>Date.now();this.toggleControls(Boolean(e||this.loading||this.paused||t.pressed||t.hover||i))}},migrateStyles(){Object.values({...this.media.style}).filter((e=>!is.empty(e)&&is.string(e)&&e.startsWith("--plyr"))).forEach((e=>{this.elements.container.style.setProperty(e,this.media.style.getPropertyValue(e)),this.media.style.removeProperty(e)})),is.empty(this.media.style)&&this.media.removeAttribute("style")}};class Listeners{constructor(e){_defineProperty$1(this,"firstTouch",(()=>{const{player:e}=this,{elements:t}=e;e.touch=!0,toggleClass(t.container,e.config.classNames.isTouch,!0)})),_defineProperty$1(this,"setTabFocus",(e=>{const{player:t}=this,{elements:i}=t;if(clearTimeout(this.focusTimer),"keydown"===e.type&&9!==e.which)return;"keydown"===e.type&&(this.lastKeyDown=e.timeStamp);const s=e.timeStamp-this.lastKeyDown<=20;("focus"!==e.type||s)&&((()=>{const e=t.config.classNames.tabFocus;toggleClass(getElements.call(t,`.${e}`),e,!1)})(),"focusout"!==e.type&&(this.focusTimer=setTimeout((()=>{const e=document.activeElement;i.container.contains(e)&&toggleClass(document.activeElement,t.config.classNames.tabFocus,!0)}),10)))})),_defineProperty$1(this,"global",((e=!0)=>{const{player:t}=this;t.config.keyboard.global&&toggleListener.call(t,window,"keydown keyup",this.handleKey,e,!1),toggleListener.call(t,document.body,"click",this.toggleMenu,e),once.call(t,document.body,"touchstart",this.firstTouch),toggleListener.call(t,document.body,"keydown focus blur focusout",this.setTabFocus,e,!1,!0)})),_defineProperty$1(this,"container",(()=>{const{player:e}=this,{config:t,elements:i,timers:s}=e;!t.keyboard.global&&t.keyboard.focused&&on.call(e,i.container,"keydown keyup",this.handleKey,!1),on.call(e,i.container,"mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen",(t=>{const{controls:n}=i;n&&"enterfullscreen"===t.type&&(n.pressed=!1,n.hover=!1);let r=0;["touchstart","touchmove","mousemove"].includes(t.type)&&(ui.toggleControls.call(e,!0),r=e.touch?3e3:2e3),clearTimeout(s.controls),s.controls=setTimeout((()=>ui.toggleControls.call(e,!1)),r)}));const n=()=>{if(!e.isVimeo||e.config.vimeo.premium)return;const t=i.wrapper,{active:s}=e.fullscreen,[n,r]=getAspectRatio.call(e),a=supportsCSS(`aspect-ratio: ${n} / ${r}`);if(!s)return void(a?(t.style.width=null,t.style.height=null):(t.style.maxWidth=null,t.style.margin=null));const[o,l]=getViewportSize(),c=o/l>n/r;a?(t.style.width=c?"auto":"100%",t.style.height=c?"100%":"auto"):(t.style.maxWidth=c?l/r*n+"px":null,t.style.margin=c?"0 auto":null)},r=()=>{clearTimeout(s.resized),s.resized=setTimeout(n,50)};on.call(e,i.container,"enterfullscreen exitfullscreen",(t=>{const{target:s}=e.fullscreen;if(s!==i.container)return;if(!e.isEmbed&&is.empty(e.config.ratio))return;n();("enterfullscreen"===t.type?on:off).call(e,window,"resize",r)}))})),_defineProperty$1(this,"media",(()=>{const{player:e}=this,{elements:t}=e;if(on.call(e,e.media,"timeupdate seeking seeked",(t=>controls.timeUpdate.call(e,t))),on.call(e,e.media,"durationchange loadeddata loadedmetadata",(t=>controls.durationUpdate.call(e,t))),on.call(e,e.media,"ended",(()=>{e.isHTML5&&e.isVideo&&e.config.resetOnEnd&&(e.restart(),e.pause())})),on.call(e,e.media,"progress playing seeking seeked",(t=>controls.updateProgress.call(e,t))),on.call(e,e.media,"volumechange",(t=>controls.updateVolume.call(e,t))),on.call(e,e.media,"playing play pause ended emptied timeupdate",(t=>ui.checkPlaying.call(e,t))),on.call(e,e.media,"waiting canplay seeked playing",(t=>ui.checkLoading.call(e,t))),e.supported.ui&&e.config.clickToPlay&&!e.isAudio){const i=getElement.call(e,`.${e.config.classNames.video}`);if(!is.element(i))return;on.call(e,t.container,"click",(s=>{([t.container,i].includes(s.target)||i.contains(s.target))&&(e.touch&&e.config.hideControls||(e.ended?(this.proxy(s,e.restart,"restart"),this.proxy(s,(()=>{silencePromise(e.play())}),"play")):this.proxy(s,(()=>{silencePromise(e.togglePlay())}),"play")))}))}e.supported.ui&&e.config.disableContextMenu&&on.call(e,t.wrapper,"contextmenu",(e=>{e.preventDefault()}),!1),on.call(e,e.media,"volumechange",(()=>{e.storage.set({volume:e.volume,muted:e.muted})})),on.call(e,e.media,"ratechange",(()=>{controls.updateSetting.call(e,"speed"),e.storage.set({speed:e.speed})})),on.call(e,e.media,"qualitychange",(t=>{controls.updateSetting.call(e,"quality",null,t.detail.quality)})),on.call(e,e.media,"ready qualitychange",(()=>{controls.setDownloadUrl.call(e)}));const i=e.config.events.concat(["keyup","keydown"]).join(" ");on.call(e,e.media,i,(i=>{let{detail:s={}}=i;"error"===i.type&&(s=e.media.error),triggerEvent.call(e,t.container,i.type,!0,s)}))})),_defineProperty$1(this,"proxy",((e,t,i)=>{const{player:s}=this,n=s.config.listeners[i];let r=!0;is.function(n)&&(r=n.call(s,e)),!1!==r&&is.function(t)&&t.call(s,e)})),_defineProperty$1(this,"bind",((e,t,i,s,n=!0)=>{const{player:r}=this,a=r.config.listeners[s],o=is.function(a);on.call(r,e,t,(e=>this.proxy(e,i,s)),n&&!o)})),_defineProperty$1(this,"controls",(()=>{const{player:e}=this,{elements:t}=e,i=browser.isIE?"change":"input";if(t.buttons.play&&Array.from(t.buttons.play).forEach((t=>{this.bind(t,"click",(()=>{silencePromise(e.togglePlay())}),"play")})),this.bind(t.buttons.restart,"click",e.restart,"restart"),this.bind(t.buttons.rewind,"click",(()=>{e.lastSeekTime=Date.now(),e.rewind()}),"rewind"),this.bind(t.buttons.fastForward,"click",(()=>{e.lastSeekTime=Date.now(),e.forward()}),"fastForward"),this.bind(t.buttons.mute,"click",(()=>{e.muted=!e.muted}),"mute"),this.bind(t.buttons.captions,"click",(()=>e.toggleCaptions())),this.bind(t.buttons.download,"click",(()=>{triggerEvent.call(e,e.media,"download")}),"download"),this.bind(t.buttons.fullscreen,"click",(()=>{e.fullscreen.toggle()}),"fullscreen"),this.bind(t.buttons.pip,"click",(()=>{e.pip="toggle"}),"pip"),this.bind(t.buttons.airplay,"click",e.airplay,"airplay"),this.bind(t.buttons.settings,"click",(t=>{t.stopPropagation(),t.preventDefault(),controls.toggleMenu.call(e,t)}),null,!1),this.bind(t.buttons.settings,"keyup",(t=>{const i=t.which;[13,32].includes(i)&&(13!==i?(t.preventDefault(),t.stopPropagation(),controls.toggleMenu.call(e,t)):controls.focusFirstMenuItem.call(e,null,!0))}),null,!1),this.bind(t.settings.menu,"keydown",(t=>{27===t.which&&controls.toggleMenu.call(e,t)})),this.bind(t.inputs.seek,"mousedown mousemove",(e=>{const i=t.progress.getBoundingClientRect(),s=100/i.width*(e.pageX-i.left);e.currentTarget.setAttribute("seek-value",s)})),this.bind(t.inputs.seek,"mousedown mouseup keydown keyup touchstart touchend",(t=>{const i=t.currentTarget,s=t.keyCode?t.keyCode:t.which,n="play-on-seeked";if(is.keyboardEvent(t)&&39!==s&&37!==s)return;e.lastSeekTime=Date.now();const r=i.hasAttribute(n),a=["mouseup","touchend","keyup"].includes(t.type);r&&a?(i.removeAttribute(n),silencePromise(e.play())):!a&&e.playing&&(i.setAttribute(n,""),e.pause())})),browser.isIos){const t=getElements.call(e,'input[type="range"]');Array.from(t).forEach((e=>this.bind(e,i,(e=>repaint(e.target)))))}this.bind(t.inputs.seek,i,(t=>{const i=t.currentTarget;let s=i.getAttribute("seek-value");is.empty(s)&&(s=i.value),i.removeAttribute("seek-value"),e.currentTime=s/i.max*e.duration}),"seek"),this.bind(t.progress,"mouseenter mouseleave mousemove",(t=>controls.updateSeekTooltip.call(e,t))),this.bind(t.progress,"mousemove touchmove",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.startMove(t)})),this.bind(t.progress,"mouseleave touchend click",(()=>{const{previewThumbnails:t}=e;t&&t.loaded&&t.endMove(!1,!0)})),this.bind(t.progress,"mousedown touchstart",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.startScrubbing(t)})),this.bind(t.progress,"mouseup touchend",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.endScrubbing(t)})),browser.isWebkit&&Array.from(getElements.call(e,'input[type="range"]')).forEach((t=>{this.bind(t,"input",(t=>controls.updateRangeFill.call(e,t.target)))})),e.config.toggleInvert&&!is.element(t.display.duration)&&this.bind(t.display.currentTime,"click",(()=>{0!==e.currentTime&&(e.config.invertTime=!e.config.invertTime,controls.timeUpdate.call(e))})),this.bind(t.inputs.volume,i,(t=>{e.volume=t.target.value}),"volume"),this.bind(t.controls,"mouseenter mouseleave",(i=>{t.controls.hover=!e.touch&&"mouseenter"===i.type})),t.fullscreen&&Array.from(t.fullscreen.children).filter((e=>!e.contains(t.container))).forEach((i=>{this.bind(i,"mouseenter mouseleave",(i=>{t.controls&&(t.controls.hover=!e.touch&&"mouseenter"===i.type)}))})),this.bind(t.controls,"mousedown mouseup touchstart touchend touchcancel",(e=>{t.controls.pressed=["mousedown","touchstart"].includes(e.type)})),this.bind(t.controls,"focusin",(()=>{const{config:i,timers:s}=e;toggleClass(t.controls,i.classNames.noTransition,!0),ui.toggleControls.call(e,!0),setTimeout((()=>{toggleClass(t.controls,i.classNames.noTransition,!1)}),0);const n=this.touch?3e3:4e3;clearTimeout(s.controls),s.controls=setTimeout((()=>ui.toggleControls.call(e,!1)),n)})),this.bind(t.inputs.volume,"wheel",(t=>{const i=t.webkitDirectionInvertedFromDevice,[s,n]=[t.deltaX,-t.deltaY].map((e=>i?-e:e)),r=Math.sign(Math.abs(s)>Math.abs(n)?s:n);e.increaseVolume(r/50);const{volume:a}=e.media;(1===r&&a<1||-1===r&&a>0)&&t.preventDefault()}),"volume",!1)})),this.player=e,this.lastKey=null,this.focusTimer=null,this.lastKeyDown=null,this.handleKey=this.handleKey.bind(this),this.toggleMenu=this.toggleMenu.bind(this),this.setTabFocus=this.setTabFocus.bind(this),this.firstTouch=this.firstTouch.bind(this)}handleKey(e){const{player:t}=this,{elements:i}=t,s=e.keyCode?e.keyCode:e.which,n="keydown"===e.type,r=n&&s===this.lastKey;if(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;if(!is.number(s))return;if(n){const n=document.activeElement;if(is.element(n)){const{editable:s}=t.config.selectors,{seek:r}=i.inputs;if(n!==r&&matches(n,s))return;if(32===e.which&&matches(n,'button, [role^="menuitem"]'))return}switch([32,37,38,39,40,48,49,50,51,52,53,54,56,57,67,70,73,75,76,77,79].includes(s)&&(e.preventDefault(),e.stopPropagation()),s){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:r||(t.currentTime=t.duration/10*(s-48));break;case 32:case 75:r||silencePromise(t.togglePlay());break;case 38:t.increaseVolume(.1);break;case 40:t.decreaseVolume(.1);break;case 77:r||(t.muted=!t.muted);break;case 39:t.forward();break;case 37:t.rewind();break;case 70:t.fullscreen.toggle();break;case 67:r||t.toggleCaptions();break;case 76:t.loop=!t.loop}27===s&&!t.fullscreen.usingNative&&t.fullscreen.active&&t.fullscreen.toggle(),this.lastKey=s}else this.lastKey=null}toggleMenu(e){controls.toggleMenu.call(this.player,e)}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}var loadjs_umd=createCommonjsModule((function(e,t){e.exports=function(){var e=function(){},t={},i={},s={};function n(e,t){e=e.push?e:[e];var n,r,a,o=[],l=e.length,c=l;for(n=function(e,i){i.length&&o.push(e),--c||t(o)};l--;)r=e[l],(a=i[r])?n(r,a):(s[r]=s[r]||[]).push(n)}function r(e,t){if(e){var n=s[e];if(i[e]=t,n)for(;n.length;)n[0](e,t),n.splice(0,1)}}function a(t,i){t.call&&(t={success:t}),i.length?(t.error||e)(i):(t.success||e)(t)}function o(t,i,s,n){var r,a,l=document,c=s.async,u=(s.numRetries||0)+1,d=s.before||e,h=t.replace(/[\?|#].*$/,""),m=t.replace(/^(css|img)!/,"");n=n||0,/(^css!|\.css$)/.test(h)?((a=l.createElement("link")).rel="stylesheet",a.href=m,(r="hideFocus"in a)&&a.relList&&(r=0,a.rel="preload",a.as="style")):/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(h)?(a=l.createElement("img")).src=m:((a=l.createElement("script")).src=t,a.async=void 0===c||c),a.onload=a.onerror=a.onbeforeload=function(e){var l=e.type[0];if(r)try{a.sheet.cssText.length||(l="e")}catch(e){18!=e.code&&(l="e")}if("e"==l){if((n+=1)<u)return o(t,i,s,n)}else if("preload"==a.rel&&"style"==a.as)return a.rel="stylesheet";i(t,l,e.defaultPrevented)},!1!==d(t,a)&&l.head.appendChild(a)}function l(e,t,i){var s,n,r=(e=e.push?e:[e]).length,a=r,l=[];for(s=function(e,i,s){if("e"==i&&l.push(e),"b"==i){if(!s)return;l.push(e)}--r||t(l)},n=0;n<a;n++)o(e[n],s,i)}function c(e,i,s){var n,o;if(i&&i.trim&&(n=i),o=(n?s:i)||{},n){if(n in t)throw"LoadJS";t[n]=!0}function c(t,i){l(e,(function(e){a(o,e),t&&a({success:t,error:i},e),r(n,e)}),o)}if(o.returnPromise)return new Promise(c);c()}return c.ready=function(e,t){return n(e,(function(e){a(t,e)})),c},c.done=function(e){r(e,[])},c.reset=function(){t={},i={},s={}},c.isDefined=function(e){return e in t},c}()}));function loadScript(e){return new Promise(((t,i)=>{loadjs_umd(e,{success:t,error:i})}))}function parseId$1(e){if(is.empty(e))return null;if(is.number(Number(e)))return e;return e.match(/^.*(vimeo.com\/|video\/)(\d+).*/)?RegExp.$2:e}function parseHash(e){const t=e.match(/^.*(?:vimeo.com\/|video\/)(?:\d+)(?:\?.*&*h=|\/)+(?<hash>[\d,a-f]+)/);return t?t.groups.hash:null}function assurePlaybackState$1(e){e&&!this.embed.hasPlayed&&(this.embed.hasPlayed=!0),this.media.paused===e&&(this.media.paused=!e,triggerEvent.call(this,this.media,e?"play":"pause"))}const vimeo={setup(){const e=this;toggleClass(e.elements.wrapper,e.config.classNames.embed,!0),e.options.speed=e.config.speed.options,setAspectRatio.call(e),is.object(window.Vimeo)?vimeo.ready.call(e):loadScript(e.config.urls.vimeo.sdk).then((()=>{vimeo.ready.call(e)})).catch((t=>{e.debug.warn("Vimeo SDK (player.js) failed to load",t)}))},ready(){const e=this,t=e.config.vimeo,{premium:i,referrerPolicy:s,...n}=t;let r=e.media.getAttribute("src"),a="";is.empty(r)?(r=e.media.getAttribute(e.config.attributes.embed.id),a=e.media.getAttribute(e.config.attributes.embed.hash)):a=parseHash(r);const o=a?{h:a}:{};i&&Object.assign(n,{controls:!1,sidedock:!1});const l=buildUrlParams({loop:e.config.loop.active,autoplay:e.autoplay,muted:e.muted,gesture:"media",playsinline:!this.config.fullscreen.iosNative,...o,...n}),c=parseId$1(r),u=createElement("iframe"),d=format(e.config.urls.vimeo.iframe,c,l);if(u.setAttribute("src",d),u.setAttribute("allowfullscreen",""),u.setAttribute("allow",["autoplay","fullscreen","picture-in-picture","encrypted-media","accelerometer","gyroscope"].join("; ")),is.empty(s)||u.setAttribute("referrerPolicy",s),i||!t.customControls)u.setAttribute("data-poster",e.poster),e.media=replaceElement(u,e.media);else{const t=createElement("div",{class:e.config.classNames.embedContainer,"data-poster":e.poster});t.appendChild(u),e.media=replaceElement(t,e.media)}t.customControls||fetch(format(e.config.urls.vimeo.api,d)).then((t=>{!is.empty(t)&&t.thumbnail_url&&ui.setPoster.call(e,t.thumbnail_url).catch((()=>{}))})),e.embed=new window.Vimeo.Player(u,{autopause:e.config.autopause,muted:e.muted}),e.media.paused=!0,e.media.currentTime=0,e.supported.ui&&e.embed.disableTextTrack(),e.media.play=()=>(assurePlaybackState$1.call(e,!0),e.embed.play()),e.media.pause=()=>(assurePlaybackState$1.call(e,!1),e.embed.pause()),e.media.stop=()=>{e.pause(),e.currentTime=0};let{currentTime:h}=e.media;Object.defineProperty(e.media,"currentTime",{get:()=>h,set(t){const{embed:i,media:s,paused:n,volume:r}=e,a=n&&!i.hasPlayed;s.seeking=!0,triggerEvent.call(e,s,"seeking"),Promise.resolve(a&&i.setVolume(0)).then((()=>i.setCurrentTime(t))).then((()=>a&&i.pause())).then((()=>a&&i.setVolume(r))).catch((()=>{}))}});let m=e.config.speed.selected;Object.defineProperty(e.media,"playbackRate",{get:()=>m,set(t){e.embed.setPlaybackRate(t).then((()=>{m=t,triggerEvent.call(e,e.media,"ratechange")})).catch((()=>{e.options.speed=[1]}))}});let{volume:p}=e.config;Object.defineProperty(e.media,"volume",{get:()=>p,set(t){e.embed.setVolume(t).then((()=>{p=t,triggerEvent.call(e,e.media,"volumechange")}))}});let{muted:g}=e.config;Object.defineProperty(e.media,"muted",{get:()=>g,set(t){const i=!!is.boolean(t)&&t;e.embed.setVolume(i?0:e.config.volume).then((()=>{g=i,triggerEvent.call(e,e.media,"volumechange")}))}});let f,{loop:y}=e.config;Object.defineProperty(e.media,"loop",{get:()=>y,set(t){const i=is.boolean(t)?t:e.config.loop.active;e.embed.setLoop(i).then((()=>{y=i}))}}),e.embed.getVideoUrl().then((t=>{f=t,controls.setDownloadUrl.call(e)})).catch((e=>{this.debug.warn(e)})),Object.defineProperty(e.media,"currentSrc",{get:()=>f}),Object.defineProperty(e.media,"ended",{get:()=>e.currentTime===e.duration}),Promise.all([e.embed.getVideoWidth(),e.embed.getVideoHeight()]).then((t=>{const[i,s]=t;e.embed.ratio=roundAspectRatio(i,s),setAspectRatio.call(this)})),e.embed.setAutopause(e.config.autopause).then((t=>{e.config.autopause=t})),e.embed.getVideoTitle().then((t=>{e.config.title=t,ui.setTitle.call(this)})),e.embed.getCurrentTime().then((t=>{h=t,triggerEvent.call(e,e.media,"timeupdate")})),e.embed.getDuration().then((t=>{e.media.duration=t,triggerEvent.call(e,e.media,"durationchange")})),e.embed.getTextTracks().then((t=>{e.media.textTracks=t,captions.setup.call(e)})),e.embed.on("cuechange",(({cues:t=[]})=>{const i=t.map((e=>stripHTML(e.text)));captions.updateCues.call(e,i)})),e.embed.on("loaded",(()=>{if(e.embed.getPaused().then((t=>{assurePlaybackState$1.call(e,!t),t||triggerEvent.call(e,e.media,"playing")})),is.element(e.embed.element)&&e.supported.ui){e.embed.element.setAttribute("tabindex",-1)}})),e.embed.on("bufferstart",(()=>{triggerEvent.call(e,e.media,"waiting")})),e.embed.on("bufferend",(()=>{triggerEvent.call(e,e.media,"playing")})),e.embed.on("play",(()=>{assurePlaybackState$1.call(e,!0),triggerEvent.call(e,e.media,"playing")})),e.embed.on("pause",(()=>{assurePlaybackState$1.call(e,!1)})),e.embed.on("timeupdate",(t=>{e.media.seeking=!1,h=t.seconds,triggerEvent.call(e,e.media,"timeupdate")})),e.embed.on("progress",(t=>{e.media.buffered=t.percent,triggerEvent.call(e,e.media,"progress"),1===parseInt(t.percent,10)&&triggerEvent.call(e,e.media,"canplaythrough"),e.embed.getDuration().then((t=>{t!==e.media.duration&&(e.media.duration=t,triggerEvent.call(e,e.media,"durationchange"))}))})),e.embed.on("seeked",(()=>{e.media.seeking=!1,triggerEvent.call(e,e.media,"seeked")})),e.embed.on("ended",(()=>{e.media.paused=!0,triggerEvent.call(e,e.media,"ended")})),e.embed.on("error",(t=>{e.media.error=t,triggerEvent.call(e,e.media,"error")})),t.customControls&&setTimeout((()=>ui.build.call(e)),0)}};function parseId(e){if(is.empty(e))return null;return e.match(/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/)?RegExp.$2:e}function assurePlaybackState(e){e&&!this.embed.hasPlayed&&(this.embed.hasPlayed=!0),this.media.paused===e&&(this.media.paused=!e,triggerEvent.call(this,this.media,e?"play":"pause"))}function getHost(e){return e.noCookie?"https://www.youtube-nocookie.com":"http:"===window.location.protocol?"http://www.youtube.com":void 0}const youtube={setup(){if(toggleClass(this.elements.wrapper,this.config.classNames.embed,!0),is.object(window.YT)&&is.function(window.YT.Player))youtube.ready.call(this);else{const e=window.onYouTubeIframeAPIReady;window.onYouTubeIframeAPIReady=()=>{is.function(e)&&e(),youtube.ready.call(this)},loadScript(this.config.urls.youtube.sdk).catch((e=>{this.debug.warn("YouTube API failed to load",e)}))}},getTitle(e){fetch(format(this.config.urls.youtube.api,e)).then((e=>{if(is.object(e)){const{title:t,height:i,width:s}=e;this.config.title=t,ui.setTitle.call(this),this.embed.ratio=roundAspectRatio(s,i)}setAspectRatio.call(this)})).catch((()=>{setAspectRatio.call(this)}))},ready(){const e=this,t=e.config.youtube,i=e.media&&e.media.getAttribute("id");if(!is.empty(i)&&i.startsWith("youtube-"))return;let s=e.media.getAttribute("src");is.empty(s)&&(s=e.media.getAttribute(this.config.attributes.embed.id));const n=parseId(s),r=createElement("div",{id:generateId(e.provider),"data-poster":t.customControls?e.poster:void 0});if(e.media=replaceElement(r,e.media),t.customControls){const t=e=>`https://i.ytimg.com/vi/${n}/${e}default.jpg`;loadImage(t("maxres"),121).catch((()=>loadImage(t("sd"),121))).catch((()=>loadImage(t("hq")))).then((t=>ui.setPoster.call(e,t.src))).then((t=>{t.includes("maxres")||(e.elements.poster.style.backgroundSize="cover")})).catch((()=>{}))}e.embed=new window.YT.Player(e.media,{videoId:n,host:getHost(t),playerVars:extend({},{autoplay:e.config.autoplay?1:0,hl:e.config.hl,controls:e.supported.ui&&t.customControls?0:1,disablekb:1,playsinline:e.config.fullscreen.iosNative?0:1,cc_load_policy:e.captions.active?1:0,cc_lang_pref:e.config.captions.language,widget_referrer:window?window.location.href:null},t),events:{onError(t){if(!e.media.error){const i=t.data,s={2:"The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.",5:"The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.",100:"The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.",101:"The owner of the requested video does not allow it to be played in embedded players.",150:"The owner of the requested video does not allow it to be played in embedded players."}[i]||"An unknown error occured";e.media.error={code:i,message:s},triggerEvent.call(e,e.media,"error")}},onPlaybackRateChange(t){const i=t.target;e.media.playbackRate=i.getPlaybackRate(),triggerEvent.call(e,e.media,"ratechange")},onReady(i){if(is.function(e.media.play))return;const s=i.target;youtube.getTitle.call(e,n),e.media.play=()=>{assurePlaybackState.call(e,!0),s.playVideo()},e.media.pause=()=>{assurePlaybackState.call(e,!1),s.pauseVideo()},e.media.stop=()=>{s.stopVideo()},e.media.duration=s.getDuration(),e.media.paused=!0,e.media.currentTime=0,Object.defineProperty(e.media,"currentTime",{get:()=>Number(s.getCurrentTime()),set(t){e.paused&&!e.embed.hasPlayed&&e.embed.mute(),e.media.seeking=!0,triggerEvent.call(e,e.media,"seeking"),s.seekTo(t)}}),Object.defineProperty(e.media,"playbackRate",{get:()=>s.getPlaybackRate(),set(e){s.setPlaybackRate(e)}});let{volume:r}=e.config;Object.defineProperty(e.media,"volume",{get:()=>r,set(t){r=t,s.setVolume(100*r),triggerEvent.call(e,e.media,"volumechange")}});let{muted:a}=e.config;Object.defineProperty(e.media,"muted",{get:()=>a,set(t){const i=is.boolean(t)?t:a;a=i,s[i?"mute":"unMute"](),s.setVolume(100*r),triggerEvent.call(e,e.media,"volumechange")}}),Object.defineProperty(e.media,"currentSrc",{get:()=>s.getVideoUrl()}),Object.defineProperty(e.media,"ended",{get:()=>e.currentTime===e.duration});const o=s.getAvailablePlaybackRates();e.options.speed=o.filter((t=>e.config.speed.options.includes(t))),e.supported.ui&&t.customControls&&e.media.setAttribute("tabindex",-1),triggerEvent.call(e,e.media,"timeupdate"),triggerEvent.call(e,e.media,"durationchange"),clearInterval(e.timers.buffering),e.timers.buffering=setInterval((()=>{e.media.buffered=s.getVideoLoadedFraction(),(null===e.media.lastBuffered||e.media.lastBuffered<e.media.buffered)&&triggerEvent.call(e,e.media,"progress"),e.media.lastBuffered=e.media.buffered,1===e.media.buffered&&(clearInterval(e.timers.buffering),triggerEvent.call(e,e.media,"canplaythrough"))}),200),t.customControls&&setTimeout((()=>ui.build.call(e)),50)},onStateChange(i){const s=i.target;clearInterval(e.timers.playing);switch(e.media.seeking&&[1,2].includes(i.data)&&(e.media.seeking=!1,triggerEvent.call(e,e.media,"seeked")),i.data){case-1:triggerEvent.call(e,e.media,"timeupdate"),e.media.buffered=s.getVideoLoadedFraction(),triggerEvent.call(e,e.media,"progress");break;case 0:assurePlaybackState.call(e,!1),e.media.loop?(s.stopVideo(),s.playVideo()):triggerEvent.call(e,e.media,"ended");break;case 1:t.customControls&&!e.config.autoplay&&e.media.paused&&!e.embed.hasPlayed?e.media.pause():(assurePlaybackState.call(e,!0),triggerEvent.call(e,e.media,"playing"),e.timers.playing=setInterval((()=>{triggerEvent.call(e,e.media,"timeupdate")}),50),e.media.duration!==s.getDuration()&&(e.media.duration=s.getDuration(),triggerEvent.call(e,e.media,"durationchange")));break;case 2:e.muted||e.embed.unMute(),assurePlaybackState.call(e,!1);break;case 3:triggerEvent.call(e,e.media,"waiting")}triggerEvent.call(e,e.elements.container,"statechange",!1,{code:i.data})}}})}},media={setup(){this.media?(toggleClass(this.elements.container,this.config.classNames.type.replace("{0}",this.type),!0),toggleClass(this.elements.container,this.config.classNames.provider.replace("{0}",this.provider),!0),this.isEmbed&&toggleClass(this.elements.container,this.config.classNames.type.replace("{0}","video"),!0),this.isVideo&&(this.elements.wrapper=createElement("div",{class:this.config.classNames.video}),wrap(this.media,this.elements.wrapper),this.elements.poster=createElement("div",{class:this.config.classNames.poster}),this.elements.wrapper.appendChild(this.elements.poster)),this.isHTML5?html5.setup.call(this):this.isYouTube?youtube.setup.call(this):this.isVimeo&&vimeo.setup.call(this)):this.debug.warn("No media element found!")}},destroy=e=>{e.manager&&e.manager.destroy(),e.elements.displayContainer&&e.elements.displayContainer.destroy(),e.elements.container.remove()};class Ads{constructor(e){_defineProperty$1(this,"load",(()=>{this.enabled&&(is.object(window.google)&&is.object(window.google.ima)?this.ready():loadScript(this.player.config.urls.googleIMA.sdk).then((()=>{this.ready()})).catch((()=>{this.trigger("error",new Error("Google IMA SDK failed to load"))})))})),_defineProperty$1(this,"ready",(()=>{var e;this.enabled||((e=this).manager&&e.manager.destroy(),e.elements.displayContainer&&e.elements.displayContainer.destroy(),e.elements.container.remove()),this.startSafetyTimer(12e3,"ready()"),this.managerPromise.then((()=>{this.clearSafetyTimer("onAdsManagerLoaded()")})),this.listeners(),this.setupIMA()})),_defineProperty$1(this,"setupIMA",(()=>{this.elements.container=createElement("div",{class:this.player.config.classNames.ads}),this.player.elements.container.appendChild(this.elements.container),google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED),google.ima.settings.setLocale(this.player.config.ads.language),google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline),this.elements.displayContainer=new google.ima.AdDisplayContainer(this.elements.container,this.player.media),this.loader=new google.ima.AdsLoader(this.elements.displayContainer),this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,(e=>this.onAdsManagerLoaded(e)),!1),this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,(e=>this.onAdError(e)),!1),this.requestAds()})),_defineProperty$1(this,"requestAds",(()=>{const{container:e}=this.player.elements;try{const t=new google.ima.AdsRequest;t.adTagUrl=this.tagUrl,t.linearAdSlotWidth=e.offsetWidth,t.linearAdSlotHeight=e.offsetHeight,t.nonLinearAdSlotWidth=e.offsetWidth,t.nonLinearAdSlotHeight=e.offsetHeight,t.forceNonLinearFullSlot=!1,t.setAdWillPlayMuted(!this.player.muted),this.loader.requestAds(t)}catch(e){this.onAdError(e)}})),_defineProperty$1(this,"pollCountdown",((e=!1)=>{if(!e)return clearInterval(this.countdownTimer),void this.elements.container.removeAttribute("data-badge-text");this.countdownTimer=setInterval((()=>{const e=formatTime(Math.max(this.manager.getRemainingTime(),0)),t=`${i18n.get("advertisement",this.player.config)} - ${e}`;this.elements.container.setAttribute("data-badge-text",t)}),100)})),_defineProperty$1(this,"onAdsManagerLoaded",(e=>{if(!this.enabled)return;const t=new google.ima.AdsRenderingSettings;t.restoreCustomPlaybackStateOnAdBreakComplete=!0,t.enablePreloading=!0,this.manager=e.getAdsManager(this.player,t),this.cuePoints=this.manager.getCuePoints(),this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,(e=>this.onAdError(e))),Object.keys(google.ima.AdEvent.Type).forEach((e=>{this.manager.addEventListener(google.ima.AdEvent.Type[e],(e=>this.onAdEvent(e)))})),this.trigger("loaded")})),_defineProperty$1(this,"addCuePoints",(()=>{is.empty(this.cuePoints)||this.cuePoints.forEach((e=>{if(0!==e&&-1!==e&&e<this.player.duration){const t=this.player.elements.progress;if(is.element(t)){const i=100/this.player.duration*e,s=createElement("span",{class:this.player.config.classNames.cues});s.style.left=`${i.toString()}%`,t.appendChild(s)}}}))})),_defineProperty$1(this,"onAdEvent",(e=>{const{container:t}=this.player.elements,i=e.getAd(),s=e.getAdData();switch((e=>{triggerEvent.call(this.player,this.player.media,`ads${e.replace(/_/g,"").toLowerCase()}`)})(e.type),e.type){case google.ima.AdEvent.Type.LOADED:this.trigger("loaded"),this.pollCountdown(!0),i.isLinear()||(i.width=t.offsetWidth,i.height=t.offsetHeight);break;case google.ima.AdEvent.Type.STARTED:this.manager.setVolume(this.player.volume);break;case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:this.player.ended?this.loadAds():this.loader.contentComplete();break;case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:this.pauseContent();break;case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:this.pollCountdown(),this.resumeContent();break;case google.ima.AdEvent.Type.LOG:s.adError&&this.player.debug.warn(`Non-fatal ad error: ${s.adError.getMessage()}`)}})),_defineProperty$1(this,"onAdError",(e=>{this.cancel(),this.player.debug.warn("Ads error",e)})),_defineProperty$1(this,"listeners",(()=>{const{container:e}=this.player.elements;let t;this.player.on("canplay",(()=>{this.addCuePoints()})),this.player.on("ended",(()=>{this.loader.contentComplete()})),this.player.on("timeupdate",(()=>{t=this.player.currentTime})),this.player.on("seeked",(()=>{const e=this.player.currentTime;is.empty(this.cuePoints)||this.cuePoints.forEach(((i,s)=>{t<i&&i<e&&(this.manager.discardAdBreak(),this.cuePoints.splice(s,1))}))})),window.addEventListener("resize",(()=>{this.manager&&this.manager.resize(e.offsetWidth,e.offsetHeight,google.ima.ViewMode.NORMAL)}))})),_defineProperty$1(this,"play",(()=>{const{container:e}=this.player.elements;this.managerPromise||this.resumeContent(),this.managerPromise.then((()=>{this.manager.setVolume(this.player.volume),this.elements.displayContainer.initialize();try{this.initialized||(this.manager.init(e.offsetWidth,e.offsetHeight,google.ima.ViewMode.NORMAL),this.manager.start()),this.initialized=!0}catch(e){this.onAdError(e)}})).catch((()=>{}))})),_defineProperty$1(this,"resumeContent",(()=>{this.elements.container.style.zIndex="",this.playing=!1,silencePromise(this.player.media.play())})),_defineProperty$1(this,"pauseContent",(()=>{this.elements.container.style.zIndex=3,this.playing=!0,this.player.media.pause()})),_defineProperty$1(this,"cancel",(()=>{this.initialized&&this.resumeContent(),this.trigger("error"),this.loadAds()})),_defineProperty$1(this,"loadAds",(()=>{this.managerPromise.then((()=>{this.manager&&this.manager.destroy(),this.managerPromise=new Promise((e=>{this.on("loaded",e),this.player.debug.log(this.manager)})),this.initialized=!1,this.requestAds()})).catch((()=>{}))})),_defineProperty$1(this,"trigger",((e,...t)=>{const i=this.events[e];is.array(i)&&i.forEach((e=>{is.function(e)&&e.apply(this,t)}))})),_defineProperty$1(this,"on",((e,t)=>(is.array(this.events[e])||(this.events[e]=[]),this.events[e].push(t),this))),_defineProperty$1(this,"startSafetyTimer",((e,t)=>{this.player.debug.log(`Safety timer invoked from: ${t}`),this.safetyTimer=setTimeout((()=>{this.cancel(),this.clearSafetyTimer("startSafetyTimer()")}),e)})),_defineProperty$1(this,"clearSafetyTimer",(e=>{is.nullOrUndefined(this.safetyTimer)||(this.player.debug.log(`Safety timer cleared from: ${e}`),clearTimeout(this.safetyTimer),this.safetyTimer=null)})),this.player=e,this.config=e.config.ads,this.playing=!1,this.initialized=!1,this.elements={container:null,displayContainer:null},this.manager=null,this.loader=null,this.cuePoints=null,this.events={},this.safetyTimer=null,this.countdownTimer=null,this.managerPromise=new Promise(((e,t)=>{this.on("loaded",e),this.on("error",t)})),this.load()}get enabled(){const{config:e}=this;return this.player.isHTML5&&this.player.isVideo&&e.enabled&&(!is.empty(e.publisherId)||is.url(e.tagUrl))}get tagUrl(){const{config:e}=this;if(is.url(e.tagUrl))return e.tagUrl;return`https://go.aniview.com/api/adserver6/vast/?${buildUrlParams({AV_PUBLISHERID:"58c25bb0073ef448b1087ad6",AV_CHANNELID:"5a0458dc28a06145e4519d21",AV_URL:window.location.hostname,cb:Date.now(),AV_WIDTH:640,AV_HEIGHT:480,AV_CDIM2:e.publisherId})}`}}const parseVtt=e=>{const t=[];return e.split(/\r\n\r\n|\n\n|\r\r/).forEach((e=>{const i={};e.split(/\r\n|\n|\r/).forEach((e=>{if(is.number(i.startTime)){if(!is.empty(e.trim())&&is.empty(i.text)){const t=e.trim().split("#xywh=");[i.text]=t,t[1]&&([i.x,i.y,i.w,i.h]=t[1].split(","))}}else{const t=e.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})/);t&&(i.startTime=60*Number(t[1]||0)*60+60*Number(t[2])+Number(t[3])+Number(`0.${t[4]}`),i.endTime=60*Number(t[6]||0)*60+60*Number(t[7])+Number(t[8])+Number(`0.${t[9]}`))}})),i.text&&t.push(i)})),t},fitRatio=(e,t)=>{const i={};return e>t.width/t.height?(i.width=t.width,i.height=1/e*t.width):(i.height=t.height,i.width=e*t.height),i};class PreviewThumbnails{constructor(e){_defineProperty$1(this,"load",(()=>{this.player.elements.display.seekTooltip&&(this.player.elements.display.seekTooltip.hidden=this.enabled),this.enabled&&this.getThumbnails().then((()=>{this.enabled&&(this.render(),this.determineContainerAutoSizing(),this.loaded=!0)}))})),_defineProperty$1(this,"getThumbnails",(()=>new Promise((e=>{const{src:t}=this.player.config.previewThumbnails;if(is.empty(t))throw new Error("Missing previewThumbnails.src config attribute");const i=()=>{this.thumbnails.sort(((e,t)=>e.height-t.height)),this.player.debug.log("Preview thumbnails",this.thumbnails),e()};if(is.function(t))t((e=>{this.thumbnails=e,i()}));else{const e=(is.string(t)?[t]:t).map((e=>this.getThumbnail(e)));Promise.all(e).then(i)}})))),_defineProperty$1(this,"getThumbnail",(e=>new Promise((t=>{fetch(e).then((i=>{const s={frames:parseVtt(i),height:null,urlPrefix:""};s.frames[0].text.startsWith("/")||s.frames[0].text.startsWith("http://")||s.frames[0].text.startsWith("https://")||(s.urlPrefix=e.substring(0,e.lastIndexOf("/")+1));const n=new Image;n.onload=()=>{s.height=n.naturalHeight,s.width=n.naturalWidth,this.thumbnails.push(s),t()},n.src=s.urlPrefix+s.frames[0].text}))})))),_defineProperty$1(this,"startMove",(e=>{if(this.loaded&&is.event(e)&&["touchmove","mousemove"].includes(e.type)&&this.player.media.duration){if("touchmove"===e.type)this.seekTime=this.player.media.duration*(this.player.elements.inputs.seek.value/100);else{const t=this.player.elements.progress.getBoundingClientRect(),i=100/t.width*(e.pageX-t.left);this.seekTime=this.player.media.duration*(i/100),this.seekTime<0&&(this.seekTime=0),this.seekTime>this.player.media.duration-1&&(this.seekTime=this.player.media.duration-1),this.mousePosX=e.pageX,this.elements.thumb.time.innerText=formatTime(this.seekTime)}this.showImageAtCurrentTime()}})),_defineProperty$1(this,"endMove",(()=>{this.toggleThumbContainer(!1,!0)})),_defineProperty$1(this,"startScrubbing",(e=>{(is.nullOrUndefined(e.button)||!1===e.button||0===e.button)&&(this.mouseDown=!0,this.player.media.duration&&(this.toggleScrubbingContainer(!0),this.toggleThumbContainer(!1,!0),this.showImageAtCurrentTime()))})),_defineProperty$1(this,"endScrubbing",(()=>{this.mouseDown=!1,Math.ceil(this.lastTime)===Math.ceil(this.player.media.currentTime)?this.toggleScrubbingContainer(!1):once.call(this.player,this.player.media,"timeupdate",(()=>{this.mouseDown||this.toggleScrubbingContainer(!1)}))})),_defineProperty$1(this,"listeners",(()=>{this.player.on("play",(()=>{this.toggleThumbContainer(!1,!0)})),this.player.on("seeked",(()=>{this.toggleThumbContainer(!1)})),this.player.on("timeupdate",(()=>{this.lastTime=this.player.media.currentTime}))})),_defineProperty$1(this,"render",(()=>{this.elements.thumb.container=createElement("div",{class:this.player.config.classNames.previewThumbnails.thumbContainer}),this.elements.thumb.imageContainer=createElement("div",{class:this.player.config.classNames.previewThumbnails.imageContainer}),this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer);const e=createElement("div",{class:this.player.config.classNames.previewThumbnails.timeContainer});this.elements.thumb.time=createElement("span",{},"00:00"),e.appendChild(this.elements.thumb.time),this.elements.thumb.container.appendChild(e),is.element(this.player.elements.progress)&&this.player.elements.progress.appendChild(this.elements.thumb.container),this.elements.scrubbing.container=createElement("div",{class:this.player.config.classNames.previewThumbnails.scrubbingContainer}),this.player.elements.wrapper.appendChild(this.elements.scrubbing.container)})),_defineProperty$1(this,"destroy",(()=>{this.elements.thumb.container&&this.elements.thumb.container.remove(),this.elements.scrubbing.container&&this.elements.scrubbing.container.remove()})),_defineProperty$1(this,"showImageAtCurrentTime",(()=>{this.mouseDown?this.setScrubbingContainerSize():this.setThumbContainerSizeAndPos();const e=this.thumbnails[0].frames.findIndex((e=>this.seekTime>=e.startTime&&this.seekTime<=e.endTime)),t=e>=0;let i=0;this.mouseDown||this.toggleThumbContainer(t),t&&(this.thumbnails.forEach(((t,s)=>{this.loadedImages.includes(t.frames[e].text)&&(i=s)})),e!==this.showingThumb&&(this.showingThumb=e,this.loadImage(i)))})),_defineProperty$1(this,"loadImage",((e=0)=>{const t=this.showingThumb,i=this.thumbnails[e],{urlPrefix:s}=i,n=i.frames[t],r=i.frames[t].text,a=s+r;if(this.currentImageElement&&this.currentImageElement.dataset.filename===r)this.showImage(this.currentImageElement,n,e,t,r,!1),this.currentImageElement.dataset.index=t,this.removeOldImages(this.currentImageElement);else{this.loadingImage&&this.usingSprites&&(this.loadingImage.onload=null);const i=new Image;i.src=a,i.dataset.index=t,i.dataset.filename=r,this.showingThumbFilename=r,this.player.debug.log(`Loading image: ${a}`),i.onload=()=>this.showImage(i,n,e,t,r,!0),this.loadingImage=i,this.removeOldImages(i)}})),_defineProperty$1(this,"showImage",((e,t,i,s,n,r=!0)=>{this.player.debug.log(`Showing thumb: ${n}. num: ${s}. qual: ${i}. newimg: ${r}`),this.setImageSizeAndOffset(e,t),r&&(this.currentImageContainer.appendChild(e),this.currentImageElement=e,this.loadedImages.includes(n)||this.loadedImages.push(n)),this.preloadNearby(s,!0).then(this.preloadNearby(s,!1)).then(this.getHigherQuality(i,e,t,n))})),_defineProperty$1(this,"removeOldImages",(e=>{Array.from(this.currentImageContainer.children).forEach((t=>{if("img"!==t.tagName.toLowerCase())return;const i=this.usingSprites?500:1e3;if(t.dataset.index!==e.dataset.index&&!t.dataset.deleting){t.dataset.deleting=!0;const{currentImageContainer:e}=this;setTimeout((()=>{e.removeChild(t),this.player.debug.log(`Removing thumb: ${t.dataset.filename}`)}),i)}}))})),_defineProperty$1(this,"preloadNearby",((e,t=!0)=>new Promise((i=>{setTimeout((()=>{const s=this.thumbnails[0].frames[e].text;if(this.showingThumbFilename===s){let n;n=t?this.thumbnails[0].frames.slice(e):this.thumbnails[0].frames.slice(0,e).reverse();let r=!1;n.forEach((e=>{const t=e.text;if(t!==s&&!this.loadedImages.includes(t)){r=!0,this.player.debug.log(`Preloading thumb filename: ${t}`);const{urlPrefix:e}=this.thumbnails[0],s=e+t,n=new Image;n.src=s,n.onload=()=>{this.player.debug.log(`Preloaded thumb filename: ${t}`),this.loadedImages.includes(t)||this.loadedImages.push(t),i()}}})),r||i()}}),300)})))),_defineProperty$1(this,"getHigherQuality",((e,t,i,s)=>{if(e<this.thumbnails.length-1){let n=t.naturalHeight;this.usingSprites&&(n=i.h),n<this.thumbContainerHeight&&setTimeout((()=>{this.showingThumbFilename===s&&(this.player.debug.log(`Showing higher quality thumb for: ${s}`),this.loadImage(e+1))}),300)}})),_defineProperty$1(this,"toggleThumbContainer",((e=!1,t=!1)=>{const i=this.player.config.classNames.previewThumbnails.thumbContainerShown;this.elements.thumb.container.classList.toggle(i,e),!e&&t&&(this.showingThumb=null,this.showingThumbFilename=null)})),_defineProperty$1(this,"toggleScrubbingContainer",((e=!1)=>{const t=this.player.config.classNames.previewThumbnails.scrubbingContainerShown;this.elements.scrubbing.container.classList.toggle(t,e),e||(this.showingThumb=null,this.showingThumbFilename=null)})),_defineProperty$1(this,"determineContainerAutoSizing",(()=>{(this.elements.thumb.imageContainer.clientHeight>20||this.elements.thumb.imageContainer.clientWidth>20)&&(this.sizeSpecifiedInCSS=!0)})),_defineProperty$1(this,"setThumbContainerSizeAndPos",(()=>{if(this.sizeSpecifiedInCSS){if(this.elements.thumb.imageContainer.clientHeight>20&&this.elements.thumb.imageContainer.clientWidth<20){const e=Math.floor(this.elements.thumb.imageContainer.clientHeight*this.thumbAspectRatio);this.elements.thumb.imageContainer.style.width=`${e}px`}else if(this.elements.thumb.imageContainer.clientHeight<20&&this.elements.thumb.imageContainer.clientWidth>20){const e=Math.floor(this.elements.thumb.imageContainer.clientWidth/this.thumbAspectRatio);this.elements.thumb.imageContainer.style.height=`${e}px`}}else{const e=Math.floor(this.thumbContainerHeight*this.thumbAspectRatio);this.elements.thumb.imageContainer.style.height=`${this.thumbContainerHeight}px`,this.elements.thumb.imageContainer.style.width=`${e}px`}this.setThumbContainerPos()})),_defineProperty$1(this,"setThumbContainerPos",(()=>{const e=this.player.elements.progress.getBoundingClientRect(),t=this.player.elements.container.getBoundingClientRect(),{container:i}=this.elements.thumb,s=t.left-e.left+10,n=t.right-e.left-i.clientWidth-10;let r=this.mousePosX-e.left-i.clientWidth/2;r<s&&(r=s),r>n&&(r=n),i.style.left=`${r}px`})),_defineProperty$1(this,"setScrubbingContainerSize",(()=>{const{width:e,height:t}=fitRatio(this.thumbAspectRatio,{width:this.player.media.clientWidth,height:this.player.media.clientHeight});this.elements.scrubbing.container.style.width=`${e}px`,this.elements.scrubbing.container.style.height=`${t}px`})),_defineProperty$1(this,"setImageSizeAndOffset",((e,t)=>{if(!this.usingSprites)return;const i=this.thumbContainerHeight/t.h;e.style.height=e.naturalHeight*i+"px",e.style.width=e.naturalWidth*i+"px",e.style.left=`-${t.x*i}px`,e.style.top=`-${t.y*i}px`})),this.player=e,this.thumbnails=[],this.loaded=!1,this.lastMouseMoveTime=Date.now(),this.mouseDown=!1,this.loadedImages=[],this.elements={thumb:{},scrubbing:{}},this.load()}get enabled(){return this.player.isHTML5&&this.player.isVideo&&this.player.config.previewThumbnails.enabled}get currentImageContainer(){return this.mouseDown?this.elements.scrubbing.container:this.elements.thumb.imageContainer}get usingSprites(){return Object.keys(this.thumbnails[0].frames[0]).includes("w")}get thumbAspectRatio(){return this.usingSprites?this.thumbnails[0].frames[0].w/this.thumbnails[0].frames[0].h:this.thumbnails[0].width/this.thumbnails[0].height}get thumbContainerHeight(){if(this.mouseDown){const{height:e}=fitRatio(this.thumbAspectRatio,{width:this.player.media.clientWidth,height:this.player.media.clientHeight});return e}return this.sizeSpecifiedInCSS?this.elements.thumb.imageContainer.clientHeight:Math.floor(this.player.media.clientWidth/this.thumbAspectRatio/4)}get currentImageElement(){return this.mouseDown?this.currentScrubbingImageElement:this.currentThumbnailImageElement}set currentImageElement(e){this.mouseDown?this.currentScrubbingImageElement=e:this.currentThumbnailImageElement=e}}const source={insertElements(e,t){is.string(t)?insertElement(e,this.media,{src:t}):is.array(t)&&t.forEach((t=>{insertElement(e,this.media,t)}))},change(e){getDeep(e,"sources.length")?(html5.cancelRequests.call(this),this.destroy.call(this,(()=>{this.options.quality=[],removeElement(this.media),this.media=null,is.element(this.elements.container)&&this.elements.container.removeAttribute("class");const{sources:t,type:i}=e,[{provider:s=providers.html5,src:n}]=t,r="html5"===s?i:"div",a="html5"===s?{}:{src:n};Object.assign(this,{provider:s,type:i,supported:support.check(i,s,this.config.playsinline),media:createElement(r,a)}),this.elements.container.appendChild(this.media),is.boolean(e.autoplay)&&(this.config.autoplay=e.autoplay),this.isHTML5&&(this.config.crossorigin&&this.media.setAttribute("crossorigin",""),this.config.autoplay&&this.media.setAttribute("autoplay",""),is.empty(e.poster)||(this.poster=e.poster),this.config.loop.active&&this.media.setAttribute("loop",""),this.config.muted&&this.media.setAttribute("muted",""),this.config.playsinline&&this.media.setAttribute("playsinline","")),ui.addStyleHook.call(this),this.isHTML5&&source.insertElements.call(this,"source",t),this.config.title=e.title,media.setup.call(this),this.isHTML5&&Object.keys(e).includes("tracks")&&source.insertElements.call(this,"track",e.tracks),(this.isHTML5||this.isEmbed&&!this.supported.ui)&&ui.build.call(this),this.isHTML5&&this.media.load(),is.empty(e.previewThumbnails)||(Object.assign(this.config.previewThumbnails,e.previewThumbnails),this.previewThumbnails&&this.previewThumbnails.loaded&&(this.previewThumbnails.destroy(),this.previewThumbnails=null),this.config.previewThumbnails.enabled&&(this.previewThumbnails=new PreviewThumbnails(this))),this.fullscreen.update()}),!0)):this.debug.warn("Invalid source format")}};function clamp(e=0,t=0,i=255){return Math.min(Math.max(e,t),i)}class Plyr{constructor(e,t){if(_defineProperty$1(this,"play",(()=>is.function(this.media.play)?(this.ads&&this.ads.enabled&&this.ads.managerPromise.then((()=>this.ads.play())).catch((()=>silencePromise(this.media.play()))),this.media.play()):null)),_defineProperty$1(this,"pause",(()=>this.playing&&is.function(this.media.pause)?this.media.pause():null)),_defineProperty$1(this,"togglePlay",(e=>(is.boolean(e)?e:!this.playing)?this.play():this.pause())),_defineProperty$1(this,"stop",(()=>{this.isHTML5?(this.pause(),this.restart()):is.function(this.media.stop)&&this.media.stop()})),_defineProperty$1(this,"restart",(()=>{this.currentTime=0})),_defineProperty$1(this,"rewind",(e=>{this.currentTime-=is.number(e)?e:this.config.seekTime})),_defineProperty$1(this,"forward",(e=>{this.currentTime+=is.number(e)?e:this.config.seekTime})),_defineProperty$1(this,"increaseVolume",(e=>{const t=this.media.muted?0:this.volume;this.volume=t+(is.number(e)?e:0)})),_defineProperty$1(this,"decreaseVolume",(e=>{this.increaseVolume(-e)})),_defineProperty$1(this,"airplay",(()=>{support.airplay&&this.media.webkitShowPlaybackTargetPicker()})),_defineProperty$1(this,"toggleControls",(e=>{if(this.supported.ui&&!this.isAudio){const t=hasClass(this.elements.container,this.config.classNames.hideControls),i=void 0===e?void 0:!e,s=toggleClass(this.elements.container,this.config.classNames.hideControls,i);if(s&&is.array(this.config.controls)&&this.config.controls.includes("settings")&&!is.empty(this.config.settings)&&controls.toggleMenu.call(this,!1),s!==t){const e=s?"controlshidden":"controlsshown";triggerEvent.call(this,this.media,e)}return!s}return!1})),_defineProperty$1(this,"on",((e,t)=>{on.call(this,this.elements.container,e,t)})),_defineProperty$1(this,"once",((e,t)=>{once.call(this,this.elements.container,e,t)})),_defineProperty$1(this,"off",((e,t)=>{off(this.elements.container,e,t)})),_defineProperty$1(this,"destroy",((e,t=!1)=>{if(!this.ready)return;const i=()=>{document.body.style.overflow="",this.embed=null,t?(Object.keys(this.elements).length&&(removeElement(this.elements.buttons.play),removeElement(this.elements.captions),removeElement(this.elements.controls),removeElement(this.elements.wrapper),this.elements.buttons.play=null,this.elements.captions=null,this.elements.controls=null,this.elements.wrapper=null),is.function(e)&&e()):(unbindListeners.call(this),html5.cancelRequests.call(this),replaceElement(this.elements.original,this.elements.container),triggerEvent.call(this,this.elements.original,"destroyed",!0),is.function(e)&&e.call(this.elements.original),this.ready=!1,setTimeout((()=>{this.elements=null,this.media=null}),200))};this.stop(),clearTimeout(this.timers.loading),clearTimeout(this.timers.controls),clearTimeout(this.timers.resized),this.isHTML5?(ui.toggleNativeControls.call(this,!0),i()):this.isYouTube?(clearInterval(this.timers.buffering),clearInterval(this.timers.playing),null!==this.embed&&is.function(this.embed.destroy)&&this.embed.destroy(),i()):this.isVimeo&&(null!==this.embed&&this.embed.unload().then(i),setTimeout(i,200))})),_defineProperty$1(this,"supports",(e=>support.mime.call(this,e))),this.timers={},this.ready=!1,this.loading=!1,this.failed=!1,this.touch=support.touch,this.media=e,is.string(this.media)&&(this.media=document.querySelectorAll(this.media)),(window.jQuery&&this.media instanceof jQuery||is.nodeList(this.media)||is.array(this.media))&&(this.media=this.media[0]),this.config=extend({},defaults,Plyr.defaults,t||{},(()=>{try{return JSON.parse(this.media.getAttribute("data-plyr-config"))}catch(e){return{}}})()),this.elements={container:null,fullscreen:null,captions:null,buttons:{},display:{},progress:{},inputs:{},settings:{popup:null,menu:null,panels:{},buttons:{}}},this.captions={active:null,currentTrack:-1,meta:new WeakMap},this.fullscreen={active:!1},this.options={speed:[],quality:[]},this.debug=new Console(this.config.debug),this.debug.log("Config",this.config),this.debug.log("Support",support),is.nullOrUndefined(this.media)||!is.element(this.media))return void this.debug.error("Setup failed: no suitable element passed");if(this.media.plyr)return void this.debug.warn("Target already setup");if(!this.config.enabled)return void this.debug.error("Setup failed: disabled by config");if(!support.check().api)return void this.debug.error("Setup failed: no support");const i=this.media.cloneNode(!0);i.autoplay=!1,this.elements.original=i;const s=this.media.tagName.toLowerCase();let n=null,r=null;switch(s){case"div":if(n=this.media.querySelector("iframe"),is.element(n)){if(r=parseUrl(n.getAttribute("src")),this.provider=getProviderByUrl(r.toString()),this.elements.container=this.media,this.media=n,this.elements.container.className="",r.search.length){const e=["1","true"];e.includes(r.searchParams.get("autoplay"))&&(this.config.autoplay=!0),e.includes(r.searchParams.get("loop"))&&(this.config.loop.active=!0),this.isYouTube?(this.config.playsinline=e.includes(r.searchParams.get("playsinline")),this.config.youtube.hl=r.searchParams.get("hl")):this.config.playsinline=!0}}else this.provider=this.media.getAttribute(this.config.attributes.embed.provider),this.media.removeAttribute(this.config.attributes.embed.provider);if(is.empty(this.provider)||!Object.values(providers).includes(this.provider))return void this.debug.error("Setup failed: Invalid provider");this.type=types.video;break;case"video":case"audio":this.type=s,this.provider=providers.html5,this.media.hasAttribute("crossorigin")&&(this.config.crossorigin=!0),this.media.hasAttribute("autoplay")&&(this.config.autoplay=!0),(this.media.hasAttribute("playsinline")||this.media.hasAttribute("webkit-playsinline"))&&(this.config.playsinline=!0),this.media.hasAttribute("muted")&&(this.config.muted=!0),this.media.hasAttribute("loop")&&(this.config.loop.active=!0);break;default:return void this.debug.error("Setup failed: unsupported type")}this.supported=support.check(this.type,this.provider,this.config.playsinline),this.supported.api?(this.eventListeners=[],this.listeners=new Listeners(this),this.storage=new Storage(this),this.media.plyr=this,is.element(this.elements.container)||(this.elements.container=createElement("div",{tabindex:0}),wrap(this.media,this.elements.container)),ui.migrateStyles.call(this),ui.addStyleHook.call(this),media.setup.call(this),this.config.debug&&on.call(this,this.elements.container,this.config.events.join(" "),(e=>{this.debug.log(`event: ${e.type}`)})),this.fullscreen=new Fullscreen(this),(this.isHTML5||this.isEmbed&&!this.supported.ui)&&ui.build.call(this),this.listeners.container(),this.listeners.global(),this.config.ads.enabled&&(this.ads=new Ads(this)),this.isHTML5&&this.config.autoplay&&this.once("canplay",(()=>silencePromise(this.play()))),this.lastSeekTime=0,this.config.previewThumbnails.enabled&&(this.previewThumbnails=new PreviewThumbnails(this))):this.debug.error("Setup failed: no support")}get isHTML5(){return this.provider===providers.html5}get isEmbed(){return this.isYouTube||this.isVimeo}get isYouTube(){return this.provider===providers.youtube}get isVimeo(){return this.provider===providers.vimeo}get isVideo(){return this.type===types.video}get isAudio(){return this.type===types.audio}get playing(){return Boolean(this.ready&&!this.paused&&!this.ended)}get paused(){return Boolean(this.media.paused)}get stopped(){return Boolean(this.paused&&0===this.currentTime)}get ended(){return Boolean(this.media.ended)}set currentTime(e){if(!this.duration)return;const t=is.number(e)&&e>0;this.media.currentTime=t?Math.min(e,this.duration):0,this.debug.log(`Seeking to ${this.currentTime} seconds`)}get currentTime(){return Number(this.media.currentTime)}get buffered(){const{buffered:e}=this.media;return is.number(e)?e:e&&e.length&&this.duration>0?e.end(0)/this.duration:0}get seeking(){return Boolean(this.media.seeking)}get duration(){const e=parseFloat(this.config.duration),t=(this.media||{}).duration,i=is.number(t)&&t!==1/0?t:0;return e||i}set volume(e){let t=e;is.string(t)&&(t=Number(t)),is.number(t)||(t=this.storage.get("volume")),is.number(t)||({volume:t}=this.config),t>1&&(t=1),t<0&&(t=0),this.config.volume=t,this.media.volume=t,!is.empty(e)&&this.muted&&t>0&&(this.muted=!1)}get volume(){return Number(this.media.volume)}set muted(e){let t=e;is.boolean(t)||(t=this.storage.get("muted")),is.boolean(t)||(t=this.config.muted),this.config.muted=t,this.media.muted=t}get muted(){return Boolean(this.media.muted)}get hasAudio(){return!this.isHTML5||(!!this.isAudio||(Boolean(this.media.mozHasAudio)||Boolean(this.media.webkitAudioDecodedByteCount)||Boolean(this.media.audioTracks&&this.media.audioTracks.length)))}set speed(e){let t=null;is.number(e)&&(t=e),is.number(t)||(t=this.storage.get("speed")),is.number(t)||(t=this.config.speed.selected);const{minimumSpeed:i,maximumSpeed:s}=this;t=clamp(t,i,s),this.config.speed.selected=t,setTimeout((()=>{this.media&&(this.media.playbackRate=t)}),0)}get speed(){return Number(this.media.playbackRate)}get minimumSpeed(){return this.isYouTube?Math.min(...this.options.speed):this.isVimeo?.5:.0625}get maximumSpeed(){return this.isYouTube?Math.max(...this.options.speed):this.isVimeo?2:16}set quality(e){const t=this.config.quality,i=this.options.quality;if(!i.length)return;let s=[!is.empty(e)&&Number(e),this.storage.get("quality"),t.selected,t.default].find(is.number),n=!0;if(!i.includes(s)){const e=closest(i,s);this.debug.warn(`Unsupported quality option: ${s}, using ${e} instead`),s=e,n=!1}t.selected=s,this.media.quality=s,n&&this.storage.set({quality:s})}get quality(){return this.media.quality}set loop(e){const t=is.boolean(e)?e:this.config.loop.active;this.config.loop.active=t,this.media.loop=t}get loop(){return Boolean(this.media.loop)}set source(e){source.change.call(this,e)}get source(){return this.media.currentSrc}get download(){const{download:e}=this.config.urls;return is.url(e)?e:this.source}set download(e){is.url(e)&&(this.config.urls.download=e,controls.setDownloadUrl.call(this))}set poster(e){this.isVideo?ui.setPoster.call(this,e,!1).catch((()=>{})):this.debug.warn("Poster can only be set for video")}get poster(){return this.isVideo?this.media.getAttribute("poster")||this.media.getAttribute("data-poster"):null}get ratio(){if(!this.isVideo)return null;const e=reduceAspectRatio(getAspectRatio.call(this));return is.array(e)?e.join(":"):e}set ratio(e){this.isVideo?is.string(e)&&validateAspectRatio(e)?(this.config.ratio=reduceAspectRatio(e),setAspectRatio.call(this)):this.debug.error(`Invalid aspect ratio specified (${e})`):this.debug.warn("Aspect ratio can only be set for video")}set autoplay(e){const t=is.boolean(e)?e:this.config.autoplay;this.config.autoplay=t}get autoplay(){return Boolean(this.config.autoplay)}toggleCaptions(e){captions.toggle.call(this,e,!1)}set currentTrack(e){captions.set.call(this,e,!1),captions.setup()}get currentTrack(){const{toggled:e,currentTrack:t}=this.captions;return e?t:-1}set language(e){captions.setLanguage.call(this,e,!1)}get language(){return(captions.getCurrentTrack.call(this)||{}).language}set pip(e){if(!support.pip)return;const t=is.boolean(e)?e:!this.pip;is.function(this.media.webkitSetPresentationMode)&&this.media.webkitSetPresentationMode(t?pip.active:pip.inactive),is.function(this.media.requestPictureInPicture)&&(!this.pip&&t?this.media.requestPictureInPicture():this.pip&&!t&&document.exitPictureInPicture())}get pip(){return support.pip?is.empty(this.media.webkitPresentationMode)?this.media===document.pictureInPictureElement:this.media.webkitPresentationMode===pip.active:null}setPreviewThumbnails(e){this.previewThumbnails&&this.previewThumbnails.loaded&&(this.previewThumbnails.destroy(),this.previewThumbnails=null),Object.assign(this.config.previewThumbnails,e),this.config.previewThumbnails.enabled&&(this.previewThumbnails=new PreviewThumbnails(this))}static supported(e,t,i){return support.check(e,t,i)}static loadSprite(e,t){return loadSprite(e,t)}static setup(e,t={}){let i=null;return is.string(e)?i=Array.from(document.querySelectorAll(e)):is.nodeList(e)?i=Array.from(e):is.array(e)&&(i=e.filter(is.element)),is.empty(i)?null:i.map((e=>new Plyr(e,t)))}}Plyr.defaults=cloneDeep(defaults);export{Plyr as default};
\ No newline at end of file diff --git a/extlib/plyr/plyr.min.mjs.map b/extlib/plyr/plyr.min.mjs.map new file mode 100644 index 00000000..9c3306e7 --- /dev/null +++ b/extlib/plyr/plyr.min.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["plyr.mjs","node_modules/rangetouch/dist/rangetouch.mjs","src/js/utils/is.js","src/js/utils/animation.js","src/js/utils/browser.js","src/js/utils/objects.js","src/js/utils/elements.js","src/js/support.js","src/js/utils/events.js","src/js/utils/promise.js","src/js/utils/arrays.js","src/js/utils/style.js","src/js/html5.js","src/js/utils/strings.js","src/js/utils/i18n.js","src/js/storage.js","src/js/utils/fetch.js","src/js/utils/load-sprite.js","src/js/utils/time.js","src/js/controls.js","src/js/utils/urls.js","src/js/captions.js","src/js/config/defaults.js","src/js/config/states.js","src/js/config/types.js","src/js/console.js","src/js/fullscreen.js","src/js/utils/load-image.js","src/js/ui.js","src/js/listeners.js","node_modules/loadjs/dist/loadjs.umd.js","src/js/utils/load-script.js","src/js/plugins/vimeo.js","src/js/plugins/youtube.js","src/js/media.js","src/js/plugins/ads.js","src/js/plugins/preview-thumbnails.js","src/js/source.js","src/js/utils/numbers.js","src/js/plyr.js"],"names":["_defineProperty$1","obj","key","value","Object","defineProperty","enumerable","configurable","writable","_classCallCheck","e","t","TypeError","_defineProperties","n","length","r","_createClass","prototype","_defineProperty","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","push","apply","_objectSpread2","arguments","forEach","getOwnPropertyDescriptors","defineProperties","defaults","addCSS","thumbWidth","watch","matches","Array","from","document","querySelectorAll","includes","this","call","trigger","Event","bubbles","dispatchEvent","getConstructor","constructor","instanceOf","isNullOrUndefined","isObject","isNumber","Number","isNaN","isString","String","isBoolean","Boolean","isFunction","Function","isArray","isNodeList","NodeList","isElement","Element","isEvent","isEmpty","is","nullOrUndefined","object","number","string","boolean","function","array","nodeList","element","event","empty","getDecimalPlaces","concat","match","Math","max","round","parseFloat","toFixed","RangeTouch","querySelector","rangeTouch","config","init","enabled","style","userSelect","webKitUserSelect","touchAction","listeners","set","target","i","changedTouches","o","getAttribute","s","u","c","getBoundingClientRect","a","width","clientX","left","disabled","preventDefault","get","type","MutationObserver","addedNodes","observe","body","childList","subtree","map","documentElement","input","isWeakMap","WeakMap","isTextNode","Text","isKeyboardEvent","KeyboardEvent","isCue","window","TextTrackCue","VTTCue","isTrack","TextTrack","kind","isPromise","Promise","then","nodeType","ownerDocument","isUrl","URL","startsWith","hostname","_","weakMap","textNode","keyboardEvent","cue","track","promise","url","transitionEndEvent","createElement","events","WebkitTransition","MozTransition","OTransition","transition","find","undefined","repaint","delay","setTimeout","hidden","offsetHeight","browser","isIE","documentMode","isEdge","navigator","userAgent","isWebkit","test","isIPhone","platform","isIos","maxTouchPoints","cloneDeep","JSON","parse","stringify","getDeep","path","split","reduce","extend","sources","source","shift","assign","wrap","elements","wrapper","targets","reverse","index","child","cloneNode","parent","parentNode","sibling","nextSibling","appendChild","insertBefore","setAttributes","attributes","entries","setAttribute","text","innerText","insertAfter","insertElement","removeElement","removeChild","emptyElement","childNodes","lastChild","replaceElement","newChild","oldChild","replaceChild","getAttributesFromSelector","sel","existingAttributes","existing","selector","trim","className","replace","parts","charAt","class","id","toggleHidden","hide","toggleClass","force","method","classList","contains","hasClass","webkitMatchesSelector","mozMatchesSelector","msMatchesSelector","closest","el","parentElement","getElements","container","getElement","setFocus","tabFocus","focus","preventScroll","classNames","defaultCodecs","support","audio","video","check","provider","playsinline","canPlayInline","api","ui","rangeInput","pip","webkitSetPresentationMode","pictureInPictureEnabled","disablePictureInPicture","airplay","WebKitPlaybackTargetAvailabilityEvent","mime","mediaType","isHTML5","media","canPlayType","textTracks","range","touch","transitions","reducedMotion","matchMedia","supportsPassiveListeners","supported","options","addEventListener","removeEventListener","toggleListener","callback","toggle","passive","capture","eventListeners","on","off","once","onceCallback","args","triggerEvent","detail","CustomEvent","plyr","unbindListeners","item","ready","resolve","silencePromise","dedupe","indexOf","prev","curr","abs","supportsCSS","declaration","CSS","supports","standardRatios","out","x","y","validateAspectRatio","every","reduceAspectRatio","ratio","height","getDivider","w","h","divider","getAspectRatio","embed","videoWidth","videoHeight","setAspectRatio","isVideo","padding","aspectRatio","paddingBottom","isVimeo","vimeo","premium","offsetWidth","parseInt","getComputedStyle","offset","fullscreen","active","transform","add","videoFixedRatio","roundAspectRatio","tolerance","closestRatio","getViewportSize","clientWidth","innerWidth","clientHeight","innerHeight","html5","getSources","getQualityOptions","quality","forced","setup","player","speed","onChange","currentTime","paused","preload","readyState","playbackRate","src","play","load","cancelRequests","blankVideo","debug","log","generateId","prefix","floor","random","format","toString","getPercentage","current","replaceAll","RegExp","toTitleCase","toUpperCase","substr","toLowerCase","toPascalCase","toCamelCase","slice","stripHTML","fragment","createDocumentFragment","innerHTML","firstChild","getHTML","resources","youtube","i18n","seekTime","title","k","v","Storage","store","localStorage","getItem","json","storage","setItem","removeItem","fetch","responseType","reject","request","XMLHttpRequest","responseText","response","Error","status","open","send","error","loadSprite","hasId","isCached","exists","getElementById","update","data","insertAdjacentElement","useStorage","cached","content","result","catch","getHours","trunc","getMinutes","getSeconds","formatTime","time","displayHours","inverted","hours","mins","secs","controls","getIconUrl","iconUrl","location","host","top","cors","svg4everybody","findElements","selectors","buttons","pause","restart","rewind","fastForward","mute","settings","captions","progress","inputs","seek","volume","display","buffer","duration","seekTooltip","tooltip","warn","toggleNativeControls","createIcon","namespace","iconPath","iconPrefix","icon","createElementNS","focusable","use","setAttributeNS","createLabel","attr","join","createBadge","badge","menu","createButton","buttonType","props","label","labelPressed","iconPressed","some","control","button","createRange","min","step","autocomplete","role","updateRangeFill","createProgress","suffixKey","played","suffix","createTime","attrs","bindMenuItemShortcuts","menuItem","which","stopPropagation","isRadioButton","showMenuPanel","nextElementSibling","firstElementChild","previousElementSibling","lastElementChild","focusFirstMenuItem","createMenuItem","list","checked","flex","children","node","bind","currentTrack","updateTimeDisplay","updateVolume","setRange","muted","pressed","updateProgress","setProgress","val","getElementsByTagName","nodeValue","buffered","percent","setProperty","updateSeekTooltip","tooltips","visible","show","clientRect","pageX","timeUpdate","invert","invertTime","seeking","durationUpdate","hasDuration","displayDuration","toggleMenuButton","setting","updateSetting","pane","panels","default","getLabel","setQualityMenu","checkMenu","getBadge","sort","b","sorting","setCaptionsMenu","tracks","getTracks","toggled","language","unshift","setSpeedMenu","minimumSpeed","maximumSpeed","values","popup","p","firstItem","toggleMenu","composedPath","isMenuItem","getMenuSize","tab","clone","position","opacity","removeAttribute","scrollWidth","scrollHeight","size","restore","propertyName","setDownloadUrl","download","create","defaultAttributes","progressContainer","inner","home","backButton","href","urls","isEmbed","inject","seektime","addProperty","controlPressed","labels","parseUrl","safe","parser","buildUrlParams","params","URLSearchParams","isYouTube","protocol","blob","createObjectURL","languages","userLanguage","trackEvents","meta","currentTrackNode","languageExists","mode","updateCues","setLanguage","activeClass","findTrack","enableTextTrack","has","sortIsDefault","sorted","getCurrentTrack","cues","activeCues","getCueAsHTML","cueText","caption","autoplay","autopause","toggleInvert","clickToPlay","hideControls","resetOnEnd","disableContextMenu","loop","selected","keyboard","focused","global","fallback","iosNative","seekLabel","unmute","enableCaptions","disableCaptions","enterFullscreen","exitFullscreen","frameTitle","menuBack","normal","start","end","all","reset","advertisement","qualityBadge","sdk","iframe","googleIMA","editable","embedContainer","poster","posterEnabled","ads","playing","stopped","loading","hover","isTouch","uiSupported","noTransition","previewThumbnails","thumbContainer","thumbContainerShown","imageContainer","timeContainer","scrubbingContainer","scrubbingContainerShown","hash","publisherId","tagUrl","byline","portrait","transparent","customControls","referrerPolicy","rel","showinfo","iv_load_policy","modestbranding","noCookie","inactive","providers","types","getProviderByUrl","noop","Console","console","Fullscreen","scrollPosition","scrollX","scrollY","scrollTo","overflow","viewport","head","property","hasProperty","cleanupViewport","part","keyCode","activeElement","first","last","shiftKey","forceFallback","native","requestFullscreen","webkitEnterFullscreen","toggleFallback","navigationUI","webkitExitFullscreen","action","cancelFullScreen","exit","enter","proxy","trapFocus","fullscreenEnabled","webkitFullscreenEnabled","mozFullScreenEnabled","msFullscreenEnabled","usingNative","pre","getRootNode","fullscreenElement","shadowRoot","loadImage","minWidth","image","Image","handler","onload","onerror","naturalWidth","addStyleHook","build","checkPlaying","setTitle","setPoster","togglePoster","enable","backgroundImage","backgroundSize","toggleControls","checkLoading","clearTimeout","timers","controlsElement","recentTouchSeek","lastSeekTime","Date","now","migrateStyles","getPropertyValue","removeProperty","Listeners","focusTimer","lastKeyDown","timeStamp","wasKeyDown","removeCurrent","handleKey","firstTouch","setTabFocus","setGutter","useNativeAspectRatio","maxWidth","margin","viewportWidth","viewportHeight","resized","isAudio","ended","togglePlay","proxyEvents","defaultHandler","customHandlerKey","customHandler","returned","hasCustomHandler","inputEvent","forward","toggleCaptions","code","rect","currentTarget","attribute","hasAttribute","done","seekTo","loaded","startMove","endMove","startScrubbing","endScrubbing","webkitDirectionInvertedFromDevice","deltaX","deltaY","direction","sign","increaseVolume","lastKey","repeat","altKey","ctrlKey","metaKey","decreaseVolume","commonjsGlobal","globalThis","self","createCommonjsModule","fn","module","exports","loadjs_umd","devnull","bundleIdCache","bundleResultCache","bundleCallbackQueue","subscribe","bundleIds","callbackFn","bundleId","depsNotFound","numWaiting","pathsNotFound","publish","q","splice","executeCallbacks","success","loadFile","numTries","isLegacyIECss","doc","async","maxTries","numRetries","beforeCallbackFn","before","pathname","pathStripped","relList","as","onbeforeload","ev","sheet","cssText","defaultPrevented","loadFiles","paths","loadjs","arg1","arg2","loadFn","returnPromise","deps","isDefined","factory","loadScript","parseId","$2","parseHash","found","groups","assurePlaybackState","hasPlayed","Vimeo","frameParams","hashParam","sidedock","gesture","thumbnail_url","Player","disableTextTrack","stop","restorePause","setVolume","setCurrentTime","setPlaybackRate","currentSrc","setLoop","getVideoUrl","getVideoWidth","getVideoHeight","dimensions","setAutopause","state","getVideoTitle","getCurrentTime","getDuration","getTextTracks","strippedCues","getPaused","seconds","getHost","YT","onYouTubeIframeAPIReady","getTitle","videoId","currentId","posterSrc","playerVars","hl","disablekb","cc_load_policy","cc_lang_pref","widget_referrer","onError","message","onPlaybackRateChange","instance","getPlaybackRate","onReady","playVideo","pauseVideo","stopVideo","speeds","getAvailablePlaybackRates","clearInterval","buffering","setInterval","getVideoLoadedFraction","lastBuffered","onStateChange","unMute","destroy","manager","displayContainer","remove","Ads","google","ima","startSafetyTimer","managerPromise","clearSafetyTimer","setupIMA","setVpaidMode","ImaSdkSettings","VpaidMode","ENABLED","setLocale","setDisableCustomPlaybackForIOS10Plus","AdDisplayContainer","loader","AdsLoader","AdsManagerLoadedEvent","Type","ADS_MANAGER_LOADED","onAdsManagerLoaded","AdErrorEvent","AD_ERROR","onAdError","requestAds","AdsRequest","adTagUrl","linearAdSlotWidth","linearAdSlotHeight","nonLinearAdSlotWidth","nonLinearAdSlotHeight","forceNonLinearFullSlot","setAdWillPlayMuted","countdownTimer","getRemainingTime","AdsRenderingSettings","restoreCustomPlaybackStateOnAdBreakComplete","enablePreloading","getAdsManager","cuePoints","getCuePoints","AdEvent","onAdEvent","cuePoint","seekElement","cuePercentage","ad","getAd","adData","getAdData","LOADED","pollCountdown","isLinear","STARTED","ALL_ADS_COMPLETED","loadAds","contentComplete","CONTENT_PAUSE_REQUESTED","pauseContent","CONTENT_RESUME_REQUESTED","resumeContent","LOG","adError","getMessage","cancel","addCuePoints","seekedTime","discardAdBreak","resize","ViewMode","NORMAL","initialize","initialized","zIndex","handlers","safetyTimer","AV_PUBLISHERID","AV_CHANNELID","AV_URL","cb","AV_WIDTH","AV_HEIGHT","AV_CDIM2","parseVtt","vttDataString","processedList","frame","line","startTime","lineSplit","matchTimes","endTime","fitRatio","outer","PreviewThumbnails","getThumbnails","render","determineContainerAutoSizing","sortAndResolve","thumbnails","promises","getThumbnail","thumbnail","frames","urlPrefix","substring","lastIndexOf","tempImage","naturalHeight","percentage","mousePosX","thumb","showImageAtCurrentTime","toggleThumbContainer","mouseDown","toggleScrubbingContainer","ceil","lastTime","scrubbing","setScrubbingContainerSize","setThumbContainerSizeAndPos","thumbNum","findIndex","hasThumb","qualityIndex","loadedImages","showingThumb","thumbFilename","thumbUrl","currentImageElement","dataset","filename","showImage","removeOldImages","loadingImage","usingSprites","previewImage","showingThumbFilename","newImage","setImageSizeAndOffset","currentImageContainer","preloadNearby","getHigherQuality","currentImage","tagName","removeDelay","deleting","oldThumbFilename","thumbnailsClone","foundOne","newThumbFilename","thumbURL","currentQualityIndex","previewImageHeight","thumbContainerHeight","clearShowing","sizeSpecifiedInCSS","thumbAspectRatio","thumbHeight","setThumbContainerPos","seekbarRect","plyrRect","minVal","maxVal","right","previewPos","multiplier","lastMouseMoveTime","currentScrubbingImageElement","currentThumbnailImageElement","insertElements","change","crossorigin","clamp","Plyr","webkitShowPlaybackTargetPicker","isHidden","hiding","eventName","soft","original","unload","failed","jQuery","search","truthy","searchParams","tabindex","inputIsValid","fauxDuration","realDuration","Infinity","hasAudio","mozHasAudio","webkitAudioDecodedByteCount","audioTracks","updateStorage","requestPictureInPicture","exitPictureInPicture","webkitPresentationMode","pictureInPictureElement","setPreviewThumbnails","thumbnailSource","static","inline"],"mappings":"AAAA,SAASA,kBAAkBC,EAAKC,EAAKC,GAYnC,OAXID,KAAOD,EACTG,OAAOC,eAAeJ,EAAKC,EAAK,CAC9BC,MAAOA,EACPG,YAAY,EACZC,cAAc,EACdC,UAAU,IAGZP,EAAIC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AAO+L,OAAOzJ,KAAKkD,OAAOimB,kBAAmBud,GAGzC1mC,KAAKkD,OAAOimB,kBAAkB/lB,UAChCpD,KAAKmpB,kBAAoB,IAAI2W,kBAAkB9/B,OAqMnC2mC,iBAAChiC,EAAMqJ,EAAU44B,GAC/B,OAAOh5B,QAAQG,MAAMpJ,EAAMqJ,EAAU44B,GAQtBD,kBAACz/B,EAAKkF,GACrB,OAAOsM,WAAWxR,EAAKkF,GAQbu6B,aAAC96B,EAAU4D,EAAU,IAC/B,IAAI5F,EAAU,KAUd,OARIlI,GAAGI,OAAO8J,GACZhC,EAAUlK,MAAMC,KAAKC,SAASC,iBAAiB+L,IACtClK,GAAGQ,SAAS0J,GACrBhC,EAAUlK,MAAMC,KAAKiM,GACZlK,GAAGO,MAAM2J,KAClBhC,EAAUgC,EAAShN,OAAO8C,GAAGS,UAG3BT,GAAGW,MAAMuH,GACJ,KAGFA,EAAQ3E,KAAKjH,GAAM,IAAI6mC,KAAK7mC,EAAGwR,MAI1Cq1B,KAAKxlC,SAAWuJ,UAAUvJ,iBvC4tOjBwlC","file":"plyr.min.mjs","sourcesContent":["function _defineProperty$1(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction _classCallCheck(e, t) {\n if (!(e instanceof t)) throw new TypeError(\"Cannot call a class as a function\");\n}\n\nfunction _defineProperties(e, t) {\n for (var n = 0; n < t.length; n++) {\n var r = t[n];\n r.enumerable = r.enumerable || !1, r.configurable = !0, \"value\" in r && (r.writable = !0), Object.defineProperty(e, r.key, r);\n }\n}\n\nfunction _createClass(e, t, n) {\n return t && _defineProperties(e.prototype, t), n && _defineProperties(e, n), e;\n}\n\nfunction _defineProperty(e, t, n) {\n return t in e ? Object.defineProperty(e, t, {\n value: n,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[t] = n, e;\n}\n\nfunction ownKeys(e, t) {\n var n = Object.keys(e);\n\n if (Object.getOwnPropertySymbols) {\n var r = Object.getOwnPropertySymbols(e);\n t && (r = r.filter(function (t) {\n return Object.getOwnPropertyDescriptor(e, t).enumerable;\n })), n.push.apply(n, r);\n }\n\n return n;\n}\n\nfunction _objectSpread2(e) {\n for (var t = 1; t < arguments.length; t++) {\n var n = null != arguments[t] ? arguments[t] : {};\n t % 2 ? ownKeys(Object(n), !0).forEach(function (t) {\n _defineProperty(e, t, n[t]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : ownKeys(Object(n)).forEach(function (t) {\n Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));\n });\n }\n\n return e;\n}\n\nvar defaults$1 = {\n addCSS: !0,\n thumbWidth: 15,\n watch: !0\n};\n\nfunction matches$1(e, t) {\n return function () {\n return Array.from(document.querySelectorAll(t)).includes(this);\n }.call(e, t);\n}\n\nfunction trigger(e, t) {\n if (e && t) {\n var n = new Event(t, {\n bubbles: !0\n });\n e.dispatchEvent(n);\n }\n}\n\nvar getConstructor$1 = function (e) {\n return null != e ? e.constructor : null;\n},\n instanceOf$1 = function (e, t) {\n return !!(e && t && e instanceof t);\n},\n isNullOrUndefined$1 = function (e) {\n return null == e;\n},\n isObject$1 = function (e) {\n return getConstructor$1(e) === Object;\n},\n isNumber$1 = function (e) {\n return getConstructor$1(e) === Number && !Number.isNaN(e);\n},\n isString$1 = function (e) {\n return getConstructor$1(e) === String;\n},\n isBoolean$1 = function (e) {\n return getConstructor$1(e) === Boolean;\n},\n isFunction$1 = function (e) {\n return getConstructor$1(e) === Function;\n},\n isArray$1 = function (e) {\n return Array.isArray(e);\n},\n isNodeList$1 = function (e) {\n return instanceOf$1(e, NodeList);\n},\n isElement$1 = function (e) {\n return instanceOf$1(e, Element);\n},\n isEvent$1 = function (e) {\n return instanceOf$1(e, Event);\n},\n isEmpty$1 = function (e) {\n return isNullOrUndefined$1(e) || (isString$1(e) || isArray$1(e) || isNodeList$1(e)) && !e.length || isObject$1(e) && !Object.keys(e).length;\n},\n is$1 = {\n nullOrUndefined: isNullOrUndefined$1,\n object: isObject$1,\n number: isNumber$1,\n string: isString$1,\n boolean: isBoolean$1,\n function: isFunction$1,\n array: isArray$1,\n nodeList: isNodeList$1,\n element: isElement$1,\n event: isEvent$1,\n empty: isEmpty$1\n};\n\nfunction getDecimalPlaces(e) {\n var t = \"\".concat(e).match(/(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/);\n return t ? Math.max(0, (t[1] ? t[1].length : 0) - (t[2] ? +t[2] : 0)) : 0;\n}\n\nfunction round(e, t) {\n if (1 > t) {\n var n = getDecimalPlaces(t);\n return parseFloat(e.toFixed(n));\n }\n\n return Math.round(e / t) * t;\n}\n\nvar RangeTouch = function () {\n function e(t, n) {\n _classCallCheck(this, e), is$1.element(t) ? this.element = t : is$1.string(t) && (this.element = document.querySelector(t)), is$1.element(this.element) && is$1.empty(this.element.rangeTouch) && (this.config = _objectSpread2({}, defaults$1, {}, n), this.init());\n }\n\n return _createClass(e, [{\n key: \"init\",\n value: function () {\n e.enabled && (this.config.addCSS && (this.element.style.userSelect = \"none\", this.element.style.webKitUserSelect = \"none\", this.element.style.touchAction = \"manipulation\"), this.listeners(!0), this.element.rangeTouch = this);\n }\n }, {\n key: \"destroy\",\n value: function () {\n e.enabled && (this.config.addCSS && (this.element.style.userSelect = \"\", this.element.style.webKitUserSelect = \"\", this.element.style.touchAction = \"\"), this.listeners(!1), this.element.rangeTouch = null);\n }\n }, {\n key: \"listeners\",\n value: function (e) {\n var t = this,\n n = e ? \"addEventListener\" : \"removeEventListener\";\n [\"touchstart\", \"touchmove\", \"touchend\"].forEach(function (e) {\n t.element[n](e, function (e) {\n return t.set(e);\n }, !1);\n });\n }\n }, {\n key: \"get\",\n value: function (t) {\n if (!e.enabled || !is$1.event(t)) return null;\n var n,\n r = t.target,\n i = t.changedTouches[0],\n o = parseFloat(r.getAttribute(\"min\")) || 0,\n s = parseFloat(r.getAttribute(\"max\")) || 100,\n u = parseFloat(r.getAttribute(\"step\")) || 1,\n c = r.getBoundingClientRect(),\n a = 100 / c.width * (this.config.thumbWidth / 2) / 100;\n return 0 > (n = 100 / c.width * (i.clientX - c.left)) ? n = 0 : 100 < n && (n = 100), 50 > n ? n -= (100 - 2 * n) * a : 50 < n && (n += 2 * (n - 50) * a), o + round(n / 100 * (s - o), u);\n }\n }, {\n key: \"set\",\n value: function (t) {\n e.enabled && is$1.event(t) && !t.target.disabled && (t.preventDefault(), t.target.value = this.get(t), trigger(t.target, \"touchend\" === t.type ? \"change\" : \"input\"));\n }\n }], [{\n key: \"setup\",\n value: function (t) {\n var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {},\n r = null;\n if (is$1.empty(t) || is$1.string(t) ? r = Array.from(document.querySelectorAll(is$1.string(t) ? t : 'input[type=\"range\"]')) : is$1.element(t) ? r = [t] : is$1.nodeList(t) ? r = Array.from(t) : is$1.array(t) && (r = t.filter(is$1.element)), is$1.empty(r)) return null;\n\n var i = _objectSpread2({}, defaults$1, {}, n);\n\n if (is$1.string(t) && i.watch) {\n var o = new MutationObserver(function (n) {\n Array.from(n).forEach(function (n) {\n Array.from(n.addedNodes).forEach(function (n) {\n is$1.element(n) && matches$1(n, t) && new e(n, i);\n });\n });\n });\n o.observe(document.body, {\n childList: !0,\n subtree: !0\n });\n }\n\n return r.map(function (t) {\n return new e(t, n);\n });\n }\n }, {\n key: \"enabled\",\n get: function () {\n return \"ontouchstart\" in document.documentElement;\n }\n }]), e;\n}();\n\n// ==========================================================================\n// Type checking utils\n// ==========================================================================\nconst getConstructor = input => input !== null && typeof input !== 'undefined' ? input.constructor : null;\n\nconst instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor);\n\nconst isNullOrUndefined = input => input === null || typeof input === 'undefined';\n\nconst isObject = input => getConstructor(input) === Object;\n\nconst isNumber = input => getConstructor(input) === Number && !Number.isNaN(input);\n\nconst isString = input => getConstructor(input) === String;\n\nconst isBoolean = input => getConstructor(input) === Boolean;\n\nconst isFunction = input => getConstructor(input) === Function;\n\nconst isArray = input => Array.isArray(input);\n\nconst isWeakMap = input => instanceOf(input, WeakMap);\n\nconst isNodeList = input => instanceOf(input, NodeList);\n\nconst isTextNode = input => getConstructor(input) === Text;\n\nconst isEvent = input => instanceOf(input, Event);\n\nconst isKeyboardEvent = input => instanceOf(input, KeyboardEvent);\n\nconst isCue = input => instanceOf(input, window.TextTrackCue) || instanceOf(input, window.VTTCue);\n\nconst isTrack = input => instanceOf(input, TextTrack) || !isNullOrUndefined(input) && isString(input.kind);\n\nconst isPromise = input => instanceOf(input, Promise) && isFunction(input.then);\n\nconst isElement = input => input !== null && typeof input === 'object' && input.nodeType === 1 && typeof input.style === 'object' && typeof input.ownerDocument === 'object';\n\nconst isEmpty = input => isNullOrUndefined(input) || (isString(input) || isArray(input) || isNodeList(input)) && !input.length || isObject(input) && !Object.keys(input).length;\n\nconst isUrl = input => {\n // Accept a URL object\n if (instanceOf(input, window.URL)) {\n return true;\n } // Must be string from here\n\n\n if (!isString(input)) {\n return false;\n } // Add the protocol if required\n\n\n let string = input;\n\n if (!input.startsWith('http://') || !input.startsWith('https://')) {\n string = `http://${input}`;\n }\n\n try {\n return !isEmpty(new URL(string).hostname);\n } catch (_) {\n return false;\n }\n};\n\nvar is = {\n nullOrUndefined: isNullOrUndefined,\n object: isObject,\n number: isNumber,\n string: isString,\n boolean: isBoolean,\n function: isFunction,\n array: isArray,\n weakMap: isWeakMap,\n nodeList: isNodeList,\n element: isElement,\n textNode: isTextNode,\n event: isEvent,\n keyboardEvent: isKeyboardEvent,\n cue: isCue,\n track: isTrack,\n promise: isPromise,\n url: isUrl,\n empty: isEmpty\n};\n\n// ==========================================================================\nconst transitionEndEvent = (() => {\n const element = document.createElement('span');\n const events = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend'\n };\n const type = Object.keys(events).find(event => element.style[event] !== undefined);\n return is.string(type) ? events[type] : false;\n})(); // Force repaint of element\n\nfunction repaint(element, delay) {\n setTimeout(() => {\n try {\n // eslint-disable-next-line no-param-reassign\n element.hidden = true; // eslint-disable-next-line no-unused-expressions\n\n element.offsetHeight; // eslint-disable-next-line no-param-reassign\n\n element.hidden = false;\n } catch (_) {// Do nothing\n }\n }, delay);\n}\n\n// ==========================================================================\n// Browser sniffing\n// Unfortunately, due to mixed support, UA sniffing is required\n// ==========================================================================\nconst browser = {\n isIE: Boolean(window.document.documentMode),\n isEdge: window.navigator.userAgent.includes('Edge'),\n isWebkit: 'WebkitAppearance' in document.documentElement.style && !/Edge/.test(navigator.userAgent),\n isIPhone: /(iPhone|iPod)/gi.test(navigator.platform),\n isIos: navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 || /(iPad|iPhone|iPod)/gi.test(navigator.platform)\n};\n\n// ==========================================================================\n\nfunction cloneDeep(object) {\n return JSON.parse(JSON.stringify(object));\n} // Get a nested value in an object\n\nfunction getDeep(object, path) {\n return path.split('.').reduce((obj, key) => obj && obj[key], object);\n} // Deep extend destination object with N more objects\n\nfunction extend(target = {}, ...sources) {\n if (!sources.length) {\n return target;\n }\n\n const source = sources.shift();\n\n if (!is.object(source)) {\n return target;\n }\n\n Object.keys(source).forEach(key => {\n if (is.object(source[key])) {\n if (!Object.keys(target).includes(key)) {\n Object.assign(target, {\n [key]: {}\n });\n }\n\n extend(target[key], source[key]);\n } else {\n Object.assign(target, {\n [key]: source[key]\n });\n }\n });\n return extend(target, ...sources);\n}\n\n// ==========================================================================\n\nfunction wrap(elements, wrapper) {\n // Convert `elements` to an array, if necessary.\n const targets = elements.length ? elements : [elements]; // Loops backwards to prevent having to clone the wrapper on the\n // first element (see `child` below).\n\n Array.from(targets).reverse().forEach((element, index) => {\n const child = index > 0 ? wrapper.cloneNode(true) : wrapper; // Cache the current parent and sibling.\n\n const parent = element.parentNode;\n const sibling = element.nextSibling; // Wrap the element (is automatically removed from its current\n // parent).\n\n child.appendChild(element); // If the element had a sibling, insert the wrapper before\n // the sibling to maintain the HTML structure; otherwise, just\n // append it to the parent.\n\n if (sibling) {\n parent.insertBefore(child, sibling);\n } else {\n parent.appendChild(child);\n }\n });\n} // Set attributes\n\nfunction setAttributes(element, attributes) {\n if (!is.element(element) || is.empty(attributes)) {\n return;\n } // Assume null and undefined attributes should be left out,\n // Setting them would otherwise convert them to \"null\" and \"undefined\"\n\n\n Object.entries(attributes).filter(([, value]) => !is.nullOrUndefined(value)).forEach(([key, value]) => element.setAttribute(key, value));\n} // Create a DocumentFragment\n\nfunction createElement(type, attributes, text) {\n // Create a new <element>\n const element = document.createElement(type); // Set all passed attributes\n\n if (is.object(attributes)) {\n setAttributes(element, attributes);\n } // Add text node\n\n\n if (is.string(text)) {\n element.innerText = text;\n } // Return built element\n\n\n return element;\n} // Inaert an element after another\n\nfunction insertAfter(element, target) {\n if (!is.element(element) || !is.element(target)) {\n return;\n }\n\n target.parentNode.insertBefore(element, target.nextSibling);\n} // Insert a DocumentFragment\n\nfunction insertElement(type, parent, attributes, text) {\n if (!is.element(parent)) {\n return;\n }\n\n parent.appendChild(createElement(type, attributes, text));\n} // Remove element(s)\n\nfunction removeElement(element) {\n if (is.nodeList(element) || is.array(element)) {\n Array.from(element).forEach(removeElement);\n return;\n }\n\n if (!is.element(element) || !is.element(element.parentNode)) {\n return;\n }\n\n element.parentNode.removeChild(element);\n} // Remove all child elements\n\nfunction emptyElement(element) {\n if (!is.element(element)) {\n return;\n }\n\n let {\n length\n } = element.childNodes;\n\n while (length > 0) {\n element.removeChild(element.lastChild);\n length -= 1;\n }\n} // Replace element\n\nfunction replaceElement(newChild, oldChild) {\n if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) {\n return null;\n }\n\n oldChild.parentNode.replaceChild(newChild, oldChild);\n return newChild;\n} // Get an attribute object from a string selector\n\nfunction getAttributesFromSelector(sel, existingAttributes) {\n // For example:\n // '.test' to { class: 'test' }\n // '#test' to { id: 'test' }\n // '[data-test=\"test\"]' to { 'data-test': 'test' }\n if (!is.string(sel) || is.empty(sel)) {\n return {};\n }\n\n const attributes = {};\n const existing = extend({}, existingAttributes);\n sel.split(',').forEach(s => {\n // Remove whitespace\n const selector = s.trim();\n const className = selector.replace('.', '');\n const stripped = selector.replace(/[[\\]]/g, ''); // Get the parts and value\n\n const parts = stripped.split('=');\n const [key] = parts;\n const value = parts.length > 1 ? parts[1].replace(/[\"']/g, '') : ''; // Get the first character\n\n const start = selector.charAt(0);\n\n switch (start) {\n case '.':\n // Add to existing classname\n if (is.string(existing.class)) {\n attributes.class = `${existing.class} ${className}`;\n } else {\n attributes.class = className;\n }\n\n break;\n\n case '#':\n // ID selector\n attributes.id = selector.replace('#', '');\n break;\n\n case '[':\n // Attribute selector\n attributes[key] = value;\n break;\n }\n });\n return extend(existing, attributes);\n} // Toggle hidden\n\nfunction toggleHidden(element, hidden) {\n if (!is.element(element)) {\n return;\n }\n\n let hide = hidden;\n\n if (!is.boolean(hide)) {\n hide = !element.hidden;\n } // eslint-disable-next-line no-param-reassign\n\n\n element.hidden = hide;\n} // Mirror Element.classList.toggle, with IE compatibility for \"force\" argument\n\nfunction toggleClass(element, className, force) {\n if (is.nodeList(element)) {\n return Array.from(element).map(e => toggleClass(e, className, force));\n }\n\n if (is.element(element)) {\n let method = 'toggle';\n\n if (typeof force !== 'undefined') {\n method = force ? 'add' : 'remove';\n }\n\n element.classList[method](className);\n return element.classList.contains(className);\n }\n\n return false;\n} // Has class name\n\nfunction hasClass(element, className) {\n return is.element(element) && element.classList.contains(className);\n} // Element matches selector\n\nfunction matches(element, selector) {\n const {\n prototype\n } = Element;\n\n function match() {\n return Array.from(document.querySelectorAll(selector)).includes(this);\n }\n\n const method = prototype.matches || prototype.webkitMatchesSelector || prototype.mozMatchesSelector || prototype.msMatchesSelector || match;\n return method.call(element, selector);\n} // Closest ancestor element matching selector (also tests element itself)\n\nfunction closest$1(element, selector) {\n const {\n prototype\n } = Element; // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill\n\n function closestElement() {\n let el = this;\n\n do {\n if (matches.matches(el, selector)) return el;\n el = el.parentElement || el.parentNode;\n } while (el !== null && el.nodeType === 1);\n\n return null;\n }\n\n const method = prototype.closest || closestElement;\n return method.call(element, selector);\n} // Find all elements\n\nfunction getElements(selector) {\n return this.elements.container.querySelectorAll(selector);\n} // Find a single element\n\nfunction getElement(selector) {\n return this.elements.container.querySelector(selector);\n} // Set focus and tab focus class\n\nfunction setFocus(element = null, tabFocus = false) {\n if (!is.element(element)) {\n return;\n } // Set regular focus\n\n\n element.focus({\n preventScroll: true\n }); // If we want to mimic keyboard focus via tab\n\n if (tabFocus) {\n toggleClass(element, this.config.classNames.tabFocus);\n }\n}\n\n// ==========================================================================\n\nconst defaultCodecs = {\n 'audio/ogg': 'vorbis',\n 'audio/wav': '1',\n 'video/webm': 'vp8, vorbis',\n 'video/mp4': 'avc1.42E01E, mp4a.40.2',\n 'video/ogg': 'theora'\n}; // Check for feature support\n\nconst support = {\n // Basic support\n audio: 'canPlayType' in document.createElement('audio'),\n video: 'canPlayType' in document.createElement('video'),\n\n // Check for support\n // Basic functionality vs full UI\n check(type, provider, playsinline) {\n const canPlayInline = browser.isIPhone && playsinline && support.playsinline;\n const api = support[type] || provider !== 'html5';\n const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline);\n return {\n api,\n ui\n };\n },\n\n // Picture-in-picture support\n // Safari & Chrome only currently\n pip: (() => {\n if (browser.isIPhone) {\n return false;\n } // Safari\n // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls\n\n\n if (is.function(createElement('video').webkitSetPresentationMode)) {\n return true;\n } // Chrome\n // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture\n\n\n if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) {\n return true;\n }\n\n return false;\n })(),\n // Airplay support\n // Safari only currently\n airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent),\n // Inline playback support\n // https://webkit.org/blog/6784/new-video-policies-for-ios/\n playsinline: 'playsInline' in document.createElement('video'),\n\n // Check for mime type support against a player instance\n // Credits: http://diveintohtml5.info/everything.html\n // Related: http://www.leanbackplayer.com/test/h5mt.html\n mime(input) {\n if (is.empty(input)) {\n return false;\n }\n\n const [mediaType] = input.split('/');\n let type = input; // Verify we're using HTML5 and there's no media type mismatch\n\n if (!this.isHTML5 || mediaType !== this.type) {\n return false;\n } // Add codec if required\n\n\n if (Object.keys(defaultCodecs).includes(type)) {\n type += `; codecs=\"${defaultCodecs[input]}\"`;\n }\n\n try {\n return Boolean(type && this.media.canPlayType(type).replace(/no/, ''));\n } catch (_) {\n return false;\n }\n },\n\n // Check for textTracks support\n textTracks: 'textTracks' in document.createElement('video'),\n // <input type=\"range\"> Sliders\n rangeInput: (() => {\n const range = document.createElement('input');\n range.type = 'range';\n return range.type === 'range';\n })(),\n // Touch\n // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event\n touch: 'ontouchstart' in document.documentElement,\n // Detect transitions support\n transitions: transitionEndEvent !== false,\n // Reduced motion iOS & MacOS setting\n // https://webkit.org/blog/7551/responsive-design-for-motion/\n reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches\n};\n\n// ==========================================================================\n// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md\n// https://www.youtube.com/watch?v=NPM6172J22g\n\nconst supportsPassiveListeners = (() => {\n // Test via a getter in the options object to see if the passive property is accessed\n let supported = false;\n\n try {\n const options = Object.defineProperty({}, 'passive', {\n get() {\n supported = true;\n return null;\n }\n\n });\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n } catch (_) {// Do nothing\n }\n\n return supported;\n})(); // Toggle event listener\n\n\nfunction toggleListener(element, event, callback, toggle = false, passive = true, capture = false) {\n // Bail if no element, event, or callback\n if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) {\n return;\n } // Allow multiple events\n\n\n const events = event.split(' '); // Build options\n // Default to just the capture boolean for browsers with no passive listener support\n\n let options = capture; // If passive events listeners are supported\n\n if (supportsPassiveListeners) {\n options = {\n // Whether the listener can be passive (i.e. default never prevented)\n passive,\n // Whether the listener is a capturing listener or not\n capture\n };\n } // If a single node is passed, bind the event listener\n\n\n events.forEach(type => {\n if (this && this.eventListeners && toggle) {\n // Cache event listener\n this.eventListeners.push({\n element,\n type,\n callback,\n options\n });\n }\n\n element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options);\n });\n} // Bind event handler\n\nfunction on(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, true, passive, capture);\n} // Unbind event handler\n\nfunction off(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, false, passive, capture);\n} // Bind once-only event handler\n\nfunction once(element, events = '', callback, passive = true, capture = false) {\n const onceCallback = (...args) => {\n off(element, events, onceCallback, passive, capture);\n callback.apply(this, args);\n };\n\n toggleListener.call(this, element, events, onceCallback, true, passive, capture);\n} // Trigger event\n\nfunction triggerEvent(element, type = '', bubbles = false, detail = {}) {\n // Bail if no element\n if (!is.element(element) || is.empty(type)) {\n return;\n } // Create and dispatch the event\n\n\n const event = new CustomEvent(type, {\n bubbles,\n detail: { ...detail,\n plyr: this\n }\n }); // Dispatch the event\n\n element.dispatchEvent(event);\n} // Unbind all cached event listeners\n\nfunction unbindListeners() {\n if (this && this.eventListeners) {\n this.eventListeners.forEach(item => {\n const {\n element,\n type,\n callback,\n options\n } = item;\n element.removeEventListener(type, callback, options);\n });\n this.eventListeners = [];\n }\n} // Run method when / if player is ready\n\nfunction ready() {\n return new Promise(resolve => this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve)).then(() => {});\n}\n\n/**\n * Silence a Promise-like object.\n * This is useful for avoiding non-harmful, but potentially confusing \"uncaught\n * play promise\" rejection error messages.\n * @param {Object} value An object that may or may not be `Promise`-like.\n */\n\nfunction silencePromise(value) {\n if (is.promise(value)) {\n value.then(null, () => {});\n }\n}\n\n// ==========================================================================\n\nfunction dedupe(array) {\n if (!is.array(array)) {\n return array;\n }\n\n return array.filter((item, index) => array.indexOf(item) === index);\n} // Get the closest value in an array\n\nfunction closest(array, value) {\n if (!is.array(array) || !array.length) {\n return null;\n }\n\n return array.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev);\n}\n\n// ==========================================================================\n\nfunction supportsCSS(declaration) {\n if (!window || !window.CSS) {\n return false;\n }\n\n return window.CSS.supports(declaration);\n} // Standard/common aspect ratios\n\nconst standardRatios = [[1, 1], [4, 3], [3, 4], [5, 4], [4, 5], [3, 2], [2, 3], [16, 10], [10, 16], [16, 9], [9, 16], [21, 9], [9, 21], [32, 9], [9, 32]].reduce((out, [x, y]) => ({ ...out,\n [x / y]: [x, y]\n}), {}); // Validate an aspect ratio\n\nfunction validateAspectRatio(input) {\n if (!is.array(input) && (!is.string(input) || !input.includes(':'))) {\n return false;\n }\n\n const ratio = is.array(input) ? input : input.split(':');\n return ratio.map(Number).every(is.number);\n} // Reduce an aspect ratio to it's lowest form\n\nfunction reduceAspectRatio(ratio) {\n if (!is.array(ratio) || !ratio.every(is.number)) {\n return null;\n }\n\n const [width, height] = ratio;\n\n const getDivider = (w, h) => h === 0 ? w : getDivider(h, w % h);\n\n const divider = getDivider(width, height);\n return [width / divider, height / divider];\n} // Calculate an aspect ratio\n\nfunction getAspectRatio(input) {\n const parse = ratio => validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null; // Try provided ratio\n\n\n let ratio = parse(input); // Get from config\n\n if (ratio === null) {\n ratio = parse(this.config.ratio);\n } // Get from embed\n\n\n if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) {\n ({\n ratio\n } = this.embed);\n } // Get from HTML5 video\n\n\n if (ratio === null && this.isHTML5) {\n const {\n videoWidth,\n videoHeight\n } = this.media;\n ratio = [videoWidth, videoHeight];\n }\n\n return reduceAspectRatio(ratio);\n} // Set aspect ratio for responsive container\n\nfunction setAspectRatio(input) {\n if (!this.isVideo) {\n return {};\n }\n\n const {\n wrapper\n } = this.elements;\n const ratio = getAspectRatio.call(this, input);\n\n if (!is.array(ratio)) {\n return {};\n }\n\n const [x, y] = reduceAspectRatio(ratio);\n const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`);\n const padding = 100 / x * y;\n\n if (useNative) {\n wrapper.style.aspectRatio = `${x}/${y}`;\n } else {\n wrapper.style.paddingBottom = `${padding}%`;\n } // For Vimeo we have an extra <div> to hide the standard controls and UI\n\n\n if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) {\n const height = 100 / this.media.offsetWidth * parseInt(window.getComputedStyle(this.media).paddingBottom, 10);\n const offset = (height - padding) / (height / 50);\n\n if (this.fullscreen.active) {\n wrapper.style.paddingBottom = null;\n } else {\n this.media.style.transform = `translateY(-${offset}%)`;\n }\n } else if (this.isHTML5) {\n wrapper.classList.add(this.config.classNames.videoFixedRatio);\n }\n\n return {\n padding,\n ratio\n };\n} // Round an aspect ratio to closest standard ratio\n\nfunction roundAspectRatio(x, y, tolerance = 0.05) {\n const ratio = x / y;\n const closestRatio = closest(Object.keys(standardRatios), ratio); // Check match is within tolerance\n\n if (Math.abs(closestRatio - ratio) <= tolerance) {\n return standardRatios[closestRatio];\n } // No match\n\n\n return [x, y];\n} // Get the size of the viewport\n// https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions\n\nfunction getViewportSize() {\n const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);\n const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);\n return [width, height];\n}\n\n// ==========================================================================\nconst html5 = {\n getSources() {\n if (!this.isHTML5) {\n return [];\n }\n\n const sources = Array.from(this.media.querySelectorAll('source')); // Filter out unsupported sources (if type is specified)\n\n return sources.filter(source => {\n const type = source.getAttribute('type');\n\n if (is.empty(type)) {\n return true;\n }\n\n return support.mime.call(this, type);\n });\n },\n\n // Get quality levels\n getQualityOptions() {\n // Whether we're forcing all options (e.g. for streaming)\n if (this.config.quality.forced) {\n return this.config.quality.options;\n } // Get sizes from <source> elements\n\n\n return html5.getSources.call(this).map(source => Number(source.getAttribute('data-res'))).filter(Boolean);\n },\n\n setup() {\n if (!this.isHTML5) {\n return;\n }\n\n const player = this; // Set speed options from config\n\n player.options.speed = player.config.speed.options; // Set aspect ratio if fixed\n\n if (!is.empty(this.config.ratio)) {\n setAspectRatio.call(player);\n } // Quality\n\n\n Object.defineProperty(player.media, 'quality', {\n get() {\n // Get sources\n const sources = html5.getSources.call(player);\n const source = sources.find(s => s.getAttribute('src') === player.source); // Return size, if match is found\n\n return source && Number(source.getAttribute('data-res'));\n },\n\n set(input) {\n if (player.quality === input) {\n return;\n } // If we're using an external handler...\n\n\n if (player.config.quality.forced && is.function(player.config.quality.onChange)) {\n player.config.quality.onChange(input);\n } else {\n // Get sources\n const sources = html5.getSources.call(player); // Get first match for requested size\n\n const source = sources.find(s => Number(s.getAttribute('data-res')) === input); // No matching source found\n\n if (!source) {\n return;\n } // Get current state\n\n\n const {\n currentTime,\n paused,\n preload,\n readyState,\n playbackRate\n } = player.media; // Set new source\n\n player.media.src = source.getAttribute('src'); // Prevent loading if preload=\"none\" and the current source isn't loaded (#1044)\n\n if (preload !== 'none' || readyState) {\n // Restore time\n player.once('loadedmetadata', () => {\n player.speed = playbackRate;\n player.currentTime = currentTime; // Resume playing\n\n if (!paused) {\n silencePromise(player.play());\n }\n }); // Load new source\n\n player.media.load();\n }\n } // Trigger change event\n\n\n triggerEvent.call(player, player.media, 'qualitychange', false, {\n quality: input\n });\n }\n\n });\n },\n\n // Cancel current network requests\n // See https://github.com/sampotts/plyr/issues/174\n cancelRequests() {\n if (!this.isHTML5) {\n return;\n } // Remove child sources\n\n\n removeElement(html5.getSources.call(this)); // Set blank video src attribute\n // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error\n // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection\n\n this.media.setAttribute('src', this.config.blankVideo); // Load the new empty source\n // This will cancel existing requests\n // See https://github.com/sampotts/plyr/issues/174\n\n this.media.load(); // Debugging\n\n this.debug.log('Cancelled network requests');\n }\n\n};\n\n// ==========================================================================\n\nfunction generateId(prefix) {\n return `${prefix}-${Math.floor(Math.random() * 10000)}`;\n} // Format string\n\nfunction format(input, ...args) {\n if (is.empty(input)) {\n return input;\n }\n\n return input.toString().replace(/{(\\d+)}/g, (match, i) => args[i].toString());\n} // Get percentage\n\nfunction getPercentage(current, max) {\n if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) {\n return 0;\n }\n\n return (current / max * 100).toFixed(2);\n} // Replace all occurances of a string in a string\n\nconst replaceAll = (input = '', find = '', replace = '') => input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\\]/\\\\])/g, '\\\\$1'), 'g'), replace.toString()); // Convert to title case\n\nconst toTitleCase = (input = '') => input.toString().replace(/\\w\\S*/g, text => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()); // Convert string to pascalCase\n\nfunction toPascalCase(input = '') {\n let string = input.toString(); // Convert kebab case\n\n string = replaceAll(string, '-', ' '); // Convert snake case\n\n string = replaceAll(string, '_', ' '); // Convert to title case\n\n string = toTitleCase(string); // Convert to pascal case\n\n return replaceAll(string, ' ', '');\n} // Convert string to pascalCase\n\nfunction toCamelCase(input = '') {\n let string = input.toString(); // Convert to pascal case\n\n string = toPascalCase(string); // Convert first character to lowercase\n\n return string.charAt(0).toLowerCase() + string.slice(1);\n} // Remove HTML from a string\n\nfunction stripHTML(source) {\n const fragment = document.createDocumentFragment();\n const element = document.createElement('div');\n fragment.appendChild(element);\n element.innerHTML = source;\n return fragment.firstChild.innerText;\n} // Like outerHTML, but also works for DocumentFragment\n\nfunction getHTML(element) {\n const wrapper = document.createElement('div');\n wrapper.appendChild(element);\n return wrapper.innerHTML;\n}\n\n// ==========================================================================\n\nconst resources = {\n pip: 'PIP',\n airplay: 'AirPlay',\n html5: 'HTML5',\n vimeo: 'Vimeo',\n youtube: 'YouTube'\n};\nconst i18n = {\n get(key = '', config = {}) {\n if (is.empty(key) || is.empty(config)) {\n return '';\n }\n\n let string = getDeep(config.i18n, key);\n\n if (is.empty(string)) {\n if (Object.keys(resources).includes(key)) {\n return resources[key];\n }\n\n return '';\n }\n\n const replace = {\n '{seektime}': config.seekTime,\n '{title}': config.title\n };\n Object.entries(replace).forEach(([k, v]) => {\n string = replaceAll(string, k, v);\n });\n return string;\n }\n\n};\n\nclass Storage {\n constructor(player) {\n _defineProperty$1(this, \"get\", key => {\n if (!Storage.supported || !this.enabled) {\n return null;\n }\n\n const store = window.localStorage.getItem(this.key);\n\n if (is.empty(store)) {\n return null;\n }\n\n const json = JSON.parse(store);\n return is.string(key) && key.length ? json[key] : json;\n });\n\n _defineProperty$1(this, \"set\", object => {\n // Bail if we don't have localStorage support or it's disabled\n if (!Storage.supported || !this.enabled) {\n return;\n } // Can only store objectst\n\n\n if (!is.object(object)) {\n return;\n } // Get current storage\n\n\n let storage = this.get(); // Default to empty object\n\n if (is.empty(storage)) {\n storage = {};\n } // Update the working copy of the values\n\n\n extend(storage, object); // Update storage\n\n try {\n window.localStorage.setItem(this.key, JSON.stringify(storage));\n } catch (_) {// Do nothing\n }\n });\n\n this.enabled = player.config.storage.enabled;\n this.key = player.config.storage.key;\n } // Check for actual support (see if we can use it)\n\n\n static get supported() {\n try {\n if (!('localStorage' in window)) {\n return false;\n }\n\n const test = '___test'; // Try to use it (it might be disabled, e.g. user is in private mode)\n // see: https://github.com/sampotts/plyr/issues/131\n\n window.localStorage.setItem(test, test);\n window.localStorage.removeItem(test);\n return true;\n } catch (_) {\n return false;\n }\n }\n\n}\n\n// ==========================================================================\n// Fetch wrapper\n// Using XHR to avoid issues with older browsers\n// ==========================================================================\nfunction fetch(url, responseType = 'text') {\n return new Promise((resolve, reject) => {\n try {\n const request = new XMLHttpRequest(); // Check for CORS support\n\n if (!('withCredentials' in request)) {\n return;\n }\n\n request.addEventListener('load', () => {\n if (responseType === 'text') {\n try {\n resolve(JSON.parse(request.responseText));\n } catch (_) {\n resolve(request.responseText);\n }\n } else {\n resolve(request.response);\n }\n });\n request.addEventListener('error', () => {\n throw new Error(request.status);\n });\n request.open('GET', url, true); // Set the required response type\n\n request.responseType = responseType;\n request.send();\n } catch (error) {\n reject(error);\n }\n });\n}\n\n// ==========================================================================\n\nfunction loadSprite(url, id) {\n if (!is.string(url)) {\n return;\n }\n\n const prefix = 'cache';\n const hasId = is.string(id);\n let isCached = false;\n\n const exists = () => document.getElementById(id) !== null;\n\n const update = (container, data) => {\n // eslint-disable-next-line no-param-reassign\n container.innerHTML = data; // Check again incase of race condition\n\n if (hasId && exists()) {\n return;\n } // Inject the SVG to the body\n\n\n document.body.insertAdjacentElement('afterbegin', container);\n }; // Only load once if ID set\n\n\n if (!hasId || !exists()) {\n const useStorage = Storage.supported; // Create container\n\n const container = document.createElement('div');\n container.setAttribute('hidden', '');\n\n if (hasId) {\n container.setAttribute('id', id);\n } // Check in cache\n\n\n if (useStorage) {\n const cached = window.localStorage.getItem(`${prefix}-${id}`);\n isCached = cached !== null;\n\n if (isCached) {\n const data = JSON.parse(cached);\n update(container, data.content);\n }\n } // Get the sprite\n\n\n fetch(url).then(result => {\n if (is.empty(result)) {\n return;\n }\n\n if (useStorage) {\n try {\n window.localStorage.setItem(`${prefix}-${id}`, JSON.stringify({\n content: result\n }));\n } catch (_) {// Do nothing\n }\n }\n\n update(container, result);\n }).catch(() => {});\n }\n}\n\n// ==========================================================================\n\nconst getHours = value => Math.trunc(value / 60 / 60 % 60, 10);\nconst getMinutes = value => Math.trunc(value / 60 % 60, 10);\nconst getSeconds = value => Math.trunc(value % 60, 10); // Format time to UI friendly string\n\nfunction formatTime(time = 0, displayHours = false, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return formatTime(undefined, displayHours, inverted);\n } // Format time component to add leading zero\n\n\n const format = value => `0${value}`.slice(-2); // Breakdown to hours, mins, secs\n\n\n let hours = getHours(time);\n const mins = getMinutes(time);\n const secs = getSeconds(time); // Do we need to display hours?\n\n if (displayHours || hours > 0) {\n hours = `${hours}:`;\n } else {\n hours = '';\n } // Render\n\n\n return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`;\n}\n\n// ==========================================================================\n\nconst controls = {\n // Get icon URL\n getIconUrl() {\n const url = new URL(this.config.iconUrl, window.location);\n const host = window.location.host ? window.location.host : window.top.location.host;\n const cors = url.host !== host || browser.isIE && !window.svg4everybody;\n return {\n url: this.config.iconUrl,\n cors\n };\n },\n\n // Find the UI controls\n findElements() {\n try {\n this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper); // Buttons\n\n this.elements.buttons = {\n play: getElements.call(this, this.config.selectors.buttons.play),\n pause: getElement.call(this, this.config.selectors.buttons.pause),\n restart: getElement.call(this, this.config.selectors.buttons.restart),\n rewind: getElement.call(this, this.config.selectors.buttons.rewind),\n fastForward: getElement.call(this, this.config.selectors.buttons.fastForward),\n mute: getElement.call(this, this.config.selectors.buttons.mute),\n pip: getElement.call(this, this.config.selectors.buttons.pip),\n airplay: getElement.call(this, this.config.selectors.buttons.airplay),\n settings: getElement.call(this, this.config.selectors.buttons.settings),\n captions: getElement.call(this, this.config.selectors.buttons.captions),\n fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen)\n }; // Progress\n\n this.elements.progress = getElement.call(this, this.config.selectors.progress); // Inputs\n\n this.elements.inputs = {\n seek: getElement.call(this, this.config.selectors.inputs.seek),\n volume: getElement.call(this, this.config.selectors.inputs.volume)\n }; // Display\n\n this.elements.display = {\n buffer: getElement.call(this, this.config.selectors.display.buffer),\n currentTime: getElement.call(this, this.config.selectors.display.currentTime),\n duration: getElement.call(this, this.config.selectors.display.duration)\n }; // Seek tooltip\n\n if (is.element(this.elements.progress)) {\n this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`);\n }\n\n return true;\n } catch (error) {\n // Log it\n this.debug.warn('It looks like there is a problem with your custom controls HTML', error); // Restore native video controls\n\n this.toggleNativeControls(true);\n return false;\n }\n },\n\n // Create <svg> icon\n createIcon(type, attributes) {\n const namespace = 'http://www.w3.org/2000/svg';\n const iconUrl = controls.getIconUrl.call(this);\n const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`; // Create <svg>\n\n const icon = document.createElementNS(namespace, 'svg');\n setAttributes(icon, extend(attributes, {\n 'aria-hidden': 'true',\n focusable: 'false'\n })); // Create the <use> to reference sprite\n\n const use = document.createElementNS(namespace, 'use');\n const path = `${iconPath}-${type}`; // Set `href` attributes\n // https://github.com/sampotts/plyr/issues/460\n // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href\n\n if ('href' in use) {\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path);\n } // Always set the older attribute even though it's \"deprecated\" (it'll be around for ages)\n\n\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path); // Add <use> to <svg>\n\n icon.appendChild(use);\n return icon;\n },\n\n // Create hidden text label\n createLabel(key, attr = {}) {\n const text = i18n.get(key, this.config);\n const attributes = { ...attr,\n class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ')\n };\n return createElement('span', attributes, text);\n },\n\n // Create a badge\n createBadge(text) {\n if (is.empty(text)) {\n return null;\n }\n\n const badge = createElement('span', {\n class: this.config.classNames.menu.value\n });\n badge.appendChild(createElement('span', {\n class: this.config.classNames.menu.badge\n }, text));\n return badge;\n },\n\n // Create a <button>\n createButton(buttonType, attr) {\n const attributes = extend({}, attr);\n let type = toCamelCase(buttonType);\n const props = {\n element: 'button',\n toggle: false,\n label: null,\n icon: null,\n labelPressed: null,\n iconPressed: null\n };\n ['element', 'icon', 'label'].forEach(key => {\n if (Object.keys(attributes).includes(key)) {\n props[key] = attributes[key];\n delete attributes[key];\n }\n }); // Default to 'button' type to prevent form submission\n\n if (props.element === 'button' && !Object.keys(attributes).includes('type')) {\n attributes.type = 'button';\n } // Set class name\n\n\n if (Object.keys(attributes).includes('class')) {\n if (!attributes.class.split(' ').some(c => c === this.config.classNames.control)) {\n extend(attributes, {\n class: `${attributes.class} ${this.config.classNames.control}`\n });\n }\n } else {\n attributes.class = this.config.classNames.control;\n } // Large play button\n\n\n switch (buttonType) {\n case 'play':\n props.toggle = true;\n props.label = 'play';\n props.labelPressed = 'pause';\n props.icon = 'play';\n props.iconPressed = 'pause';\n break;\n\n case 'mute':\n props.toggle = true;\n props.label = 'mute';\n props.labelPressed = 'unmute';\n props.icon = 'volume';\n props.iconPressed = 'muted';\n break;\n\n case 'captions':\n props.toggle = true;\n props.label = 'enableCaptions';\n props.labelPressed = 'disableCaptions';\n props.icon = 'captions-off';\n props.iconPressed = 'captions-on';\n break;\n\n case 'fullscreen':\n props.toggle = true;\n props.label = 'enterFullscreen';\n props.labelPressed = 'exitFullscreen';\n props.icon = 'enter-fullscreen';\n props.iconPressed = 'exit-fullscreen';\n break;\n\n case 'play-large':\n attributes.class += ` ${this.config.classNames.control}--overlaid`;\n type = 'play';\n props.label = 'play';\n props.icon = 'play';\n break;\n\n default:\n if (is.empty(props.label)) {\n props.label = type;\n }\n\n if (is.empty(props.icon)) {\n props.icon = buttonType;\n }\n\n }\n\n const button = createElement(props.element); // Setup toggle icon and labels\n\n if (props.toggle) {\n // Icon\n button.appendChild(controls.createIcon.call(this, props.iconPressed, {\n class: 'icon--pressed'\n }));\n button.appendChild(controls.createIcon.call(this, props.icon, {\n class: 'icon--not-pressed'\n })); // Label/Tooltip\n\n button.appendChild(controls.createLabel.call(this, props.labelPressed, {\n class: 'label--pressed'\n }));\n button.appendChild(controls.createLabel.call(this, props.label, {\n class: 'label--not-pressed'\n }));\n } else {\n button.appendChild(controls.createIcon.call(this, props.icon));\n button.appendChild(controls.createLabel.call(this, props.label));\n } // Merge and set attributes\n\n\n extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes));\n setAttributes(button, attributes); // We have multiple play buttons\n\n if (type === 'play') {\n if (!is.array(this.elements.buttons[type])) {\n this.elements.buttons[type] = [];\n }\n\n this.elements.buttons[type].push(button);\n } else {\n this.elements.buttons[type] = button;\n }\n\n return button;\n },\n\n // Create an <input type='range'>\n createRange(type, attributes) {\n // Seek input\n const input = createElement('input', extend(getAttributesFromSelector(this.config.selectors.inputs[type]), {\n type: 'range',\n min: 0,\n max: 100,\n step: 0.01,\n value: 0,\n autocomplete: 'off',\n // A11y fixes for https://github.com/sampotts/plyr/issues/905\n role: 'slider',\n 'aria-label': i18n.get(type, this.config),\n 'aria-valuemin': 0,\n 'aria-valuemax': 100,\n 'aria-valuenow': 0\n }, attributes));\n this.elements.inputs[type] = input; // Set the fill for webkit now\n\n controls.updateRangeFill.call(this, input); // Improve support on touch devices\n\n RangeTouch.setup(input);\n return input;\n },\n\n // Create a <progress>\n createProgress(type, attributes) {\n const progress = createElement('progress', extend(getAttributesFromSelector(this.config.selectors.display[type]), {\n min: 0,\n max: 100,\n value: 0,\n role: 'progressbar',\n 'aria-hidden': true\n }, attributes)); // Create the label inside\n\n if (type !== 'volume') {\n progress.appendChild(createElement('span', null, '0'));\n const suffixKey = {\n played: 'played',\n buffer: 'buffered'\n }[type];\n const suffix = suffixKey ? i18n.get(suffixKey, this.config) : '';\n progress.innerText = `% ${suffix.toLowerCase()}`;\n }\n\n this.elements.display[type] = progress;\n return progress;\n },\n\n // Create time display\n createTime(type, attrs) {\n const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs);\n const container = createElement('div', extend(attributes, {\n class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(),\n 'aria-label': i18n.get(type, this.config)\n }), '00:00'); // Reference for updates\n\n this.elements.display[type] = container;\n return container;\n },\n\n // Bind keyboard shortcuts for a menu item\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n bindMenuItemShortcuts(menuItem, type) {\n // Navigate through menus via arrow keys and space\n on.call(this, menuItem, 'keydown keyup', event => {\n // We only care about space and ⬆️ ⬇️️ ➡️\n if (![32, 38, 39, 40].includes(event.which)) {\n return;\n } // Prevent play / seek\n\n\n event.preventDefault();\n event.stopPropagation(); // We're just here to prevent the keydown bubbling\n\n if (event.type === 'keydown') {\n return;\n }\n\n const isRadioButton = matches(menuItem, '[role=\"menuitemradio\"]'); // Show the respective menu\n\n if (!isRadioButton && [32, 39].includes(event.which)) {\n controls.showMenuPanel.call(this, type, true);\n } else {\n let target;\n\n if (event.which !== 32) {\n if (event.which === 40 || isRadioButton && event.which === 39) {\n target = menuItem.nextElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.firstElementChild;\n }\n } else {\n target = menuItem.previousElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.lastElementChild;\n }\n }\n\n setFocus.call(this, target, true);\n }\n }\n }, false); // Enter will fire a `click` event but we still need to manage focus\n // So we bind to keyup which fires after and set focus here\n\n on.call(this, menuItem, 'keyup', event => {\n if (event.which !== 13) {\n return;\n }\n\n controls.focusFirstMenuItem.call(this, null, true);\n });\n },\n\n // Create a settings menu item\n createMenuItem({\n value,\n list,\n type,\n title,\n badge = null,\n checked = false\n }) {\n const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]);\n const menuItem = createElement('button', extend(attributes, {\n type: 'button',\n role: 'menuitemradio',\n class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(),\n 'aria-checked': checked,\n value\n }));\n const flex = createElement('span'); // We have to set as HTML incase of special characters\n\n flex.innerHTML = title;\n\n if (is.element(badge)) {\n flex.appendChild(badge);\n }\n\n menuItem.appendChild(flex); // Replicate radio button behaviour\n\n Object.defineProperty(menuItem, 'checked', {\n enumerable: true,\n\n get() {\n return menuItem.getAttribute('aria-checked') === 'true';\n },\n\n set(check) {\n // Ensure exclusivity\n if (check) {\n Array.from(menuItem.parentNode.children).filter(node => matches(node, '[role=\"menuitemradio\"]')).forEach(node => node.setAttribute('aria-checked', 'false'));\n }\n\n menuItem.setAttribute('aria-checked', check ? 'true' : 'false');\n }\n\n });\n this.listeners.bind(menuItem, 'click keyup', event => {\n if (is.keyboardEvent(event) && event.which !== 32) {\n return;\n }\n\n event.preventDefault();\n event.stopPropagation();\n menuItem.checked = true;\n\n switch (type) {\n case 'language':\n this.currentTrack = Number(value);\n break;\n\n case 'quality':\n this.quality = value;\n break;\n\n case 'speed':\n this.speed = parseFloat(value);\n break;\n }\n\n controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event));\n }, type, false);\n controls.bindMenuItemShortcuts.call(this, menuItem, type);\n list.appendChild(menuItem);\n },\n\n // Format a time for display\n formatTime(time = 0, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return time;\n } // Always display hours if duration is over an hour\n\n\n const forceHours = getHours(this.duration) > 0;\n return formatTime(time, forceHours, inverted);\n },\n\n // Update the displayed time\n updateTimeDisplay(target = null, time = 0, inverted = false) {\n // Bail if there's no element to display or the value isn't a number\n if (!is.element(target) || !is.number(time)) {\n return;\n } // eslint-disable-next-line no-param-reassign\n\n\n target.innerText = controls.formatTime(time, inverted);\n },\n\n // Update volume UI and storage\n updateVolume() {\n if (!this.supported.ui) {\n return;\n } // Update range\n\n\n if (is.element(this.elements.inputs.volume)) {\n controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);\n } // Update mute state\n\n\n if (is.element(this.elements.buttons.mute)) {\n this.elements.buttons.mute.pressed = this.muted || this.volume === 0;\n }\n },\n\n // Update seek value and lower fill\n setRange(target, value = 0) {\n if (!is.element(target)) {\n return;\n } // eslint-disable-next-line\n\n\n target.value = value; // Webkit range fill\n\n controls.updateRangeFill.call(this, target);\n },\n\n // Update <progress> elements\n updateProgress(event) {\n if (!this.supported.ui || !is.event(event)) {\n return;\n }\n\n let value = 0;\n\n const setProgress = (target, input) => {\n const val = is.number(input) ? input : 0;\n const progress = is.element(target) ? target : this.elements.display.buffer; // Update value and label\n\n if (is.element(progress)) {\n progress.value = val; // Update text label inside\n\n const label = progress.getElementsByTagName('span')[0];\n\n if (is.element(label)) {\n label.childNodes[0].nodeValue = val;\n }\n }\n };\n\n if (event) {\n switch (event.type) {\n // Video playing\n case 'timeupdate':\n case 'seeking':\n case 'seeked':\n value = getPercentage(this.currentTime, this.duration); // Set seek range value only if it's a 'natural' time event\n\n if (event.type === 'timeupdate') {\n controls.setRange.call(this, this.elements.inputs.seek, value);\n }\n\n break;\n // Check buffer status\n\n case 'playing':\n case 'progress':\n setProgress(this.elements.display.buffer, this.buffered * 100);\n break;\n }\n }\n },\n\n // Webkit polyfill for lower fill range\n updateRangeFill(target) {\n // Get range from event if event passed\n const range = is.event(target) ? target.target : target; // Needs to be a valid <input type='range'>\n\n if (!is.element(range) || range.getAttribute('type') !== 'range') {\n return;\n } // Set aria values for https://github.com/sampotts/plyr/issues/905\n\n\n if (matches(range, this.config.selectors.inputs.seek)) {\n range.setAttribute('aria-valuenow', this.currentTime);\n const currentTime = controls.formatTime(this.currentTime);\n const duration = controls.formatTime(this.duration);\n const format = i18n.get('seekLabel', this.config);\n range.setAttribute('aria-valuetext', format.replace('{currentTime}', currentTime).replace('{duration}', duration));\n } else if (matches(range, this.config.selectors.inputs.volume)) {\n const percent = range.value * 100;\n range.setAttribute('aria-valuenow', percent);\n range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`);\n } else {\n range.setAttribute('aria-valuenow', range.value);\n } // WebKit only\n\n\n if (!browser.isWebkit) {\n return;\n } // Set CSS custom property\n\n\n range.style.setProperty('--value', `${range.value / range.max * 100}%`);\n },\n\n // Update hover tooltip for seeking\n updateSeekTooltip(event) {\n // Bail if setting not true\n if (!this.config.tooltips.seek || !is.element(this.elements.inputs.seek) || !is.element(this.elements.display.seekTooltip) || this.duration === 0) {\n return;\n }\n\n const visible = `${this.config.classNames.tooltip}--visible`;\n\n const toggle = show => toggleClass(this.elements.display.seekTooltip, visible, show); // Hide on touch\n\n\n if (this.touch) {\n toggle(false);\n return;\n } // Determine percentage, if already visible\n\n\n let percent = 0;\n const clientRect = this.elements.progress.getBoundingClientRect();\n\n if (is.event(event)) {\n percent = 100 / clientRect.width * (event.pageX - clientRect.left);\n } else if (hasClass(this.elements.display.seekTooltip, visible)) {\n percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);\n } else {\n return;\n } // Set bounds\n\n\n if (percent < 0) {\n percent = 0;\n } else if (percent > 100) {\n percent = 100;\n } // Display the time a click would seek to\n\n\n controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent); // Set position\n\n this.elements.display.seekTooltip.style.left = `${percent}%`; // Show/hide the tooltip\n // If the event is a moues in/out and percentage is inside bounds\n\n if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) {\n toggle(event.type === 'mouseenter');\n }\n },\n\n // Handle time change event\n timeUpdate(event) {\n // Only invert if only one time element is displayed and used for both duration and currentTime\n const invert = !is.element(this.elements.display.duration) && this.config.invertTime; // Duration\n\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, invert ? this.duration - this.currentTime : this.currentTime, invert); // Ignore updates while seeking\n\n if (event && event.type === 'timeupdate' && this.media.seeking) {\n return;\n } // Playing progress\n\n\n controls.updateProgress.call(this, event);\n },\n\n // Show the duration on metadataloaded or durationchange events\n durationUpdate() {\n // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false\n if (!this.supported.ui || !this.config.invertTime && this.currentTime) {\n return;\n } // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar.\n // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415\n // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062\n // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338\n\n\n if (this.duration >= 2 ** 32) {\n toggleHidden(this.elements.display.currentTime, true);\n toggleHidden(this.elements.progress, true);\n return;\n } // Update ARIA values\n\n\n if (is.element(this.elements.inputs.seek)) {\n this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration);\n } // If there's a spot to display duration\n\n\n const hasDuration = is.element(this.elements.display.duration); // If there's only one time display, display duration there\n\n if (!hasDuration && this.config.displayDuration && this.paused) {\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);\n } // If there's a duration element, update content\n\n\n if (hasDuration) {\n controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);\n } // Update the tooltip (if visible)\n\n\n controls.updateSeekTooltip.call(this);\n },\n\n // Hide/show a tab\n toggleMenuButton(setting, toggle) {\n toggleHidden(this.elements.settings.buttons[setting], !toggle);\n },\n\n // Update the selected setting\n updateSetting(setting, container, input) {\n const pane = this.elements.settings.panels[setting];\n let value = null;\n let list = container;\n\n if (setting === 'captions') {\n value = this.currentTrack;\n } else {\n value = !is.empty(input) ? input : this[setting]; // Get default\n\n if (is.empty(value)) {\n value = this.config[setting].default;\n } // Unsupported value\n\n\n if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) {\n this.debug.warn(`Unsupported value of '${value}' for ${setting}`);\n return;\n } // Disabled value\n\n\n if (!this.config[setting].options.includes(value)) {\n this.debug.warn(`Disabled value of '${value}' for ${setting}`);\n return;\n }\n } // Get the list if we need to\n\n\n if (!is.element(list)) {\n list = pane && pane.querySelector('[role=\"menu\"]');\n } // If there's no list it means it's not been rendered...\n\n\n if (!is.element(list)) {\n return;\n } // Update the label\n\n\n const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`);\n label.innerHTML = controls.getLabel.call(this, setting, value); // Find the radio option and check it\n\n const target = list && list.querySelector(`[value=\"${value}\"]`);\n\n if (is.element(target)) {\n target.checked = true;\n }\n },\n\n // Translate a value into a nice label\n getLabel(setting, value) {\n switch (setting) {\n case 'speed':\n return value === 1 ? i18n.get('normal', this.config) : `${value}×`;\n\n case 'quality':\n if (is.number(value)) {\n const label = i18n.get(`qualityLabel.${value}`, this.config);\n\n if (!label.length) {\n return `${value}p`;\n }\n\n return label;\n }\n\n return toTitleCase(value);\n\n case 'captions':\n return captions.getLabel.call(this);\n\n default:\n return null;\n }\n },\n\n // Set the quality menu\n setQualityMenu(options) {\n // Menu required\n if (!is.element(this.elements.settings.panels.quality)) {\n return;\n }\n\n const type = 'quality';\n const list = this.elements.settings.panels.quality.querySelector('[role=\"menu\"]'); // Set options if passed and filter based on uniqueness and config\n\n if (is.array(options)) {\n this.options.quality = dedupe(options).filter(quality => this.config.quality.options.includes(quality));\n } // Toggle the pane and tab\n\n\n const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1;\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If we're hiding, nothing more to do\n\n if (!toggle) {\n return;\n } // Get the badge HTML for HD, 4K etc\n\n\n const getBadge = quality => {\n const label = i18n.get(`qualityBadge.${quality}`, this.config);\n\n if (!label.length) {\n return null;\n }\n\n return controls.createBadge.call(this, label);\n }; // Sort options by the config and then render options\n\n\n this.options.quality.sort((a, b) => {\n const sorting = this.config.quality.options;\n return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1;\n }).forEach(quality => {\n controls.createMenuItem.call(this, {\n value: quality,\n list,\n type,\n title: controls.getLabel.call(this, 'quality', quality),\n badge: getBadge(quality)\n });\n });\n controls.updateSetting.call(this, type, list);\n },\n\n // Set the looping options\n\n /* setLoopMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.loop)) {\n return;\n }\n const options = ['start', 'end', 'all', 'reset'];\n const list = this.elements.settings.panels.loop.querySelector('[role=\"menu\"]');\n // Show the pane and tab\n toggleHidden(this.elements.settings.buttons.loop, false);\n toggleHidden(this.elements.settings.panels.loop, false);\n // Toggle the pane and tab\n const toggle = !is.empty(this.loop.options);\n controls.toggleMenuButton.call(this, 'loop', toggle);\n // Empty the menu\n emptyElement(list);\n options.forEach(option => {\n const item = createElement('li');\n const button = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.loop), {\n type: 'button',\n class: this.config.classNames.control,\n 'data-plyr-loop-action': option,\n }),\n i18n.get(option, this.config)\n );\n if (['start', 'end'].includes(option)) {\n const badge = controls.createBadge.call(this, '00:00');\n button.appendChild(badge);\n }\n item.appendChild(button);\n list.appendChild(item);\n });\n }, */\n // Get current selected caption language\n // TODO: rework this to user the getter in the API?\n // Set a list of available captions languages\n setCaptionsMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.captions)) {\n return;\n } // TODO: Captions or language? Currently it's mixed\n\n\n const type = 'captions';\n const list = this.elements.settings.panels.captions.querySelector('[role=\"menu\"]');\n const tracks = captions.getTracks.call(this);\n const toggle = Boolean(tracks.length); // Toggle the pane and tab\n\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If there's no captions, bail\n\n if (!toggle) {\n return;\n } // Generate options data\n\n\n const options = tracks.map((track, value) => ({\n value,\n checked: this.captions.toggled && this.currentTrack === value,\n title: captions.getLabel.call(this, track),\n badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()),\n list,\n type: 'language'\n })); // Add the \"Disabled\" option to turn off captions\n\n options.unshift({\n value: -1,\n checked: !this.captions.toggled,\n title: i18n.get('disabled', this.config),\n list,\n type: 'language'\n }); // Generate options\n\n options.forEach(controls.createMenuItem.bind(this));\n controls.updateSetting.call(this, type, list);\n },\n\n // Set a list of available captions languages\n setSpeedMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.speed)) {\n return;\n }\n\n const type = 'speed';\n const list = this.elements.settings.panels.speed.querySelector('[role=\"menu\"]'); // Filter out invalid speeds\n\n this.options.speed = this.options.speed.filter(o => o >= this.minimumSpeed && o <= this.maximumSpeed); // Toggle the pane and tab\n\n const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1;\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If we're hiding, nothing more to do\n\n if (!toggle) {\n return;\n } // Create items\n\n\n this.options.speed.forEach(speed => {\n controls.createMenuItem.call(this, {\n value: speed,\n list,\n type,\n title: controls.getLabel.call(this, 'speed', speed)\n });\n });\n controls.updateSetting.call(this, type, list);\n },\n\n // Check if we need to hide/show the settings menu\n checkMenu() {\n const {\n buttons\n } = this.elements.settings;\n const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden);\n toggleHidden(this.elements.settings.menu, !visible);\n },\n\n // Focus the first menu item in a given (or visible) menu\n focusFirstMenuItem(pane, tabFocus = false) {\n if (this.elements.settings.popup.hidden) {\n return;\n }\n\n let target = pane;\n\n if (!is.element(target)) {\n target = Object.values(this.elements.settings.panels).find(p => !p.hidden);\n }\n\n const firstItem = target.querySelector('[role^=\"menuitem\"]');\n setFocus.call(this, firstItem, tabFocus);\n },\n\n // Show/hide menu\n toggleMenu(input) {\n const {\n popup\n } = this.elements.settings;\n const button = this.elements.buttons.settings; // Menu and button are required\n\n if (!is.element(popup) || !is.element(button)) {\n return;\n } // True toggle by default\n\n\n const {\n hidden\n } = popup;\n let show = hidden;\n\n if (is.boolean(input)) {\n show = input;\n } else if (is.keyboardEvent(input) && input.which === 27) {\n show = false;\n } else if (is.event(input)) {\n // If Plyr is in a shadowDOM, the event target is set to the component, instead of the\n // Element in the shadowDOM. The path, if available, is complete.\n const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target;\n const isMenuItem = popup.contains(target); // If the click was inside the menu or if the click\n // wasn't the button or menu item and we're trying to\n // show the menu (a doc click shouldn't show the menu)\n\n if (isMenuItem || !isMenuItem && input.target !== button && show) {\n return;\n }\n } // Set button attributes\n\n\n button.setAttribute('aria-expanded', show); // Show the actual popup\n\n toggleHidden(popup, !show); // Add class hook\n\n toggleClass(this.elements.container, this.config.classNames.menu.open, show); // Focus the first item if key interaction\n\n if (show && is.keyboardEvent(input)) {\n controls.focusFirstMenuItem.call(this, null, true);\n } else if (!show && !hidden) {\n // If closing, re-focus the button\n setFocus.call(this, button, is.keyboardEvent(input));\n }\n },\n\n // Get the natural size of a menu panel\n getMenuSize(tab) {\n const clone = tab.cloneNode(true);\n clone.style.position = 'absolute';\n clone.style.opacity = 0;\n clone.removeAttribute('hidden'); // Append to parent so we get the \"real\" size\n\n tab.parentNode.appendChild(clone); // Get the sizes before we remove\n\n const width = clone.scrollWidth;\n const height = clone.scrollHeight; // Remove from the DOM\n\n removeElement(clone);\n return {\n width,\n height\n };\n },\n\n // Show a panel in the menu\n showMenuPanel(type = '', tabFocus = false) {\n const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`); // Nothing to show, bail\n\n if (!is.element(target)) {\n return;\n } // Hide all other panels\n\n\n const container = target.parentNode;\n const current = Array.from(container.children).find(node => !node.hidden); // If we can do fancy animations, we'll animate the height/width\n\n if (support.transitions && !support.reducedMotion) {\n // Set the current width as a base\n container.style.width = `${current.scrollWidth}px`;\n container.style.height = `${current.scrollHeight}px`; // Get potential sizes\n\n const size = controls.getMenuSize.call(this, target); // Restore auto height/width\n\n const restore = event => {\n // We're only bothered about height and width on the container\n if (event.target !== container || !['width', 'height'].includes(event.propertyName)) {\n return;\n } // Revert back to auto\n\n\n container.style.width = '';\n container.style.height = ''; // Only listen once\n\n off.call(this, container, transitionEndEvent, restore);\n }; // Listen for the transition finishing and restore auto height/width\n\n\n on.call(this, container, transitionEndEvent, restore); // Set dimensions to target\n\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n } // Set attributes on current tab\n\n\n toggleHidden(current, true); // Set attributes on target\n\n toggleHidden(target, false); // Focus the first item\n\n controls.focusFirstMenuItem.call(this, target, tabFocus);\n },\n\n // Set the download URL\n setDownloadUrl() {\n const button = this.elements.buttons.download; // Bail if no button\n\n if (!is.element(button)) {\n return;\n } // Set attribute\n\n\n button.setAttribute('href', this.download);\n },\n\n // Build the default HTML\n create(data) {\n const {\n bindMenuItemShortcuts,\n createButton,\n createProgress,\n createRange,\n createTime,\n setQualityMenu,\n setSpeedMenu,\n showMenuPanel\n } = controls;\n this.elements.controls = null; // Larger overlaid play button\n\n if (is.array(this.config.controls) && this.config.controls.includes('play-large')) {\n this.elements.container.appendChild(createButton.call(this, 'play-large'));\n } // Create the container\n\n\n const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper));\n this.elements.controls = container; // Default item attributes\n\n const defaultAttributes = {\n class: 'plyr__controls__item'\n }; // Loop through controls in order\n\n dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach(control => {\n // Restart button\n if (control === 'restart') {\n container.appendChild(createButton.call(this, 'restart', defaultAttributes));\n } // Rewind button\n\n\n if (control === 'rewind') {\n container.appendChild(createButton.call(this, 'rewind', defaultAttributes));\n } // Play/Pause button\n\n\n if (control === 'play') {\n container.appendChild(createButton.call(this, 'play', defaultAttributes));\n } // Fast forward button\n\n\n if (control === 'fast-forward') {\n container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes));\n } // Progress\n\n\n if (control === 'progress') {\n const progressContainer = createElement('div', {\n class: `${defaultAttributes.class} plyr__progress__container`\n });\n const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress)); // Seek range slider\n\n progress.appendChild(createRange.call(this, 'seek', {\n id: `plyr-seek-${data.id}`\n })); // Buffer progress\n\n progress.appendChild(createProgress.call(this, 'buffer')); // TODO: Add loop display indicator\n // Seek tooltip\n\n if (this.config.tooltips.seek) {\n const tooltip = createElement('span', {\n class: this.config.classNames.tooltip\n }, '00:00');\n progress.appendChild(tooltip);\n this.elements.display.seekTooltip = tooltip;\n }\n\n this.elements.progress = progress;\n progressContainer.appendChild(this.elements.progress);\n container.appendChild(progressContainer);\n } // Media current time display\n\n\n if (control === 'current-time') {\n container.appendChild(createTime.call(this, 'currentTime', defaultAttributes));\n } // Media duration display\n\n\n if (control === 'duration') {\n container.appendChild(createTime.call(this, 'duration', defaultAttributes));\n } // Volume controls\n\n\n if (control === 'mute' || control === 'volume') {\n let {\n volume\n } = this.elements; // Create the volume container if needed\n\n if (!is.element(volume) || !container.contains(volume)) {\n volume = createElement('div', extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__volume`.trim()\n }));\n this.elements.volume = volume;\n container.appendChild(volume);\n } // Toggle mute button\n\n\n if (control === 'mute') {\n volume.appendChild(createButton.call(this, 'mute'));\n } // Volume range control\n // Ignored on iOS as it's handled globally\n // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html\n\n\n if (control === 'volume' && !browser.isIos) {\n // Set the attributes\n const attributes = {\n max: 1,\n step: 0.05,\n value: this.config.volume\n }; // Create the volume range slider\n\n volume.appendChild(createRange.call(this, 'volume', extend(attributes, {\n id: `plyr-volume-${data.id}`\n })));\n }\n } // Toggle captions button\n\n\n if (control === 'captions') {\n container.appendChild(createButton.call(this, 'captions', defaultAttributes));\n } // Settings button / menu\n\n\n if (control === 'settings' && !is.empty(this.config.settings)) {\n const wrapper = createElement('div', extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__menu`.trim(),\n hidden: ''\n }));\n wrapper.appendChild(createButton.call(this, 'settings', {\n 'aria-haspopup': true,\n 'aria-controls': `plyr-settings-${data.id}`,\n 'aria-expanded': false\n }));\n const popup = createElement('div', {\n class: 'plyr__menu__container',\n id: `plyr-settings-${data.id}`,\n hidden: ''\n });\n const inner = createElement('div');\n const home = createElement('div', {\n id: `plyr-settings-${data.id}-home`\n }); // Create the menu\n\n const menu = createElement('div', {\n role: 'menu'\n });\n home.appendChild(menu);\n inner.appendChild(home);\n this.elements.settings.panels.home = home; // Build the menu items\n\n this.config.settings.forEach(type => {\n // TODO: bundle this with the createMenuItem helper and bindings\n const menuItem = createElement('button', extend(getAttributesFromSelector(this.config.selectors.buttons.settings), {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`,\n role: 'menuitem',\n 'aria-haspopup': true,\n hidden: ''\n })); // Bind menu shortcuts for keyboard users\n\n bindMenuItemShortcuts.call(this, menuItem, type); // Show menu on click\n\n on.call(this, menuItem, 'click', () => {\n showMenuPanel.call(this, type, false);\n });\n const flex = createElement('span', null, i18n.get(type, this.config));\n const value = createElement('span', {\n class: this.config.classNames.menu.value\n }); // Speed contains HTML entities\n\n value.innerHTML = data[type];\n flex.appendChild(value);\n menuItem.appendChild(flex);\n menu.appendChild(menuItem); // Build the panes\n\n const pane = createElement('div', {\n id: `plyr-settings-${data.id}-${type}`,\n hidden: ''\n }); // Back button\n\n const backButton = createElement('button', {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--back`\n }); // Visible label\n\n backButton.appendChild(createElement('span', {\n 'aria-hidden': true\n }, i18n.get(type, this.config))); // Screen reader label\n\n backButton.appendChild(createElement('span', {\n class: this.config.classNames.hidden\n }, i18n.get('menuBack', this.config))); // Go back via keyboard\n\n on.call(this, pane, 'keydown', event => {\n // We only care about <-\n if (event.which !== 37) {\n return;\n } // Prevent seek\n\n\n event.preventDefault();\n event.stopPropagation(); // Show the respective menu\n\n showMenuPanel.call(this, 'home', true);\n }, false); // Go back via button click\n\n on.call(this, backButton, 'click', () => {\n showMenuPanel.call(this, 'home', false);\n }); // Add to pane\n\n pane.appendChild(backButton); // Menu\n\n pane.appendChild(createElement('div', {\n role: 'menu'\n }));\n inner.appendChild(pane);\n this.elements.settings.buttons[type] = menuItem;\n this.elements.settings.panels[type] = pane;\n });\n popup.appendChild(inner);\n wrapper.appendChild(popup);\n container.appendChild(wrapper);\n this.elements.settings.popup = popup;\n this.elements.settings.menu = wrapper;\n } // Picture in picture button\n\n\n if (control === 'pip' && support.pip) {\n container.appendChild(createButton.call(this, 'pip', defaultAttributes));\n } // Airplay button\n\n\n if (control === 'airplay' && support.airplay) {\n container.appendChild(createButton.call(this, 'airplay', defaultAttributes));\n } // Download button\n\n\n if (control === 'download') {\n const attributes = extend({}, defaultAttributes, {\n element: 'a',\n href: this.download,\n target: '_blank'\n }); // Set download attribute for HTML5 only\n\n if (this.isHTML5) {\n attributes.download = '';\n }\n\n const {\n download\n } = this.config.urls;\n\n if (!is.url(download) && this.isEmbed) {\n extend(attributes, {\n icon: `logo-${this.provider}`,\n label: this.provider\n });\n }\n\n container.appendChild(createButton.call(this, 'download', attributes));\n } // Toggle fullscreen button\n\n\n if (control === 'fullscreen') {\n container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes));\n }\n }); // Set available quality levels\n\n if (this.isHTML5) {\n setQualityMenu.call(this, html5.getQualityOptions.call(this));\n }\n\n setSpeedMenu.call(this);\n return container;\n },\n\n // Insert controls\n inject() {\n // Sprite\n if (this.config.loadSprite) {\n const icon = controls.getIconUrl.call(this); // Only load external sprite using AJAX\n\n if (icon.cors) {\n loadSprite(icon.url, 'sprite-plyr');\n }\n } // Create a unique ID\n\n\n this.id = Math.floor(Math.random() * 10000); // Null by default\n\n let container = null;\n this.elements.controls = null; // Set template properties\n\n const props = {\n id: this.id,\n seektime: this.config.seekTime,\n title: this.config.title\n };\n let update = true; // If function, run it and use output\n\n if (is.function(this.config.controls)) {\n this.config.controls = this.config.controls.call(this, props);\n } // Convert falsy controls to empty array (primarily for empty strings)\n\n\n if (!this.config.controls) {\n this.config.controls = [];\n }\n\n if (is.element(this.config.controls) || is.string(this.config.controls)) {\n // HTMLElement or Non-empty string passed as the option\n container = this.config.controls;\n } else {\n // Create controls\n container = controls.create.call(this, {\n id: this.id,\n seektime: this.config.seekTime,\n speed: this.speed,\n quality: this.quality,\n captions: captions.getLabel.call(this) // TODO: Looping\n // loop: 'None',\n\n });\n update = false;\n } // Replace props with their value\n\n\n const replace = input => {\n let result = input;\n Object.entries(props).forEach(([key, value]) => {\n result = replaceAll(result, `{${key}}`, value);\n });\n return result;\n }; // Update markup\n\n\n if (update) {\n if (is.string(this.config.controls)) {\n container = replace(container);\n }\n } // Controls container\n\n\n let target; // Inject to custom location\n\n if (is.string(this.config.selectors.controls.container)) {\n target = document.querySelector(this.config.selectors.controls.container);\n } // Inject into the container by default\n\n\n if (!is.element(target)) {\n target = this.elements.container;\n } // Inject controls HTML (needs to be before captions, hence \"afterbegin\")\n\n\n const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML';\n target[insertMethod]('afterbegin', container); // Find the elements if need be\n\n if (!is.element(this.elements.controls)) {\n controls.findElements.call(this);\n } // Add pressed property to buttons\n\n\n if (!is.empty(this.elements.buttons)) {\n const addProperty = button => {\n const className = this.config.classNames.controlPressed;\n Object.defineProperty(button, 'pressed', {\n enumerable: true,\n\n get() {\n return hasClass(button, className);\n },\n\n set(pressed = false) {\n toggleClass(button, className, pressed);\n }\n\n });\n }; // Toggle classname when pressed property is set\n\n\n Object.values(this.elements.buttons).filter(Boolean).forEach(button => {\n if (is.array(button) || is.nodeList(button)) {\n Array.from(button).filter(Boolean).forEach(addProperty);\n } else {\n addProperty(button);\n }\n });\n } // Edge sometimes doesn't finish the paint so force a repaint\n\n\n if (browser.isEdge) {\n repaint(target);\n } // Setup tooltips\n\n\n if (this.config.tooltips.controls) {\n const {\n classNames,\n selectors\n } = this.config;\n const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`;\n const labels = getElements.call(this, selector);\n Array.from(labels).forEach(label => {\n toggleClass(label, this.config.classNames.hidden, false);\n toggleClass(label, this.config.classNames.tooltip, true);\n });\n }\n }\n\n};\n\n// ==========================================================================\n/**\n * Parse a string to a URL object\n * @param {String} input - the URL to be parsed\n * @param {Boolean} safe - failsafe parsing\n */\n\nfunction parseUrl(input, safe = true) {\n let url = input;\n\n if (safe) {\n const parser = document.createElement('a');\n parser.href = url;\n url = parser.href;\n }\n\n try {\n return new URL(url);\n } catch (_) {\n return null;\n }\n} // Convert object to URLSearchParams\n\nfunction buildUrlParams(input) {\n const params = new URLSearchParams();\n\n if (is.object(input)) {\n Object.entries(input).forEach(([key, value]) => {\n params.set(key, value);\n });\n }\n\n return params;\n}\n\n// ==========================================================================\nconst captions = {\n // Setup captions\n setup() {\n // Requires UI support\n if (!this.supported.ui) {\n return;\n } // Only Vimeo and HTML5 video supported at this point\n\n\n if (!this.isVideo || this.isYouTube || this.isHTML5 && !support.textTracks) {\n // Clear menu and hide\n if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) {\n controls.setCaptionsMenu.call(this);\n }\n\n return;\n } // Inject the container\n\n\n if (!is.element(this.elements.captions)) {\n this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions));\n insertAfter(this.elements.captions, this.elements.wrapper);\n } // Fix IE captions if CORS is used\n // Fetch captions and inject as blobs instead (data URIs not supported!)\n\n\n if (browser.isIE && window.URL) {\n const elements = this.media.querySelectorAll('track');\n Array.from(elements).forEach(track => {\n const src = track.getAttribute('src');\n const url = parseUrl(src);\n\n if (url !== null && url.hostname !== window.location.href.hostname && ['http:', 'https:'].includes(url.protocol)) {\n fetch(src, 'blob').then(blob => {\n track.setAttribute('src', window.URL.createObjectURL(blob));\n }).catch(() => {\n removeElement(track);\n });\n }\n });\n } // Get and set initial data\n // The \"preferred\" options are not realized unless / until the wanted language has a match\n // * languages: Array of user's browser languages.\n // * language: The language preferred by user settings or config\n // * active: The state preferred by user settings or config\n // * toggled: The real captions state\n\n\n const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en'];\n const languages = dedupe(browserLanguages.map(language => language.split('-')[0]));\n let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase(); // Use first browser language when language is 'auto'\n\n if (language === 'auto') {\n [language] = languages;\n }\n\n let active = this.storage.get('captions');\n\n if (!is.boolean(active)) {\n ({\n active\n } = this.config.captions);\n }\n\n Object.assign(this.captions, {\n toggled: false,\n active,\n language,\n languages\n }); // Watch changes to textTracks and update captions menu\n\n if (this.isHTML5) {\n const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack';\n on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this));\n } // Update available languages in list next tick (the event must not be triggered before the listeners)\n\n\n setTimeout(captions.update.bind(this), 0);\n },\n\n // Update available language options in settings based on tracks\n update() {\n const tracks = captions.getTracks.call(this, true); // Get the wanted language\n\n const {\n active,\n language,\n meta,\n currentTrackNode\n } = this.captions;\n const languageExists = Boolean(tracks.find(track => track.language === language)); // Handle tracks (add event listener and \"pseudo\"-default)\n\n if (this.isHTML5 && this.isVideo) {\n tracks.filter(track => !meta.get(track)).forEach(track => {\n this.debug.log('Track added', track); // Attempt to store if the original dom element was \"default\"\n\n meta.set(track, {\n default: track.mode === 'showing'\n }); // Turn off native caption rendering to avoid double captions\n // Note: mode='hidden' forces a track to download. To ensure every track\n // isn't downloaded at once, only 'showing' tracks should be reassigned\n // eslint-disable-next-line no-param-reassign\n\n if (track.mode === 'showing') {\n // eslint-disable-next-line no-param-reassign\n track.mode = 'hidden';\n } // Add event listener for cue changes\n\n\n on.call(this, track, 'cuechange', () => captions.updateCues.call(this));\n });\n } // Update language first time it matches, or if the previous matching track was removed\n\n\n if (languageExists && this.language !== language || !tracks.includes(currentTrackNode)) {\n captions.setLanguage.call(this, language);\n captions.toggle.call(this, active && languageExists);\n } // Enable or disable captions based on track length\n\n\n if (this.elements) {\n toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks));\n } // Update available languages in list\n\n\n if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) {\n controls.setCaptionsMenu.call(this);\n }\n },\n\n // Toggle captions display\n // Used internally for the toggleCaptions method, with the passive option forced to false\n toggle(input, passive = true) {\n // If there's no full support\n if (!this.supported.ui) {\n return;\n }\n\n const {\n toggled\n } = this.captions; // Current state\n\n const activeClass = this.config.classNames.captions.active; // Get the next state\n // If the method is called without parameter, toggle based on current value\n\n const active = is.nullOrUndefined(input) ? !toggled : input; // Update state and trigger event\n\n if (active !== toggled) {\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.active = active;\n this.storage.set({\n captions: active\n });\n } // Force language if the call isn't passive and there is no matching language to toggle to\n\n\n if (!this.language && active && !passive) {\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true); // Override user preferences to avoid switching languages if a matching track is added\n\n this.captions.language = track.language; // Set caption, but don't store in localStorage as user preference\n\n captions.set.call(this, tracks.indexOf(track));\n return;\n } // Toggle button if it's enabled\n\n\n if (this.elements.buttons.captions) {\n this.elements.buttons.captions.pressed = active;\n } // Add class hook\n\n\n toggleClass(this.elements.container, activeClass, active);\n this.captions.toggled = active; // Update settings menu\n\n controls.updateSetting.call(this, 'captions'); // Trigger event (not used internally)\n\n triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled');\n } // Wait for the call stack to clear before setting mode='hidden'\n // on the active track - forcing the browser to download it\n\n\n setTimeout(() => {\n if (active && this.captions.toggled) {\n this.captions.currentTrackNode.mode = 'hidden';\n }\n });\n },\n\n // Set captions by track index\n // Used internally for the currentTrack setter with the passive option forced to false\n set(index, passive = true) {\n const tracks = captions.getTracks.call(this); // Disable captions if setting to -1\n\n if (index === -1) {\n captions.toggle.call(this, false, passive);\n return;\n }\n\n if (!is.number(index)) {\n this.debug.warn('Invalid caption argument', index);\n return;\n }\n\n if (!(index in tracks)) {\n this.debug.warn('Track not found', index);\n return;\n }\n\n if (this.captions.currentTrack !== index) {\n this.captions.currentTrack = index;\n const track = tracks[index];\n const {\n language\n } = track || {}; // Store reference to node for invalidation on remove\n\n this.captions.currentTrackNode = track; // Update settings menu\n\n controls.updateSetting.call(this, 'captions'); // When passive, don't override user preferences\n\n if (!passive) {\n this.captions.language = language;\n this.storage.set({\n language\n });\n } // Handle Vimeo captions\n\n\n if (this.isVimeo) {\n this.embed.enableTextTrack(language);\n } // Trigger event\n\n\n triggerEvent.call(this, this.media, 'languagechange');\n } // Show captions\n\n\n captions.toggle.call(this, true, passive);\n\n if (this.isHTML5 && this.isVideo) {\n // If we change the active track while a cue is already displayed we need to update it\n captions.updateCues.call(this);\n }\n },\n\n // Set captions by language\n // Used internally for the language setter with the passive option forced to false\n setLanguage(input, passive = true) {\n if (!is.string(input)) {\n this.debug.warn('Invalid language argument', input);\n return;\n } // Normalize\n\n\n const language = input.toLowerCase();\n this.captions.language = language; // Set currentTrack\n\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [language]);\n captions.set.call(this, tracks.indexOf(track), passive);\n },\n\n // Get current valid caption tracks\n // If update is false it will also ignore tracks without metadata\n // This is used to \"freeze\" the language options when captions.update is false\n getTracks(update = false) {\n // Handle media or textTracks missing or null\n const tracks = Array.from((this.media || {}).textTracks || []); // For HTML5, use cache instead of current tracks when it exists (if captions.update is false)\n // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata)\n\n return tracks.filter(track => !this.isHTML5 || update || this.captions.meta.has(track)).filter(track => ['captions', 'subtitles'].includes(track.kind));\n },\n\n // Match tracks based on languages and get the first\n findTrack(languages, force = false) {\n const tracks = captions.getTracks.call(this);\n\n const sortIsDefault = track => Number((this.captions.meta.get(track) || {}).default);\n\n const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a));\n let track;\n languages.every(language => {\n track = sorted.find(t => t.language === language);\n return !track; // Break iteration if there is a match\n }); // If no match is found but is required, get first\n\n return track || (force ? sorted[0] : undefined);\n },\n\n // Get the current track\n getCurrentTrack() {\n return captions.getTracks.call(this)[this.currentTrack];\n },\n\n // Get UI label for track\n getLabel(track) {\n let currentTrack = track;\n\n if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) {\n currentTrack = captions.getCurrentTrack.call(this);\n }\n\n if (is.track(currentTrack)) {\n if (!is.empty(currentTrack.label)) {\n return currentTrack.label;\n }\n\n if (!is.empty(currentTrack.language)) {\n return track.language.toUpperCase();\n }\n\n return i18n.get('enabled', this.config);\n }\n\n return i18n.get('disabled', this.config);\n },\n\n // Update captions using current track's active cues\n // Also optional array argument in case there isn't any track (ex: vimeo)\n updateCues(input) {\n // Requires UI\n if (!this.supported.ui) {\n return;\n }\n\n if (!is.element(this.elements.captions)) {\n this.debug.warn('No captions element to render to');\n return;\n } // Only accept array or empty input\n\n\n if (!is.nullOrUndefined(input) && !Array.isArray(input)) {\n this.debug.warn('updateCues: Invalid input', input);\n return;\n }\n\n let cues = input; // Get cues from track\n\n if (!cues) {\n const track = captions.getCurrentTrack.call(this);\n cues = Array.from((track || {}).activeCues || []).map(cue => cue.getCueAsHTML()).map(getHTML);\n } // Set new caption text\n\n\n const content = cues.map(cueText => cueText.trim()).join('\\n');\n const changed = content !== this.elements.captions.innerHTML;\n\n if (changed) {\n // Empty the container and create a new child element\n emptyElement(this.elements.captions);\n const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption));\n caption.innerHTML = content;\n this.elements.captions.appendChild(caption); // Trigger event\n\n triggerEvent.call(this, this.media, 'cuechange');\n }\n }\n\n};\n\n// ==========================================================================\n// Plyr default config\n// ==========================================================================\nconst defaults = {\n // Disable\n enabled: true,\n // Custom media title\n title: '',\n // Logging to console\n debug: false,\n // Auto play (if supported)\n autoplay: false,\n // Only allow one media playing at once (vimeo only)\n autopause: true,\n // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present)\n // TODO: Remove iosNative fullscreen option in favour of this (logic needs work)\n playsinline: true,\n // Default time to skip when rewind/fast forward\n seekTime: 10,\n // Default volume\n volume: 1,\n muted: false,\n // Pass a custom duration\n duration: null,\n // Display the media duration on load in the current time position\n // If you have opted to display both duration and currentTime, this is ignored\n displayDuration: true,\n // Invert the current time to be a countdown\n invertTime: true,\n // Clicking the currentTime inverts it's value to show time left rather than elapsed\n toggleInvert: true,\n // Force an aspect ratio\n // The format must be `'w:h'` (e.g. `'16:9'`)\n ratio: null,\n // Click video container to play/pause\n clickToPlay: true,\n // Auto hide the controls\n hideControls: true,\n // Reset to start when playback ended\n resetOnEnd: false,\n // Disable the standard context menu\n disableContextMenu: true,\n // Sprite (for icons)\n loadSprite: true,\n iconPrefix: 'plyr',\n iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg',\n // Blank video (used to prevent errors on source change)\n blankVideo: 'https://cdn.plyr.io/static/blank.mp4',\n // Quality default\n quality: {\n default: 576,\n // The options to display in the UI, if available for the source media\n options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240],\n forced: false,\n onChange: null\n },\n // Set loops\n loop: {\n active: false // start: null,\n // end: null,\n\n },\n // Speed default and options to display\n speed: {\n selected: 1,\n // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x)\n options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4]\n },\n // Keyboard shortcut settings\n keyboard: {\n focused: true,\n global: false\n },\n // Display tooltips\n tooltips: {\n controls: false,\n seek: true\n },\n // Captions settings\n captions: {\n active: false,\n language: 'auto',\n // Listen to new tracks added after Plyr is initialized.\n // This is needed for streaming captions, but may result in unselectable options\n update: false\n },\n // Fullscreen settings\n fullscreen: {\n enabled: true,\n // Allow fullscreen?\n fallback: true,\n // Fallback using full viewport/window\n iosNative: false // Use the native fullscreen in iOS (disables custom controls)\n // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode\n // Non-ancestors of the player element will be ignored\n // container: null, // defaults to the player element\n\n },\n // Local storage\n storage: {\n enabled: true,\n key: 'plyr'\n },\n // Default controls\n controls: ['play-large', // 'restart',\n // 'rewind',\n 'play', // 'fast-forward',\n 'progress', 'current-time', // 'duration',\n 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', // 'download',\n 'fullscreen'],\n settings: ['captions', 'quality', 'speed'],\n // Localisation\n i18n: {\n restart: 'Restart',\n rewind: 'Rewind {seektime}s',\n play: 'Play',\n pause: 'Pause',\n fastForward: 'Forward {seektime}s',\n seek: 'Seek',\n seekLabel: '{currentTime} of {duration}',\n played: 'Played',\n buffered: 'Buffered',\n currentTime: 'Current time',\n duration: 'Duration',\n volume: 'Volume',\n mute: 'Mute',\n unmute: 'Unmute',\n enableCaptions: 'Enable captions',\n disableCaptions: 'Disable captions',\n download: 'Download',\n enterFullscreen: 'Enter fullscreen',\n exitFullscreen: 'Exit fullscreen',\n frameTitle: 'Player for {title}',\n captions: 'Captions',\n settings: 'Settings',\n pip: 'PIP',\n menuBack: 'Go back to previous menu',\n speed: 'Speed',\n normal: 'Normal',\n quality: 'Quality',\n loop: 'Loop',\n start: 'Start',\n end: 'End',\n all: 'All',\n reset: 'Reset',\n disabled: 'Disabled',\n enabled: 'Enabled',\n advertisement: 'Ad',\n qualityBadge: {\n 2160: '4K',\n 1440: 'HD',\n 1080: 'HD',\n 720: 'HD',\n 576: 'SD',\n 480: 'SD'\n }\n },\n // URLs\n urls: {\n download: null,\n vimeo: {\n sdk: 'https://player.vimeo.com/api/player.js',\n iframe: 'https://player.vimeo.com/video/{0}?{1}',\n api: 'https://vimeo.com/api/oembed.json?url={0}'\n },\n youtube: {\n sdk: 'https://www.youtube.com/iframe_api',\n api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}'\n },\n googleIMA: {\n sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js'\n }\n },\n // Custom control listeners\n listeners: {\n seek: null,\n play: null,\n pause: null,\n restart: null,\n rewind: null,\n fastForward: null,\n mute: null,\n volume: null,\n captions: null,\n download: null,\n fullscreen: null,\n pip: null,\n airplay: null,\n speed: null,\n quality: null,\n loop: null,\n language: null\n },\n // Events to watch and bubble\n events: [// Events to watch on HTML5 media elements and bubble\n // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events\n 'ended', 'progress', 'stalled', 'playing', 'waiting', 'canplay', 'canplaythrough', 'loadstart', 'loadeddata', 'loadedmetadata', 'timeupdate', 'volumechange', 'play', 'pause', 'error', 'seeking', 'seeked', 'emptied', 'ratechange', 'cuechange', // Custom events\n 'download', 'enterfullscreen', 'exitfullscreen', 'captionsenabled', 'captionsdisabled', 'languagechange', 'controlshidden', 'controlsshown', 'ready', // YouTube\n 'statechange', // Quality\n 'qualitychange', // Ads\n 'adsloaded', 'adscontentpause', 'adscontentresume', 'adstarted', 'adsmidpoint', 'adscomplete', 'adsallcomplete', 'adsimpression', 'adsclick'],\n // Selectors\n // Change these to match your template if using custom HTML\n selectors: {\n editable: 'input, textarea, select, [contenteditable]',\n container: '.plyr',\n controls: {\n container: null,\n wrapper: '.plyr__controls'\n },\n labels: '[data-plyr]',\n buttons: {\n play: '[data-plyr=\"play\"]',\n pause: '[data-plyr=\"pause\"]',\n restart: '[data-plyr=\"restart\"]',\n rewind: '[data-plyr=\"rewind\"]',\n fastForward: '[data-plyr=\"fast-forward\"]',\n mute: '[data-plyr=\"mute\"]',\n captions: '[data-plyr=\"captions\"]',\n download: '[data-plyr=\"download\"]',\n fullscreen: '[data-plyr=\"fullscreen\"]',\n pip: '[data-plyr=\"pip\"]',\n airplay: '[data-plyr=\"airplay\"]',\n settings: '[data-plyr=\"settings\"]',\n loop: '[data-plyr=\"loop\"]'\n },\n inputs: {\n seek: '[data-plyr=\"seek\"]',\n volume: '[data-plyr=\"volume\"]',\n speed: '[data-plyr=\"speed\"]',\n language: '[data-plyr=\"language\"]',\n quality: '[data-plyr=\"quality\"]'\n },\n display: {\n currentTime: '.plyr__time--current',\n duration: '.plyr__time--duration',\n buffer: '.plyr__progress__buffer',\n loop: '.plyr__progress__loop',\n // Used later\n volume: '.plyr__volume--display'\n },\n progress: '.plyr__progress',\n captions: '.plyr__captions',\n caption: '.plyr__caption'\n },\n // Class hooks added to the player in different states\n classNames: {\n type: 'plyr--{0}',\n provider: 'plyr--{0}',\n video: 'plyr__video-wrapper',\n embed: 'plyr__video-embed',\n videoFixedRatio: 'plyr__video-wrapper--fixed-ratio',\n embedContainer: 'plyr__video-embed__container',\n poster: 'plyr__poster',\n posterEnabled: 'plyr__poster-enabled',\n ads: 'plyr__ads',\n control: 'plyr__control',\n controlPressed: 'plyr__control--pressed',\n playing: 'plyr--playing',\n paused: 'plyr--paused',\n stopped: 'plyr--stopped',\n loading: 'plyr--loading',\n hover: 'plyr--hover',\n tooltip: 'plyr__tooltip',\n cues: 'plyr__cues',\n hidden: 'plyr__sr-only',\n hideControls: 'plyr--hide-controls',\n isIos: 'plyr--is-ios',\n isTouch: 'plyr--is-touch',\n uiSupported: 'plyr--full-ui',\n noTransition: 'plyr--no-transition',\n display: {\n time: 'plyr__time'\n },\n menu: {\n value: 'plyr__menu__value',\n badge: 'plyr__badge',\n open: 'plyr--menu-open'\n },\n captions: {\n enabled: 'plyr--captions-enabled',\n active: 'plyr--captions-active'\n },\n fullscreen: {\n enabled: 'plyr--fullscreen-enabled',\n fallback: 'plyr--fullscreen-fallback'\n },\n pip: {\n supported: 'plyr--pip-supported',\n active: 'plyr--pip-active'\n },\n airplay: {\n supported: 'plyr--airplay-supported',\n active: 'plyr--airplay-active'\n },\n tabFocus: 'plyr__tab-focus',\n previewThumbnails: {\n // Tooltip thumbs\n thumbContainer: 'plyr__preview-thumb',\n thumbContainerShown: 'plyr__preview-thumb--is-shown',\n imageContainer: 'plyr__preview-thumb__image-container',\n timeContainer: 'plyr__preview-thumb__time-container',\n // Scrubbing\n scrubbingContainer: 'plyr__preview-scrubbing',\n scrubbingContainerShown: 'plyr__preview-scrubbing--is-shown'\n }\n },\n // Embed attributes\n attributes: {\n embed: {\n provider: 'data-plyr-provider',\n id: 'data-plyr-embed-id',\n hash: 'data-plyr-embed-hash'\n }\n },\n // Advertisements plugin\n // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio\n ads: {\n enabled: false,\n publisherId: '',\n tagUrl: ''\n },\n // Preview Thumbnails plugin\n previewThumbnails: {\n enabled: false,\n src: ''\n },\n // Vimeo plugin\n vimeo: {\n byline: false,\n portrait: false,\n title: false,\n speed: true,\n transparent: false,\n // Custom settings from Plyr\n customControls: true,\n referrerPolicy: null,\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy\n // Whether the owner of the video has a Pro or Business account\n // (which allows us to properly hide controls without CSS hacks, etc)\n premium: false\n },\n // YouTube plugin\n youtube: {\n rel: 0,\n // No related vids\n showinfo: 0,\n // Hide info\n iv_load_policy: 3,\n // Hide annotations\n modestbranding: 1,\n // Hide logos as much as possible (they still show one in the corner when paused)\n // Custom settings from Plyr\n customControls: true,\n noCookie: false // Whether to use an alternative version of YouTube without cookies\n\n }\n};\n\n// ==========================================================================\n// Plyr states\n// ==========================================================================\nconst pip = {\n active: 'picture-in-picture',\n inactive: 'inline'\n};\n\n// ==========================================================================\n// Plyr supported types and providers\n// ==========================================================================\nconst providers = {\n html5: 'html5',\n youtube: 'youtube',\n vimeo: 'vimeo'\n};\nconst types = {\n audio: 'audio',\n video: 'video'\n};\n/**\n * Get provider by URL\n * @param {String} url\n */\n\nfunction getProviderByUrl(url) {\n // YouTube\n if (/^(https?:\\/\\/)?(www\\.)?(youtube\\.com|youtube-nocookie\\.com|youtu\\.?be)\\/.+$/.test(url)) {\n return providers.youtube;\n } // Vimeo\n\n\n if (/^https?:\\/\\/player.vimeo.com\\/video\\/\\d{0,9}(?=\\b|\\/)/.test(url)) {\n return providers.vimeo;\n }\n\n return null;\n}\n\n// ==========================================================================\n// Console wrapper\n// ==========================================================================\nconst noop = () => {};\n\nclass Console {\n constructor(enabled = false) {\n this.enabled = window.console && enabled;\n\n if (this.enabled) {\n this.log('Debugging enabled');\n }\n }\n\n get log() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.log, console) : noop;\n }\n\n get warn() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop;\n }\n\n get error() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.error, console) : noop;\n }\n\n}\n\nclass Fullscreen {\n constructor(player) {\n _defineProperty$1(this, \"onChange\", () => {\n if (!this.enabled) {\n return;\n } // Update toggle button\n\n\n const button = this.player.elements.buttons.fullscreen;\n\n if (is.element(button)) {\n button.pressed = this.active;\n } // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up\n\n\n const target = this.target === this.player.media ? this.target : this.player.elements.container; // Trigger an event\n\n triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true);\n });\n\n _defineProperty$1(this, \"toggleFallback\", (toggle = false) => {\n // Store or restore scroll position\n if (toggle) {\n this.scrollPosition = {\n x: window.scrollX || 0,\n y: window.scrollY || 0\n };\n } else {\n window.scrollTo(this.scrollPosition.x, this.scrollPosition.y);\n } // Toggle scroll\n\n\n document.body.style.overflow = toggle ? 'hidden' : ''; // Toggle class hook\n\n toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle); // Force full viewport on iPhone X+\n\n if (browser.isIos) {\n let viewport = document.head.querySelector('meta[name=\"viewport\"]');\n const property = 'viewport-fit=cover'; // Inject the viewport meta if required\n\n if (!viewport) {\n viewport = document.createElement('meta');\n viewport.setAttribute('name', 'viewport');\n } // Check if the property already exists\n\n\n const hasProperty = is.string(viewport.content) && viewport.content.includes(property);\n\n if (toggle) {\n this.cleanupViewport = !hasProperty;\n\n if (!hasProperty) {\n viewport.content += `,${property}`;\n }\n } else if (this.cleanupViewport) {\n viewport.content = viewport.content.split(',').filter(part => part.trim() !== property).join(',');\n }\n } // Toggle button and fire events\n\n\n this.onChange();\n });\n\n _defineProperty$1(this, \"trapFocus\", event => {\n // Bail if iOS, not active, not the tab key\n if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) {\n return;\n } // Get the current focused element\n\n\n const focused = document.activeElement;\n const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]');\n const [first] = focusable;\n const last = focusable[focusable.length - 1];\n\n if (focused === last && !event.shiftKey) {\n // Move focus to first element that can be tabbed if Shift isn't used\n first.focus();\n event.preventDefault();\n } else if (focused === first && event.shiftKey) {\n // Move focus to last element that can be tabbed if Shift is used\n last.focus();\n event.preventDefault();\n }\n });\n\n _defineProperty$1(this, \"update\", () => {\n if (this.enabled) {\n let mode;\n\n if (this.forceFallback) {\n mode = 'Fallback (forced)';\n } else if (Fullscreen.native) {\n mode = 'Native';\n } else {\n mode = 'Fallback';\n }\n\n this.player.debug.log(`${mode} fullscreen enabled`);\n } else {\n this.player.debug.log('Fullscreen not supported and fallback disabled');\n } // Add styling hook to show button\n\n\n toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled);\n });\n\n _defineProperty$1(this, \"enter\", () => {\n if (!this.enabled) {\n return;\n } // iOS native fullscreen doesn't need the request step\n\n\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n if (this.player.isVimeo) {\n this.player.embed.requestFullscreen();\n } else {\n this.target.webkitEnterFullscreen();\n }\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(true);\n } else if (!this.prefix) {\n this.target.requestFullscreen({\n navigationUI: 'hide'\n });\n } else if (!is.empty(this.prefix)) {\n this.target[`${this.prefix}Request${this.property}`]();\n }\n });\n\n _defineProperty$1(this, \"exit\", () => {\n if (!this.enabled) {\n return;\n } // iOS native fullscreen\n\n\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n this.target.webkitExitFullscreen();\n silencePromise(this.player.play());\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(false);\n } else if (!this.prefix) {\n (document.cancelFullScreen || document.exitFullscreen).call(document);\n } else if (!is.empty(this.prefix)) {\n const action = this.prefix === 'moz' ? 'Cancel' : 'Exit';\n document[`${this.prefix}${action}${this.property}`]();\n }\n });\n\n _defineProperty$1(this, \"toggle\", () => {\n if (!this.active) {\n this.enter();\n } else {\n this.exit();\n }\n });\n\n // Keep reference to parent\n this.player = player; // Get prefix\n\n this.prefix = Fullscreen.prefix;\n this.property = Fullscreen.property; // Scroll position\n\n this.scrollPosition = {\n x: 0,\n y: 0\n }; // Force the use of 'full window/browser' rather than fullscreen\n\n this.forceFallback = player.config.fullscreen.fallback === 'force'; // Get the fullscreen element\n // Checks container is an ancestor, defaults to null\n\n this.player.elements.fullscreen = player.config.fullscreen.container && closest$1(this.player.elements.container, player.config.fullscreen.container); // Register event listeners\n // Handle event (incase user presses escape etc)\n\n on.call(this.player, document, this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`, () => {\n // TODO: Filter for target??\n this.onChange();\n }); // Fullscreen toggle on double click\n\n on.call(this.player, this.player.elements.container, 'dblclick', event => {\n // Ignore double click in controls\n if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) {\n return;\n }\n\n this.player.listeners.proxy(event, this.toggle, 'fullscreen');\n }); // Tap focus when in fullscreen\n\n on.call(this, this.player.elements.container, 'keydown', event => this.trapFocus(event)); // Update the UI\n\n this.update(); // this.toggle = this.toggle.bind(this);\n } // Determine if native supported\n\n\n static get native() {\n return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled);\n } // If we're actually using native\n\n\n get usingNative() {\n return Fullscreen.native && !this.forceFallback;\n } // Get the prefix for handlers\n\n\n static get prefix() {\n // No prefix\n if (is.function(document.exitFullscreen)) {\n return '';\n } // Check for fullscreen support by vendor prefix\n\n\n let value = '';\n const prefixes = ['webkit', 'moz', 'ms'];\n prefixes.some(pre => {\n if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) {\n value = pre;\n return true;\n }\n\n return false;\n });\n return value;\n }\n\n static get property() {\n return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen';\n } // Determine if fullscreen is enabled\n\n\n get enabled() {\n return (Fullscreen.native || this.player.config.fullscreen.fallback) && this.player.config.fullscreen.enabled && this.player.supported.ui && this.player.isVideo;\n } // Get active state\n\n\n get active() {\n if (!this.enabled) {\n return false;\n } // Fallback using classname\n\n\n if (!Fullscreen.native || this.forceFallback) {\n return hasClass(this.target, this.player.config.classNames.fullscreen.fallback);\n }\n\n const element = !this.prefix ? this.target.getRootNode().fullscreenElement : this.target.getRootNode()[`${this.prefix}${this.property}Element`];\n return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target;\n } // Get target element\n\n\n get target() {\n return browser.isIos && this.player.config.fullscreen.iosNative ? this.player.media : this.player.elements.fullscreen || this.player.elements.container;\n }\n\n}\n\n// ==========================================================================\n// Load image avoiding xhr/fetch CORS issues\n// Server status can't be obtained this way unfortunately, so this uses \"naturalWidth\" to determine if the image has loaded\n// By default it checks if it is at least 1px, but you can add a second argument to change this\n// ==========================================================================\nfunction loadImage(src, minWidth = 1) {\n return new Promise((resolve, reject) => {\n const image = new Image();\n\n const handler = () => {\n delete image.onload;\n delete image.onerror;\n (image.naturalWidth >= minWidth ? resolve : reject)(image);\n };\n\n Object.assign(image, {\n onload: handler,\n onerror: handler,\n src\n });\n });\n}\n\n// ==========================================================================\nconst ui = {\n addStyleHook() {\n toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);\n toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);\n },\n\n // Toggle native HTML5 media controls\n toggleNativeControls(toggle = false) {\n if (toggle && this.isHTML5) {\n this.media.setAttribute('controls', '');\n } else {\n this.media.removeAttribute('controls');\n }\n },\n\n // Setup the UI\n build() {\n // Re-attach media element listeners\n // TODO: Use event bubbling?\n this.listeners.media(); // Don't setup interface if no support\n\n if (!this.supported.ui) {\n this.debug.warn(`Basic support only for ${this.provider} ${this.type}`); // Restore native controls\n\n ui.toggleNativeControls.call(this, true); // Bail\n\n return;\n } // Inject custom controls if not present\n\n\n if (!is.element(this.elements.controls)) {\n // Inject custom controls\n controls.inject.call(this); // Re-attach control listeners\n\n this.listeners.controls();\n } // Remove native controls\n\n\n ui.toggleNativeControls.call(this); // Setup captions for HTML5\n\n if (this.isHTML5) {\n captions.setup.call(this);\n } // Reset volume\n\n\n this.volume = null; // Reset mute state\n\n this.muted = null; // Reset loop state\n\n this.loop = null; // Reset quality setting\n\n this.quality = null; // Reset speed\n\n this.speed = null; // Reset volume display\n\n controls.updateVolume.call(this); // Reset time display\n\n controls.timeUpdate.call(this); // Reset duration display\n\n controls.durationUpdate.call(this); // Update the UI\n\n ui.checkPlaying.call(this); // Check for picture-in-picture support\n\n toggleClass(this.elements.container, this.config.classNames.pip.supported, support.pip && this.isHTML5 && this.isVideo); // Check for airplay support\n\n toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5); // Add iOS class\n\n toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos); // Add touch class\n\n toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch); // Ready for API calls\n\n this.ready = true; // Ready event at end of execution stack\n\n setTimeout(() => {\n triggerEvent.call(this, this.media, 'ready');\n }, 0); // Set the title\n\n ui.setTitle.call(this); // Assure the poster image is set, if the property was added before the element was created\n\n if (this.poster) {\n ui.setPoster.call(this, this.poster, false).catch(() => {});\n } // Manually set the duration if user has overridden it.\n // The event listeners for it doesn't get called if preload is disabled (#701)\n\n\n if (this.config.duration) {\n controls.durationUpdate.call(this);\n }\n },\n\n // Setup aria attribute for play and iframe title\n setTitle() {\n // Find the current text\n let label = i18n.get('play', this.config); // If there's a media title set, use that for the label\n\n if (is.string(this.config.title) && !is.empty(this.config.title)) {\n label += `, ${this.config.title}`;\n } // If there's a play button, set label\n\n\n Array.from(this.elements.buttons.play || []).forEach(button => {\n button.setAttribute('aria-label', label);\n }); // Set iframe title\n // https://github.com/sampotts/plyr/issues/124\n\n if (this.isEmbed) {\n const iframe = getElement.call(this, 'iframe');\n\n if (!is.element(iframe)) {\n return;\n } // Default to media type\n\n\n const title = !is.empty(this.config.title) ? this.config.title : 'video';\n const format = i18n.get('frameTitle', this.config);\n iframe.setAttribute('title', format.replace('{title}', title));\n }\n },\n\n // Toggle poster\n togglePoster(enable) {\n toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);\n },\n\n // Set the poster image (async)\n // Used internally for the poster setter, with the passive option forced to false\n setPoster(poster, passive = true) {\n // Don't override if call is passive\n if (passive && this.poster) {\n return Promise.reject(new Error('Poster already set'));\n } // Set property synchronously to respect the call order\n\n\n this.media.setAttribute('data-poster', poster); // Show the poster\n\n this.elements.poster.removeAttribute('hidden'); // Wait until ui is ready\n\n return ready.call(this) // Load image\n .then(() => loadImage(poster)).catch(error => {\n // Hide poster on error unless it's been set by another call\n if (poster === this.poster) {\n ui.togglePoster.call(this, false);\n } // Rethrow\n\n\n throw error;\n }).then(() => {\n // Prevent race conditions\n if (poster !== this.poster) {\n throw new Error('setPoster cancelled by later call to setPoster');\n }\n }).then(() => {\n Object.assign(this.elements.poster.style, {\n backgroundImage: `url('${poster}')`,\n // Reset backgroundSize as well (since it can be set to \"cover\" for padded thumbnails for youtube)\n backgroundSize: ''\n });\n ui.togglePoster.call(this, true);\n return poster;\n });\n },\n\n // Check playing state\n checkPlaying(event) {\n // Class hooks\n toggleClass(this.elements.container, this.config.classNames.playing, this.playing);\n toggleClass(this.elements.container, this.config.classNames.paused, this.paused);\n toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped); // Set state\n\n Array.from(this.elements.buttons.play || []).forEach(target => {\n Object.assign(target, {\n pressed: this.playing\n });\n target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config));\n }); // Only update controls on non timeupdate events\n\n if (is.event(event) && event.type === 'timeupdate') {\n return;\n } // Toggle controls\n\n\n ui.toggleControls.call(this);\n },\n\n // Check if media is loading\n checkLoading(event) {\n this.loading = ['stalled', 'waiting'].includes(event.type); // Clear timer\n\n clearTimeout(this.timers.loading); // Timer to prevent flicker when seeking\n\n this.timers.loading = setTimeout(() => {\n // Update progress bar loading class state\n toggleClass(this.elements.container, this.config.classNames.loading, this.loading); // Update controls visibility\n\n ui.toggleControls.call(this);\n }, this.loading ? 250 : 0);\n },\n\n // Toggle controls based on state and `force` argument\n toggleControls(force) {\n const {\n controls: controlsElement\n } = this.elements;\n\n if (controlsElement && this.config.hideControls) {\n // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.)\n const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now(); // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide\n\n this.toggleControls(Boolean(force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek));\n }\n },\n\n // Migrate any custom properties from the media to the parent\n migrateStyles() {\n // Loop through values (as they are the keys when the object is spread 🤔)\n Object.values({ ...this.media.style\n }) // We're only fussed about Plyr specific properties\n .filter(key => !is.empty(key) && is.string(key) && key.startsWith('--plyr')).forEach(key => {\n // Set on the container\n this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key)); // Clean up from media element\n\n this.media.style.removeProperty(key);\n }); // Remove attribute if empty\n\n if (is.empty(this.media.style)) {\n this.media.removeAttribute('style');\n }\n }\n\n};\n\nclass Listeners {\n constructor(_player) {\n _defineProperty$1(this, \"firstTouch\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n player.touch = true; // Add touch class\n\n toggleClass(elements.container, player.config.classNames.isTouch, true);\n });\n\n _defineProperty$1(this, \"setTabFocus\", event => {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n clearTimeout(this.focusTimer); // Ignore any key other than tab\n\n if (event.type === 'keydown' && event.which !== 9) {\n return;\n } // Store reference to event timeStamp\n\n\n if (event.type === 'keydown') {\n this.lastKeyDown = event.timeStamp;\n } // Remove current classes\n\n\n const removeCurrent = () => {\n const className = player.config.classNames.tabFocus;\n const current = getElements.call(player, `.${className}`);\n toggleClass(current, className, false);\n }; // Determine if a key was pressed to trigger this event\n\n\n const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20; // Ignore focus events if a key was pressed prior\n\n if (event.type === 'focus' && !wasKeyDown) {\n return;\n } // Remove all current\n\n\n removeCurrent(); // Delay the adding of classname until the focus has changed\n // This event fires before the focusin event\n\n if (event.type !== 'focusout') {\n this.focusTimer = setTimeout(() => {\n const focused = document.activeElement; // Ignore if current focus element isn't inside the player\n\n if (!elements.container.contains(focused)) {\n return;\n }\n\n toggleClass(document.activeElement, player.config.classNames.tabFocus, true);\n }, 10);\n }\n });\n\n _defineProperty$1(this, \"global\", (toggle = true) => {\n const {\n player\n } = this; // Keyboard shortcuts\n\n if (player.config.keyboard.global) {\n toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false);\n } // Click anywhere closes menu\n\n\n toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle); // Detect touch by events\n\n once.call(player, document.body, 'touchstart', this.firstTouch); // Tab focus detection\n\n toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true);\n });\n\n _defineProperty$1(this, \"container\", () => {\n const {\n player\n } = this;\n const {\n config,\n elements,\n timers\n } = player; // Keyboard shortcuts\n\n if (!config.keyboard.global && config.keyboard.focused) {\n on.call(player, elements.container, 'keydown keyup', this.handleKey, false);\n } // Toggle controls on mouse events and entering fullscreen\n\n\n on.call(player, elements.container, 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen', event => {\n const {\n controls: controlsElement\n } = elements; // Remove button states for fullscreen\n\n if (controlsElement && event.type === 'enterfullscreen') {\n controlsElement.pressed = false;\n controlsElement.hover = false;\n } // Show, then hide after a timeout unless another control event occurs\n\n\n const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type);\n let delay = 0;\n\n if (show) {\n ui.toggleControls.call(player, true); // Use longer timeout for touch devices\n\n delay = player.touch ? 3000 : 2000;\n } // Clear timer\n\n\n clearTimeout(timers.controls); // Set new timer to prevent flicker when seeking\n\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n }); // Set a gutter for Vimeo\n\n const setGutter = () => {\n if (!player.isVimeo || player.config.vimeo.premium) {\n return;\n }\n\n const target = elements.wrapper;\n const {\n active\n } = player.fullscreen;\n const [videoWidth, videoHeight] = getAspectRatio.call(player);\n const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`); // If not active, remove styles\n\n if (!active) {\n if (useNativeAspectRatio) {\n target.style.width = null;\n target.style.height = null;\n } else {\n target.style.maxWidth = null;\n target.style.margin = null;\n }\n\n return;\n } // Determine which dimension will overflow and constrain view\n\n\n const [viewportWidth, viewportHeight] = getViewportSize();\n const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight;\n\n if (useNativeAspectRatio) {\n target.style.width = overflow ? 'auto' : '100%';\n target.style.height = overflow ? '100%' : 'auto';\n } else {\n target.style.maxWidth = overflow ? `${viewportHeight / videoHeight * videoWidth}px` : null;\n target.style.margin = overflow ? '0 auto' : null;\n }\n }; // Handle resizing\n\n\n const resized = () => {\n clearTimeout(timers.resized);\n timers.resized = setTimeout(setGutter, 50);\n };\n\n on.call(player, elements.container, 'enterfullscreen exitfullscreen', event => {\n const {\n target\n } = player.fullscreen; // Ignore events not from target\n\n if (target !== elements.container) {\n return;\n } // If it's not an embed and no ratio specified\n\n\n if (!player.isEmbed && is.empty(player.config.ratio)) {\n return;\n } // Set Vimeo gutter\n\n\n setGutter(); // Watch for resizes\n\n const method = event.type === 'enterfullscreen' ? on : off;\n method.call(player, window, 'resize', resized);\n });\n });\n\n _defineProperty$1(this, \"media\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player; // Time change on media\n\n on.call(player, player.media, 'timeupdate seeking seeked', event => controls.timeUpdate.call(player, event)); // Display duration\n\n on.call(player, player.media, 'durationchange loadeddata loadedmetadata', event => controls.durationUpdate.call(player, event)); // Handle the media finishing\n\n on.call(player, player.media, 'ended', () => {\n // Show poster on end\n if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) {\n // Restart\n player.restart(); // Call pause otherwise IE11 will start playing the video again\n\n player.pause();\n }\n }); // Check for buffer progress\n\n on.call(player, player.media, 'progress playing seeking seeked', event => controls.updateProgress.call(player, event)); // Handle volume changes\n\n on.call(player, player.media, 'volumechange', event => controls.updateVolume.call(player, event)); // Handle play/pause\n\n on.call(player, player.media, 'playing play pause ended emptied timeupdate', event => ui.checkPlaying.call(player, event)); // Loading state\n\n on.call(player, player.media, 'waiting canplay seeked playing', event => ui.checkLoading.call(player, event)); // Click video\n\n if (player.supported.ui && player.config.clickToPlay && !player.isAudio) {\n // Re-fetch the wrapper\n const wrapper = getElement.call(player, `.${player.config.classNames.video}`); // Bail if there's no wrapper (this should never happen)\n\n if (!is.element(wrapper)) {\n return;\n } // On click play, pause or restart\n\n\n on.call(player, elements.container, 'click', event => {\n const targets = [elements.container, wrapper]; // Ignore if click if not container or in video wrapper\n\n if (!targets.includes(event.target) && !wrapper.contains(event.target)) {\n return;\n } // Touch devices will just show controls (if hidden)\n\n\n if (player.touch && player.config.hideControls) {\n return;\n }\n\n if (player.ended) {\n this.proxy(event, player.restart, 'restart');\n this.proxy(event, () => {\n silencePromise(player.play());\n }, 'play');\n } else {\n this.proxy(event, () => {\n silencePromise(player.togglePlay());\n }, 'play');\n }\n });\n } // Disable right click\n\n\n if (player.supported.ui && player.config.disableContextMenu) {\n on.call(player, elements.wrapper, 'contextmenu', event => {\n event.preventDefault();\n }, false);\n } // Volume change\n\n\n on.call(player, player.media, 'volumechange', () => {\n // Save to storage\n player.storage.set({\n volume: player.volume,\n muted: player.muted\n });\n }); // Speed change\n\n on.call(player, player.media, 'ratechange', () => {\n // Update UI\n controls.updateSetting.call(player, 'speed'); // Save to storage\n\n player.storage.set({\n speed: player.speed\n });\n }); // Quality change\n\n on.call(player, player.media, 'qualitychange', event => {\n // Update UI\n controls.updateSetting.call(player, 'quality', null, event.detail.quality);\n }); // Update download link when ready and if quality changes\n\n on.call(player, player.media, 'ready qualitychange', () => {\n controls.setDownloadUrl.call(player);\n }); // Proxy events to container\n // Bubble up key events for Edge\n\n const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' ');\n on.call(player, player.media, proxyEvents, event => {\n let {\n detail = {}\n } = event; // Get error details from media\n\n if (event.type === 'error') {\n detail = player.media.error;\n }\n\n triggerEvent.call(player, elements.container, event.type, true, detail);\n });\n });\n\n _defineProperty$1(this, \"proxy\", (event, defaultHandler, customHandlerKey) => {\n const {\n player\n } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n let returned = true; // Execute custom handler\n\n if (hasCustomHandler) {\n returned = customHandler.call(player, event);\n } // Only call default handler if not prevented in custom handler\n\n\n if (returned !== false && is.function(defaultHandler)) {\n defaultHandler.call(player, event);\n }\n });\n\n _defineProperty$1(this, \"bind\", (element, type, defaultHandler, customHandlerKey, passive = true) => {\n const {\n player\n } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n on.call(player, element, type, event => this.proxy(event, defaultHandler, customHandlerKey), passive && !hasCustomHandler);\n });\n\n _defineProperty$1(this, \"controls\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player; // IE doesn't support input event, so we fallback to change\n\n const inputEvent = browser.isIE ? 'change' : 'input'; // Play/pause toggle\n\n if (elements.buttons.play) {\n Array.from(elements.buttons.play).forEach(button => {\n this.bind(button, 'click', () => {\n silencePromise(player.togglePlay());\n }, 'play');\n });\n } // Pause\n\n\n this.bind(elements.buttons.restart, 'click', player.restart, 'restart'); // Rewind\n\n this.bind(elements.buttons.rewind, 'click', () => {\n // Record seek time so we can prevent hiding controls for a few seconds after rewind\n player.lastSeekTime = Date.now();\n player.rewind();\n }, 'rewind'); // Rewind\n\n this.bind(elements.buttons.fastForward, 'click', () => {\n // Record seek time so we can prevent hiding controls for a few seconds after fast forward\n player.lastSeekTime = Date.now();\n player.forward();\n }, 'fastForward'); // Mute toggle\n\n this.bind(elements.buttons.mute, 'click', () => {\n player.muted = !player.muted;\n }, 'mute'); // Captions toggle\n\n this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions()); // Download\n\n this.bind(elements.buttons.download, 'click', () => {\n triggerEvent.call(player, player.media, 'download');\n }, 'download'); // Fullscreen toggle\n\n this.bind(elements.buttons.fullscreen, 'click', () => {\n player.fullscreen.toggle();\n }, 'fullscreen'); // Picture-in-Picture\n\n this.bind(elements.buttons.pip, 'click', () => {\n player.pip = 'toggle';\n }, 'pip'); // Airplay\n\n this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay'); // Settings menu - click toggle\n\n this.bind(elements.buttons.settings, 'click', event => {\n // Prevent the document click listener closing the menu\n event.stopPropagation();\n event.preventDefault();\n controls.toggleMenu.call(player, event);\n }, null, false); // Can't be passive as we're preventing default\n // Settings menu - keyboard toggle\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n\n this.bind(elements.buttons.settings, 'keyup', event => {\n const code = event.which; // We only care about space and return\n\n if (![13, 32].includes(code)) {\n return;\n } // Because return triggers a click anyway, all we need to do is set focus\n\n\n if (code === 13) {\n controls.focusFirstMenuItem.call(player, null, true);\n return;\n } // Prevent scroll\n\n\n event.preventDefault(); // Prevent playing video (Firefox)\n\n event.stopPropagation(); // Toggle menu\n\n controls.toggleMenu.call(player, event);\n }, null, false // Can't be passive as we're preventing default\n ); // Escape closes menu\n\n this.bind(elements.settings.menu, 'keydown', event => {\n if (event.which === 27) {\n controls.toggleMenu.call(player, event);\n }\n }); // Set range input alternative \"value\", which matches the tooltip time (#954)\n\n this.bind(elements.inputs.seek, 'mousedown mousemove', event => {\n const rect = elements.progress.getBoundingClientRect();\n const percent = 100 / rect.width * (event.pageX - rect.left);\n event.currentTarget.setAttribute('seek-value', percent);\n }); // Pause while seeking\n\n this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', event => {\n const seek = event.currentTarget;\n const code = event.keyCode ? event.keyCode : event.which;\n const attribute = 'play-on-seeked';\n\n if (is.keyboardEvent(event) && code !== 39 && code !== 37) {\n return;\n } // Record seek time so we can prevent hiding controls for a few seconds after seek\n\n\n player.lastSeekTime = Date.now(); // Was playing before?\n\n const play = seek.hasAttribute(attribute); // Done seeking\n\n const done = ['mouseup', 'touchend', 'keyup'].includes(event.type); // If we're done seeking and it was playing, resume playback\n\n if (play && done) {\n seek.removeAttribute(attribute);\n silencePromise(player.play());\n } else if (!done && player.playing) {\n seek.setAttribute(attribute, '');\n player.pause();\n }\n }); // Fix range inputs on iOS\n // Super weird iOS bug where after you interact with an <input type=\"range\">,\n // it takes over further interactions on the page. This is a hack\n\n if (browser.isIos) {\n const inputs = getElements.call(player, 'input[type=\"range\"]');\n Array.from(inputs).forEach(input => this.bind(input, inputEvent, event => repaint(event.target)));\n } // Seek\n\n\n this.bind(elements.inputs.seek, inputEvent, event => {\n const seek = event.currentTarget; // If it exists, use seek-value instead of \"value\" for consistency with tooltip time (#954)\n\n let seekTo = seek.getAttribute('seek-value');\n\n if (is.empty(seekTo)) {\n seekTo = seek.value;\n }\n\n seek.removeAttribute('seek-value');\n player.currentTime = seekTo / seek.max * player.duration;\n }, 'seek'); // Seek tooltip\n\n this.bind(elements.progress, 'mouseenter mouseleave mousemove', event => controls.updateSeekTooltip.call(player, event)); // Preview thumbnails plugin\n // TODO: Really need to work on some sort of plug-in wide event bus or pub-sub for this\n\n this.bind(elements.progress, 'mousemove touchmove', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startMove(event);\n }\n }); // Hide thumbnail preview - on mouse click, mouse leave, and video play/seek. All four are required, e.g., for buffering\n\n this.bind(elements.progress, 'mouseleave touchend click', () => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endMove(false, true);\n }\n }); // Show scrubbing preview\n\n this.bind(elements.progress, 'mousedown touchstart', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startScrubbing(event);\n }\n });\n this.bind(elements.progress, 'mouseup touchend', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endScrubbing(event);\n }\n }); // Polyfill for lower fill in <input type=\"range\"> for webkit\n\n if (browser.isWebkit) {\n Array.from(getElements.call(player, 'input[type=\"range\"]')).forEach(element => {\n this.bind(element, 'input', event => controls.updateRangeFill.call(player, event.target));\n });\n } // Current time invert\n // Only if one time element is used for both currentTime and duration\n\n\n if (player.config.toggleInvert && !is.element(elements.display.duration)) {\n this.bind(elements.display.currentTime, 'click', () => {\n // Do nothing if we're at the start\n if (player.currentTime === 0) {\n return;\n }\n\n player.config.invertTime = !player.config.invertTime;\n controls.timeUpdate.call(player);\n });\n } // Volume\n\n\n this.bind(elements.inputs.volume, inputEvent, event => {\n player.volume = event.target.value;\n }, 'volume'); // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting)\n\n this.bind(elements.controls, 'mouseenter mouseleave', event => {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }); // Also update controls.hover state for any non-player children of fullscreen element (as above)\n\n if (elements.fullscreen) {\n Array.from(elements.fullscreen.children).filter(c => !c.contains(elements.container)).forEach(child => {\n this.bind(child, 'mouseenter mouseleave', event => {\n if (elements.controls) {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }\n });\n });\n } // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting)\n\n\n this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', event => {\n elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type);\n }); // Show controls when they receive focus (e.g., when using keyboard tab key)\n\n this.bind(elements.controls, 'focusin', () => {\n const {\n config,\n timers\n } = player; // Skip transition to prevent focus from scrolling the parent element\n\n toggleClass(elements.controls, config.classNames.noTransition, true); // Toggle\n\n ui.toggleControls.call(player, true); // Restore transition\n\n setTimeout(() => {\n toggleClass(elements.controls, config.classNames.noTransition, false);\n }, 0); // Delay a little more for mouse users\n\n const delay = this.touch ? 3000 : 4000; // Clear timer\n\n clearTimeout(timers.controls); // Hide again after delay\n\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n }); // Mouse wheel for volume\n\n this.bind(elements.inputs.volume, 'wheel', event => {\n // Detect \"natural\" scroll - suppored on OS X Safari only\n // Other browsers on OS X will be inverted until support improves\n const inverted = event.webkitDirectionInvertedFromDevice; // Get delta from event. Invert if `inverted` is true\n\n const [x, y] = [event.deltaX, -event.deltaY].map(value => inverted ? -value : value); // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta)\n\n const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y); // Change the volume by 2%\n\n player.increaseVolume(direction / 50); // Don't break page scrolling at max and min\n\n const {\n volume\n } = player.media;\n\n if (direction === 1 && volume < 1 || direction === -1 && volume > 0) {\n event.preventDefault();\n }\n }, 'volume', false);\n });\n\n this.player = _player;\n this.lastKey = null;\n this.focusTimer = null;\n this.lastKeyDown = null;\n this.handleKey = this.handleKey.bind(this);\n this.toggleMenu = this.toggleMenu.bind(this);\n this.setTabFocus = this.setTabFocus.bind(this);\n this.firstTouch = this.firstTouch.bind(this);\n } // Handle key presses\n\n\n handleKey(event) {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n const code = event.keyCode ? event.keyCode : event.which;\n const pressed = event.type === 'keydown';\n const repeat = pressed && code === this.lastKey; // Bail if a modifier key is set\n\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {\n return;\n } // If the event is bubbled from the media element\n // Firefox doesn't get the keycode for whatever reason\n\n\n if (!is.number(code)) {\n return;\n } // Seek by the number keys\n\n\n const seekByKey = () => {\n // Divide the max duration into 10th's and times by the number value\n player.currentTime = player.duration / 10 * (code - 48);\n }; // Handle the key on keydown\n // Reset on keyup\n\n\n if (pressed) {\n // Check focused element\n // and if the focused element is not editable (e.g. text input)\n // and any that accept key input http://webaim.org/techniques/keyboard/\n const focused = document.activeElement;\n\n if (is.element(focused)) {\n const {\n editable\n } = player.config.selectors;\n const {\n seek\n } = elements.inputs;\n\n if (focused !== seek && matches(focused, editable)) {\n return;\n }\n\n if (event.which === 32 && matches(focused, 'button, [role^=\"menuitem\"]')) {\n return;\n }\n } // Which keycodes should we prevent default\n\n\n const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79]; // If the code is found prevent default (e.g. prevent scrolling for arrows)\n\n if (preventDefault.includes(code)) {\n event.preventDefault();\n event.stopPropagation();\n }\n\n switch (code) {\n case 48:\n case 49:\n case 50:\n case 51:\n case 52:\n case 53:\n case 54:\n case 55:\n case 56:\n case 57:\n // 0-9\n if (!repeat) {\n seekByKey();\n }\n\n break;\n\n case 32:\n case 75:\n // Space and K key\n if (!repeat) {\n silencePromise(player.togglePlay());\n }\n\n break;\n\n case 38:\n // Arrow up\n player.increaseVolume(0.1);\n break;\n\n case 40:\n // Arrow down\n player.decreaseVolume(0.1);\n break;\n\n case 77:\n // M key\n if (!repeat) {\n player.muted = !player.muted;\n }\n\n break;\n\n case 39:\n // Arrow forward\n player.forward();\n break;\n\n case 37:\n // Arrow back\n player.rewind();\n break;\n\n case 70:\n // F key\n player.fullscreen.toggle();\n break;\n\n case 67:\n // C key\n if (!repeat) {\n player.toggleCaptions();\n }\n\n break;\n\n case 76:\n // L key\n player.loop = !player.loop;\n break;\n } // Escape is handle natively when in full screen\n // So we only need to worry about non native\n\n\n if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) {\n player.fullscreen.toggle();\n } // Store last code for next cycle\n\n\n this.lastKey = code;\n } else {\n this.lastKey = null;\n }\n } // Toggle menu\n\n\n toggleMenu(event) {\n controls.toggleMenu.call(this.player, event);\n } // Device is touch enabled\n\n\n}\n\nvar commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nfunction createCommonjsModule(fn, module) {\n\treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n}\n\nvar loadjs_umd = createCommonjsModule(function (module, exports) {\n (function (root, factory) {\n {\n module.exports = factory();\n }\n })(commonjsGlobal, function () {\n /**\n * Global dependencies.\n * @global {Object} document - DOM\n */\n var devnull = function () {},\n bundleIdCache = {},\n bundleResultCache = {},\n bundleCallbackQueue = {};\n /**\n * Subscribe to bundle load event.\n * @param {string[]} bundleIds - Bundle ids\n * @param {Function} callbackFn - The callback function\n */\n\n\n function subscribe(bundleIds, callbackFn) {\n // listify\n bundleIds = bundleIds.push ? bundleIds : [bundleIds];\n var depsNotFound = [],\n i = bundleIds.length,\n numWaiting = i,\n fn,\n bundleId,\n r,\n q; // define callback function\n\n fn = function (bundleId, pathsNotFound) {\n if (pathsNotFound.length) depsNotFound.push(bundleId);\n numWaiting--;\n if (!numWaiting) callbackFn(depsNotFound);\n }; // register callback\n\n\n while (i--) {\n bundleId = bundleIds[i]; // execute callback if in result cache\n\n r = bundleResultCache[bundleId];\n\n if (r) {\n fn(bundleId, r);\n continue;\n } // add to callback queue\n\n\n q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];\n q.push(fn);\n }\n }\n /**\n * Publish bundle load event.\n * @param {string} bundleId - Bundle id\n * @param {string[]} pathsNotFound - List of files not found\n */\n\n\n function publish(bundleId, pathsNotFound) {\n // exit if id isn't defined\n if (!bundleId) return;\n var q = bundleCallbackQueue[bundleId]; // cache result\n\n bundleResultCache[bundleId] = pathsNotFound; // exit if queue is empty\n\n if (!q) return; // empty callback queue\n\n while (q.length) {\n q[0](bundleId, pathsNotFound);\n q.splice(0, 1);\n }\n }\n /**\n * Execute callbacks.\n * @param {Object or Function} args - The callback args\n * @param {string[]} depsNotFound - List of dependencies not found\n */\n\n\n function executeCallbacks(args, depsNotFound) {\n // accept function as argument\n if (args.call) args = {\n success: args\n }; // success and error callbacks\n\n if (depsNotFound.length) (args.error || devnull)(depsNotFound);else (args.success || devnull)(args);\n }\n /**\n * Load individual file.\n * @param {string} path - The file path\n * @param {Function} callbackFn - The callback function\n */\n\n\n function loadFile(path, callbackFn, args, numTries) {\n var doc = document,\n async = args.async,\n maxTries = (args.numRetries || 0) + 1,\n beforeCallbackFn = args.before || devnull,\n pathname = path.replace(/[\\?|#].*$/, ''),\n pathStripped = path.replace(/^(css|img)!/, ''),\n isLegacyIECss,\n e;\n numTries = numTries || 0;\n\n if (/(^css!|\\.css$)/.test(pathname)) {\n // css\n e = doc.createElement('link');\n e.rel = 'stylesheet';\n e.href = pathStripped; // tag IE9+\n\n isLegacyIECss = 'hideFocus' in e; // use preload in IE Edge (to detect load errors)\n\n if (isLegacyIECss && e.relList) {\n isLegacyIECss = 0;\n e.rel = 'preload';\n e.as = 'style';\n }\n } else if (/(^img!|\\.(png|gif|jpg|svg|webp)$)/.test(pathname)) {\n // image\n e = doc.createElement('img');\n e.src = pathStripped;\n } else {\n // javascript\n e = doc.createElement('script');\n e.src = path;\n e.async = async === undefined ? true : async;\n }\n\n e.onload = e.onerror = e.onbeforeload = function (ev) {\n var result = ev.type[0]; // treat empty stylesheets as failures to get around lack of onerror\n // support in IE9-11\n\n if (isLegacyIECss) {\n try {\n if (!e.sheet.cssText.length) result = 'e';\n } catch (x) {\n // sheets objects created from load errors don't allow access to\n // `cssText` (unless error is Code:18 SecurityError)\n if (x.code != 18) result = 'e';\n }\n } // handle retries in case of load failure\n\n\n if (result == 'e') {\n // increment counter\n numTries += 1; // exit function and try again\n\n if (numTries < maxTries) {\n return loadFile(path, callbackFn, args, numTries);\n }\n } else if (e.rel == 'preload' && e.as == 'style') {\n // activate preloaded stylesheets\n return e.rel = 'stylesheet'; // jshint ignore:line\n } // execute callback\n\n\n callbackFn(path, result, ev.defaultPrevented);\n }; // add to document (unless callback returns `false`)\n\n\n if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);\n }\n /**\n * Load multiple files.\n * @param {string[]} paths - The file paths\n * @param {Function} callbackFn - The callback function\n */\n\n\n function loadFiles(paths, callbackFn, args) {\n // listify paths\n paths = paths.push ? paths : [paths];\n var numWaiting = paths.length,\n x = numWaiting,\n pathsNotFound = [],\n fn,\n i; // define callback function\n\n fn = function (path, result, defaultPrevented) {\n // handle error\n if (result == 'e') pathsNotFound.push(path); // handle beforeload event. If defaultPrevented then that means the load\n // will be blocked (ex. Ghostery/ABP on Safari)\n\n if (result == 'b') {\n if (defaultPrevented) pathsNotFound.push(path);else return;\n }\n\n numWaiting--;\n if (!numWaiting) callbackFn(pathsNotFound);\n }; // load scripts\n\n\n for (i = 0; i < x; i++) loadFile(paths[i], fn, args);\n }\n /**\n * Initiate script load and register bundle.\n * @param {(string|string[])} paths - The file paths\n * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success\n * callback or (3) object literal with success/error arguments, numRetries,\n * etc.\n * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object\n * literal with success/error arguments, numRetries, etc.\n */\n\n\n function loadjs(paths, arg1, arg2) {\n var bundleId, args; // bundleId (if string)\n\n if (arg1 && arg1.trim) bundleId = arg1; // args (default is {})\n\n args = (bundleId ? arg2 : arg1) || {}; // throw error if bundle is already defined\n\n if (bundleId) {\n if (bundleId in bundleIdCache) {\n throw \"LoadJS\";\n } else {\n bundleIdCache[bundleId] = true;\n }\n }\n\n function loadFn(resolve, reject) {\n loadFiles(paths, function (pathsNotFound) {\n // execute callbacks\n executeCallbacks(args, pathsNotFound); // resolve Promise\n\n if (resolve) {\n executeCallbacks({\n success: resolve,\n error: reject\n }, pathsNotFound);\n } // publish bundle load event\n\n\n publish(bundleId, pathsNotFound);\n }, args);\n }\n\n if (args.returnPromise) return new Promise(loadFn);else loadFn();\n }\n /**\n * Execute callbacks when dependencies have been satisfied.\n * @param {(string|string[])} deps - List of bundle ids\n * @param {Object} args - success/error arguments\n */\n\n\n loadjs.ready = function ready(deps, args) {\n // subscribe to bundle load event\n subscribe(deps, function (depsNotFound) {\n // execute callbacks\n executeCallbacks(args, depsNotFound);\n });\n return loadjs;\n };\n /**\n * Manually satisfy bundle dependencies.\n * @param {string} bundleId - The bundle id\n */\n\n\n loadjs.done = function done(bundleId) {\n publish(bundleId, []);\n };\n /**\n * Reset loadjs dependencies statuses\n */\n\n\n loadjs.reset = function reset() {\n bundleIdCache = {};\n bundleResultCache = {};\n bundleCallbackQueue = {};\n };\n /**\n * Determine if bundle has already been defined\n * @param String} bundleId - The bundle id\n */\n\n\n loadjs.isDefined = function isDefined(bundleId) {\n return bundleId in bundleIdCache;\n }; // export\n\n\n return loadjs;\n });\n});\n\n// ==========================================================================\nfunction loadScript(url) {\n return new Promise((resolve, reject) => {\n loadjs_umd(url, {\n success: resolve,\n error: reject\n });\n });\n}\n\n// ==========================================================================\n\nfunction parseId$1(url) {\n if (is.empty(url)) {\n return null;\n }\n\n if (is.number(Number(url))) {\n return url;\n }\n\n const regex = /^.*(vimeo.com\\/|video\\/)(\\d+).*/;\n return url.match(regex) ? RegExp.$2 : url;\n} // Try to extract a hash for private videos from the URL\n\n\nfunction parseHash(url) {\n /* This regex matches a hexadecimal hash if given in any of these forms:\n * - [https://player.]vimeo.com/video/{id}/{hash}[?params]\n * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms]\n * - [https://player.]vimeo.com/video/{id}?[params]&h={hash}\n * - video/{id}/{hash}\n * If matched, the hash is available in the named group `hash`\n */\n const regex = /^.*(?:vimeo.com\\/|video\\/)(?:\\d+)(?:\\?.*&*h=|\\/)+(?<hash>[\\d,a-f]+)/;\n const found = url.match(regex);\n return found ? found.groups.hash : null;\n} // Set playback state and trigger change (only on actual change)\n\n\nfunction assurePlaybackState$1(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nconst vimeo = {\n setup() {\n const player = this; // Add embed class for responsive\n\n toggleClass(player.elements.wrapper, player.config.classNames.embed, true); // Set speed options from config\n\n player.options.speed = player.config.speed.options; // Set intial ratio\n\n setAspectRatio.call(player); // Load the SDK if not already\n\n if (!is.object(window.Vimeo)) {\n loadScript(player.config.urls.vimeo.sdk).then(() => {\n vimeo.ready.call(player);\n }).catch(error => {\n player.debug.warn('Vimeo SDK (player.js) failed to load', error);\n });\n } else {\n vimeo.ready.call(player);\n }\n },\n\n // API Ready\n ready() {\n const player = this;\n const config = player.config.vimeo;\n const {\n premium,\n referrerPolicy,\n ...frameParams\n } = config; // Get the source URL or ID\n\n let source = player.media.getAttribute('src');\n let hash = ''; // Get from <div> if needed\n\n if (is.empty(source)) {\n source = player.media.getAttribute(player.config.attributes.embed.id); // hash can also be set as attribute on the <div>\n\n hash = player.media.getAttribute(player.config.attributes.embed.hash);\n } else {\n hash = parseHash(source);\n }\n\n const hashParam = hash ? {\n h: hash\n } : {}; // If the owner has a pro or premium account then we can hide controls etc\n\n if (premium) {\n Object.assign(frameParams, {\n controls: false,\n sidedock: false\n });\n } // Get Vimeo params for the iframe\n\n\n const params = buildUrlParams({\n loop: player.config.loop.active,\n autoplay: player.autoplay,\n muted: player.muted,\n gesture: 'media',\n playsinline: !this.config.fullscreen.iosNative,\n // hash has to be added to iframe-URL\n ...hashParam,\n ...frameParams\n });\n const id = parseId$1(source); // Build an iframe\n\n const iframe = createElement('iframe');\n const src = format(player.config.urls.vimeo.iframe, id, params);\n iframe.setAttribute('src', src);\n iframe.setAttribute('allowfullscreen', '');\n iframe.setAttribute('allow', ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; ')); // Set the referrer policy if required\n\n if (!is.empty(referrerPolicy)) {\n iframe.setAttribute('referrerPolicy', referrerPolicy);\n } // Inject the package\n\n\n if (premium || !config.customControls) {\n iframe.setAttribute('data-poster', player.poster);\n player.media = replaceElement(iframe, player.media);\n } else {\n const wrapper = createElement('div', {\n class: player.config.classNames.embedContainer,\n 'data-poster': player.poster\n });\n wrapper.appendChild(iframe);\n player.media = replaceElement(wrapper, player.media);\n } // Get poster image\n\n\n if (!config.customControls) {\n fetch(format(player.config.urls.vimeo.api, src)).then(response => {\n if (is.empty(response) || !response.thumbnail_url) {\n return;\n } // Set and show poster\n\n\n ui.setPoster.call(player, response.thumbnail_url).catch(() => {});\n });\n } // Setup instance\n // https://github.com/vimeo/player.js\n\n\n player.embed = new window.Vimeo.Player(iframe, {\n autopause: player.config.autopause,\n muted: player.muted\n });\n player.media.paused = true;\n player.media.currentTime = 0; // Disable native text track rendering\n\n if (player.supported.ui) {\n player.embed.disableTextTrack();\n } // Create a faux HTML5 API using the Vimeo API\n\n\n player.media.play = () => {\n assurePlaybackState$1.call(player, true);\n return player.embed.play();\n };\n\n player.media.pause = () => {\n assurePlaybackState$1.call(player, false);\n return player.embed.pause();\n };\n\n player.media.stop = () => {\n player.pause();\n player.currentTime = 0;\n }; // Seeking\n\n\n let {\n currentTime\n } = player.media;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return currentTime;\n },\n\n set(time) {\n // Vimeo will automatically play on seek if the video hasn't been played before\n // Get current paused state and volume etc\n const {\n embed,\n media,\n paused,\n volume\n } = player;\n const restorePause = paused && !embed.hasPlayed; // Set seeking state and trigger event\n\n media.seeking = true;\n triggerEvent.call(player, media, 'seeking'); // If paused, mute until seek is complete\n\n Promise.resolve(restorePause && embed.setVolume(0)) // Seek\n .then(() => embed.setCurrentTime(time)) // Restore paused\n .then(() => restorePause && embed.pause()) // Restore volume\n .then(() => restorePause && embed.setVolume(volume)).catch(() => {// Do nothing\n });\n }\n\n }); // Playback speed\n\n let speed = player.config.speed.selected;\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return speed;\n },\n\n set(input) {\n player.embed.setPlaybackRate(input).then(() => {\n speed = input;\n triggerEvent.call(player, player.media, 'ratechange');\n }).catch(() => {\n // Cannot set Playback Rate, Video is probably not on Pro account\n player.options.speed = [1];\n });\n }\n\n }); // Volume\n\n let {\n volume\n } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n\n set(input) {\n player.embed.setVolume(input).then(() => {\n volume = input;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n }\n\n }); // Muted\n\n let {\n muted\n } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : false;\n player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => {\n muted = toggle;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n }\n\n }); // Loop\n\n let {\n loop\n } = player.config;\n Object.defineProperty(player.media, 'loop', {\n get() {\n return loop;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : player.config.loop.active;\n player.embed.setLoop(toggle).then(() => {\n loop = toggle;\n });\n }\n\n }); // Source\n\n let currentSrc;\n player.embed.getVideoUrl().then(value => {\n currentSrc = value;\n controls.setDownloadUrl.call(player);\n }).catch(error => {\n this.debug.warn(error);\n });\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return currentSrc;\n }\n\n }); // Ended\n\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n }\n\n }); // Set aspect ratio based on video size\n\n Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(dimensions => {\n const [width, height] = dimensions;\n player.embed.ratio = roundAspectRatio(width, height);\n setAspectRatio.call(this);\n }); // Set autopause\n\n player.embed.setAutopause(player.config.autopause).then(state => {\n player.config.autopause = state;\n }); // Get title\n\n player.embed.getVideoTitle().then(title => {\n player.config.title = title;\n ui.setTitle.call(this);\n }); // Get current time\n\n player.embed.getCurrentTime().then(value => {\n currentTime = value;\n triggerEvent.call(player, player.media, 'timeupdate');\n }); // Get duration\n\n player.embed.getDuration().then(value => {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }); // Get captions\n\n player.embed.getTextTracks().then(tracks => {\n player.media.textTracks = tracks;\n captions.setup.call(player);\n });\n player.embed.on('cuechange', ({\n cues = []\n }) => {\n const strippedCues = cues.map(cue => stripHTML(cue.text));\n captions.updateCues.call(player, strippedCues);\n });\n player.embed.on('loaded', () => {\n // Assure state and events are updated on autoplay\n player.embed.getPaused().then(paused => {\n assurePlaybackState$1.call(player, !paused);\n\n if (!paused) {\n triggerEvent.call(player, player.media, 'playing');\n }\n });\n\n if (is.element(player.embed.element) && player.supported.ui) {\n const frame = player.embed.element; // Fix keyboard focus issues\n // https://github.com/sampotts/plyr/issues/317\n\n frame.setAttribute('tabindex', -1);\n }\n });\n player.embed.on('bufferstart', () => {\n triggerEvent.call(player, player.media, 'waiting');\n });\n player.embed.on('bufferend', () => {\n triggerEvent.call(player, player.media, 'playing');\n });\n player.embed.on('play', () => {\n assurePlaybackState$1.call(player, true);\n triggerEvent.call(player, player.media, 'playing');\n });\n player.embed.on('pause', () => {\n assurePlaybackState$1.call(player, false);\n });\n player.embed.on('timeupdate', data => {\n player.media.seeking = false;\n currentTime = data.seconds;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n player.embed.on('progress', data => {\n player.media.buffered = data.percent;\n triggerEvent.call(player, player.media, 'progress'); // Check all loaded\n\n if (parseInt(data.percent, 10) === 1) {\n triggerEvent.call(player, player.media, 'canplaythrough');\n } // Get duration as if we do it before load, it gives an incorrect value\n // https://github.com/sampotts/plyr/issues/891\n\n\n player.embed.getDuration().then(value => {\n if (value !== player.media.duration) {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }\n });\n });\n player.embed.on('seeked', () => {\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n });\n player.embed.on('ended', () => {\n player.media.paused = true;\n triggerEvent.call(player, player.media, 'ended');\n });\n player.embed.on('error', detail => {\n player.media.error = detail;\n triggerEvent.call(player, player.media, 'error');\n }); // Rebuild UI\n\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 0);\n }\n }\n\n};\n\n// ==========================================================================\n\nfunction parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n const regex = /^.*(youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=|&v=)([^#&?]*).*/;\n return url.match(regex) ? RegExp.$2 : url;\n} // Set playback state and trigger change (only on actual change)\n\n\nfunction assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nfunction getHost(config) {\n if (config.noCookie) {\n return 'https://www.youtube-nocookie.com';\n }\n\n if (window.location.protocol === 'http:') {\n return 'http://www.youtube.com';\n } // Use YouTube's default\n\n\n return undefined;\n}\n\nconst youtube = {\n setup() {\n // Add embed class for responsive\n toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Setup API\n\n if (is.object(window.YT) && is.function(window.YT.Player)) {\n youtube.ready.call(this);\n } else {\n // Reference current global callback\n const callback = window.onYouTubeIframeAPIReady; // Set callback to process queue\n\n window.onYouTubeIframeAPIReady = () => {\n // Call global callback if set\n if (is.function(callback)) {\n callback();\n }\n\n youtube.ready.call(this);\n }; // Load the SDK\n\n\n loadScript(this.config.urls.youtube.sdk).catch(error => {\n this.debug.warn('YouTube API failed to load', error);\n });\n }\n },\n\n // Get the media title\n getTitle(videoId) {\n const url = format(this.config.urls.youtube.api, videoId);\n fetch(url).then(data => {\n if (is.object(data)) {\n const {\n title,\n height,\n width\n } = data; // Set title\n\n this.config.title = title;\n ui.setTitle.call(this); // Set aspect ratio\n\n this.embed.ratio = roundAspectRatio(width, height);\n }\n\n setAspectRatio.call(this);\n }).catch(() => {\n // Set aspect ratio\n setAspectRatio.call(this);\n });\n },\n\n // API ready\n ready() {\n const player = this;\n const config = player.config.youtube; // Ignore already setup (race condition)\n\n const currentId = player.media && player.media.getAttribute('id');\n\n if (!is.empty(currentId) && currentId.startsWith('youtube-')) {\n return;\n } // Get the source URL or ID\n\n\n let source = player.media.getAttribute('src'); // Get from <div> if needed\n\n if (is.empty(source)) {\n source = player.media.getAttribute(this.config.attributes.embed.id);\n } // Replace the <iframe> with a <div> due to YouTube API issues\n\n\n const videoId = parseId(source);\n const id = generateId(player.provider); // Replace media element\n\n const container = createElement('div', {\n id,\n 'data-poster': config.customControls ? player.poster : undefined\n });\n player.media = replaceElement(container, player.media); // Only load the poster when using custom controls\n\n if (config.customControls) {\n const posterSrc = s => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`; // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide)\n\n\n loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded\n .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3\n .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists\n .then(image => ui.setPoster.call(player, image.src)).then(src => {\n // If the image is padded, use background-size \"cover\" instead (like youtube does too with their posters)\n if (!src.includes('maxres')) {\n player.elements.poster.style.backgroundSize = 'cover';\n }\n }).catch(() => {});\n } // Setup instance\n // https://developers.google.com/youtube/iframe_api_reference\n\n\n player.embed = new window.YT.Player(player.media, {\n videoId,\n host: getHost(config),\n playerVars: extend({}, {\n // Autoplay\n autoplay: player.config.autoplay ? 1 : 0,\n // iframe interface language\n hl: player.config.hl,\n // Only show controls if not fully supported or opted out\n controls: player.supported.ui && config.customControls ? 0 : 1,\n // Disable keyboard as we handle it\n disablekb: 1,\n // Allow iOS inline playback\n playsinline: !player.config.fullscreen.iosNative ? 1 : 0,\n // Captions are flaky on YouTube\n cc_load_policy: player.captions.active ? 1 : 0,\n cc_lang_pref: player.config.captions.language,\n // Tracking for stats\n widget_referrer: window ? window.location.href : null\n }, config),\n events: {\n onError(event) {\n // YouTube may fire onError twice, so only handle it once\n if (!player.media.error) {\n const code = event.data; // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError\n\n const message = {\n 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.',\n 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.',\n 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.',\n 101: 'The owner of the requested video does not allow it to be played in embedded players.',\n 150: 'The owner of the requested video does not allow it to be played in embedded players.'\n }[code] || 'An unknown error occured';\n player.media.error = {\n code,\n message\n };\n triggerEvent.call(player, player.media, 'error');\n }\n },\n\n onPlaybackRateChange(event) {\n // Get the instance\n const instance = event.target; // Get current speed\n\n player.media.playbackRate = instance.getPlaybackRate();\n triggerEvent.call(player, player.media, 'ratechange');\n },\n\n onReady(event) {\n // Bail if onReady has already been called. See issue #1108\n if (is.function(player.media.play)) {\n return;\n } // Get the instance\n\n\n const instance = event.target; // Get the title\n\n youtube.getTitle.call(player, videoId); // Create a faux HTML5 API using the YouTube API\n\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n instance.playVideo();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n instance.pauseVideo();\n };\n\n player.media.stop = () => {\n instance.stopVideo();\n };\n\n player.media.duration = instance.getDuration();\n player.media.paused = true; // Seeking\n\n player.media.currentTime = 0;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return Number(instance.getCurrentTime());\n },\n\n set(time) {\n // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet).\n if (player.paused && !player.embed.hasPlayed) {\n player.embed.mute();\n } // Set seeking state and trigger event\n\n\n player.media.seeking = true;\n triggerEvent.call(player, player.media, 'seeking'); // Seek after events sent\n\n instance.seekTo(time);\n }\n\n }); // Playback speed\n\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return instance.getPlaybackRate();\n },\n\n set(input) {\n instance.setPlaybackRate(input);\n }\n\n }); // Volume\n\n let {\n volume\n } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n\n set(input) {\n volume = input;\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n }\n\n }); // Muted\n\n let {\n muted\n } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : muted;\n muted = toggle;\n instance[toggle ? 'mute' : 'unMute']();\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n }\n\n }); // Source\n\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return instance.getVideoUrl();\n }\n\n }); // Ended\n\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n }\n\n }); // Get available speeds\n\n const speeds = instance.getAvailablePlaybackRates(); // Filter based on config\n\n player.options.speed = speeds.filter(s => player.config.speed.options.includes(s)); // Set the tabindex to avoid focus entering iframe\n\n if (player.supported.ui && config.customControls) {\n player.media.setAttribute('tabindex', -1);\n }\n\n triggerEvent.call(player, player.media, 'timeupdate');\n triggerEvent.call(player, player.media, 'durationchange'); // Reset timer\n\n clearInterval(player.timers.buffering); // Setup buffering\n\n player.timers.buffering = setInterval(() => {\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction(); // Trigger progress only when we actually buffer something\n\n if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) {\n triggerEvent.call(player, player.media, 'progress');\n } // Set last buffer point\n\n\n player.media.lastBuffered = player.media.buffered; // Bail if we're at 100%\n\n if (player.media.buffered === 1) {\n clearInterval(player.timers.buffering); // Trigger event\n\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n }, 200); // Rebuild UI\n\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 50);\n }\n },\n\n onStateChange(event) {\n // Get the instance\n const instance = event.target; // Reset timer\n\n clearInterval(player.timers.playing);\n const seeked = player.media.seeking && [1, 2].includes(event.data);\n\n if (seeked) {\n // Unset seeking and fire seeked event\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n } // Handle events\n // -1 Unstarted\n // 0 Ended\n // 1 Playing\n // 2 Paused\n // 3 Buffering\n // 5 Video cued\n\n\n switch (event.data) {\n case -1:\n // Update scrubber\n triggerEvent.call(player, player.media, 'timeupdate'); // Get loaded % from YouTube\n\n player.media.buffered = instance.getVideoLoadedFraction();\n triggerEvent.call(player, player.media, 'progress');\n break;\n\n case 0:\n assurePlaybackState.call(player, false); // YouTube doesn't support loop for a single video, so mimick it.\n\n if (player.media.loop) {\n // YouTube needs a call to `stopVideo` before playing again\n instance.stopVideo();\n instance.playVideo();\n } else {\n triggerEvent.call(player, player.media, 'ended');\n }\n\n break;\n\n case 1:\n // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet)\n if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) {\n player.media.pause();\n } else {\n assurePlaybackState.call(player, true);\n triggerEvent.call(player, player.media, 'playing'); // Poll to get playback progress\n\n player.timers.playing = setInterval(() => {\n triggerEvent.call(player, player.media, 'timeupdate');\n }, 50); // Check duration again due to YouTube bug\n // https://github.com/sampotts/plyr/issues/374\n // https://code.google.com/p/gdata-issues/issues/detail?id=8690\n\n if (player.media.duration !== instance.getDuration()) {\n player.media.duration = instance.getDuration();\n triggerEvent.call(player, player.media, 'durationchange');\n }\n }\n\n break;\n\n case 2:\n // Restore audio (YouTube starts playing on seek if the video hasn't been played yet)\n if (!player.muted) {\n player.embed.unMute();\n }\n\n assurePlaybackState.call(player, false);\n break;\n\n case 3:\n // Trigger waiting event to add loading classes to container as the video buffers.\n triggerEvent.call(player, player.media, 'waiting');\n break;\n }\n\n triggerEvent.call(player, player.elements.container, 'statechange', false, {\n code: event.data\n });\n }\n\n }\n });\n }\n\n};\n\n// ==========================================================================\nconst media = {\n // Setup media\n setup() {\n // If there's no media, bail\n if (!this.media) {\n this.debug.warn('No media element found!');\n return;\n } // Add type class\n\n\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true); // Add provider class\n\n toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true); // Add video class for embeds\n // This will require changes if audio embeds are added\n\n if (this.isEmbed) {\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true);\n } // Inject the player wrapper\n\n\n if (this.isVideo) {\n // Create the wrapper div\n this.elements.wrapper = createElement('div', {\n class: this.config.classNames.video\n }); // Wrap the video in a container\n\n wrap(this.media, this.elements.wrapper); // Poster image container\n\n this.elements.poster = createElement('div', {\n class: this.config.classNames.poster\n });\n this.elements.wrapper.appendChild(this.elements.poster);\n }\n\n if (this.isHTML5) {\n html5.setup.call(this);\n } else if (this.isYouTube) {\n youtube.setup.call(this);\n } else if (this.isVimeo) {\n vimeo.setup.call(this);\n }\n }\n\n};\n\nconst destroy = instance => {\n // Destroy our adsManager\n if (instance.manager) {\n instance.manager.destroy();\n } // Destroy our adsManager\n\n\n if (instance.elements.displayContainer) {\n instance.elements.displayContainer.destroy();\n }\n\n instance.elements.container.remove();\n};\n\nclass Ads {\n /**\n * Ads constructor.\n * @param {Object} player\n * @return {Ads}\n */\n constructor(player) {\n _defineProperty$1(this, \"load\", () => {\n if (!this.enabled) {\n return;\n } // Check if the Google IMA3 SDK is loaded or load it ourselves\n\n\n if (!is.object(window.google) || !is.object(window.google.ima)) {\n loadScript(this.player.config.urls.googleIMA.sdk).then(() => {\n this.ready();\n }).catch(() => {\n // Script failed to load or is blocked\n this.trigger('error', new Error('Google IMA SDK failed to load'));\n });\n } else {\n this.ready();\n }\n });\n\n _defineProperty$1(this, \"ready\", () => {\n // Double check we're enabled\n if (!this.enabled) {\n destroy(this);\n } // Start ticking our safety timer. If the whole advertisement\n // thing doesn't resolve within our set time; we bail\n\n\n this.startSafetyTimer(12000, 'ready()'); // Clear the safety timer\n\n this.managerPromise.then(() => {\n this.clearSafetyTimer('onAdsManagerLoaded()');\n }); // Set listeners on the Plyr instance\n\n this.listeners(); // Setup the IMA SDK\n\n this.setupIMA();\n });\n\n _defineProperty$1(this, \"setupIMA\", () => {\n // Create the container for our advertisements\n this.elements.container = createElement('div', {\n class: this.player.config.classNames.ads\n });\n this.player.elements.container.appendChild(this.elements.container); // So we can run VPAID2\n\n google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED); // Set language\n\n google.ima.settings.setLocale(this.player.config.ads.language); // Set playback for iOS10+\n\n 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\n\n this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container, this.player.media); // Create ads loader\n\n this.loader = new google.ima.AdsLoader(this.elements.displayContainer); // Listen and respond to ads loaded and error events\n\n this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false);\n this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false); // Request video ads to be pre-loaded\n\n this.requestAds();\n });\n\n _defineProperty$1(this, \"requestAds\", () => {\n const {\n container\n } = this.player.elements;\n\n try {\n // Request video ads\n const request = new google.ima.AdsRequest();\n request.adTagUrl = this.tagUrl; // Specify the linear and nonlinear slot sizes. This helps the SDK\n // to select the correct creative if multiple are returned\n\n request.linearAdSlotWidth = container.offsetWidth;\n request.linearAdSlotHeight = container.offsetHeight;\n request.nonLinearAdSlotWidth = container.offsetWidth;\n request.nonLinearAdSlotHeight = container.offsetHeight; // We only overlay ads as we only support video.\n\n request.forceNonLinearFullSlot = false; // Mute based on current state\n\n request.setAdWillPlayMuted(!this.player.muted);\n this.loader.requestAds(request);\n } catch (error) {\n this.onAdError(error);\n }\n });\n\n _defineProperty$1(this, \"pollCountdown\", (start = false) => {\n if (!start) {\n clearInterval(this.countdownTimer);\n this.elements.container.removeAttribute('data-badge-text');\n return;\n }\n\n const update = () => {\n const time = formatTime(Math.max(this.manager.getRemainingTime(), 0));\n const label = `${i18n.get('advertisement', this.player.config)} - ${time}`;\n this.elements.container.setAttribute('data-badge-text', label);\n };\n\n this.countdownTimer = setInterval(update, 100);\n });\n\n _defineProperty$1(this, \"onAdsManagerLoaded\", event => {\n // Load could occur after a source change (race condition)\n if (!this.enabled) {\n return;\n } // Get the ads manager\n\n\n const settings = new google.ima.AdsRenderingSettings(); // Tell the SDK to save and restore content video state on our behalf\n\n settings.restoreCustomPlaybackStateOnAdBreakComplete = true;\n settings.enablePreloading = true; // The SDK is polling currentTime on the contentPlayback. And needs a duration\n // so it can determine when to start the mid- and post-roll\n\n this.manager = event.getAdsManager(this.player, settings); // Get the cue points for any mid-rolls by filtering out the pre- and post-roll\n\n this.cuePoints = this.manager.getCuePoints(); // Add listeners to the required events\n // Advertisement error events\n\n this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error)); // Advertisement regular events\n\n Object.keys(google.ima.AdEvent.Type).forEach(type => {\n this.manager.addEventListener(google.ima.AdEvent.Type[type], e => this.onAdEvent(e));\n }); // Resolve our adsManager\n\n this.trigger('loaded');\n });\n\n _defineProperty$1(this, \"addCuePoints\", () => {\n // Add advertisement cue's within the time line if available\n if (!is.empty(this.cuePoints)) {\n this.cuePoints.forEach(cuePoint => {\n if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {\n const seekElement = this.player.elements.progress;\n\n if (is.element(seekElement)) {\n const cuePercentage = 100 / this.player.duration * cuePoint;\n const cue = createElement('span', {\n class: this.player.config.classNames.cues\n });\n cue.style.left = `${cuePercentage.toString()}%`;\n seekElement.appendChild(cue);\n }\n }\n });\n }\n });\n\n _defineProperty$1(this, \"onAdEvent\", event => {\n const {\n container\n } = this.player.elements; // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)\n // don't have ad object associated\n\n const ad = event.getAd();\n const adData = event.getAdData(); // Proxy event\n\n const dispatchEvent = type => {\n triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`);\n }; // Bubble the event\n\n\n dispatchEvent(event.type);\n\n switch (event.type) {\n case google.ima.AdEvent.Type.LOADED:\n // This is the first event sent for an ad - it is possible to determine whether the\n // ad is a video ad or an overlay\n this.trigger('loaded'); // Start countdown\n\n this.pollCountdown(true);\n\n if (!ad.isLinear()) {\n // Position AdDisplayContainer correctly for overlay\n ad.width = container.offsetWidth;\n ad.height = container.offsetHeight;\n } // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex());\n // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset());\n\n\n break;\n\n case google.ima.AdEvent.Type.STARTED:\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n break;\n\n case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:\n // All ads for the current videos are done. We can now request new advertisements\n // in case the video is re-played\n // TODO: Example for what happens when a next video in a playlist would be loaded.\n // So here we load a new video when all ads are done.\n // Then we load new ads within a new adsManager. When the video\n // Is started - after - the ads are loaded, then we get ads.\n // You can also easily test cancelling and reloading by running\n // player.ads.cancel() and player.ads.play from the console I guess.\n // this.player.source = {\n // type: 'video',\n // title: 'View From A Blue Moon',\n // sources: [{\n // src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type:\n // 'video/mp4', }], poster:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks:\n // [ { kind: 'captions', label: 'English', srclang: 'en', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',\n // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ],\n // };\n // TODO: So there is still this thing where a video should only be allowed to start\n // playing when the IMA SDK is ready or has failed\n if (this.player.ended) {\n this.loadAds();\n } else {\n // The SDK won't allow new ads to be called without receiving a contentComplete()\n this.loader.contentComplete();\n }\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:\n // This event indicates the ad has started - the video player can adjust the UI,\n // for example display a pause button and remaining time. Fired when content should\n // be paused. This usually happens right before an ad is about to cover the content\n this.pauseContent();\n break;\n\n case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:\n // This event indicates the ad has finished - the video player can perform\n // appropriate UI actions, such as removing the timer for remaining time detection.\n // Fired when content should be resumed. This usually happens when an ad finishes\n // or collapses\n this.pollCountdown();\n this.resumeContent();\n break;\n\n case google.ima.AdEvent.Type.LOG:\n if (adData.adError) {\n this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);\n }\n\n break;\n }\n });\n\n _defineProperty$1(this, \"onAdError\", event => {\n this.cancel();\n this.player.debug.warn('Ads error', event);\n });\n\n _defineProperty$1(this, \"listeners\", () => {\n const {\n container\n } = this.player.elements;\n let time;\n this.player.on('canplay', () => {\n this.addCuePoints();\n });\n this.player.on('ended', () => {\n this.loader.contentComplete();\n });\n this.player.on('timeupdate', () => {\n time = this.player.currentTime;\n });\n this.player.on('seeked', () => {\n const seekedTime = this.player.currentTime;\n\n if (is.empty(this.cuePoints)) {\n return;\n }\n\n this.cuePoints.forEach((cuePoint, index) => {\n if (time < cuePoint && cuePoint < seekedTime) {\n this.manager.discardAdBreak();\n this.cuePoints.splice(index, 1);\n }\n });\n }); // Listen to the resizing of the window. And resize ad accordingly\n // TODO: eventually implement ResizeObserver\n\n window.addEventListener('resize', () => {\n if (this.manager) {\n this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n }\n });\n });\n\n _defineProperty$1(this, \"play\", () => {\n const {\n container\n } = this.player.elements;\n\n if (!this.managerPromise) {\n this.resumeContent();\n } // Play the requested advertisement whenever the adsManager is ready\n\n\n this.managerPromise.then(() => {\n // Set volume to match player\n this.manager.setVolume(this.player.volume); // Initialize the container. Must be done via a user action on mobile devices\n\n this.elements.displayContainer.initialize();\n\n try {\n if (!this.initialized) {\n // Initialize the ads manager. Ad rules playlist will start at this time\n this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will\n // start at this time; the call will be ignored for ad rules\n\n this.manager.start();\n }\n\n this.initialized = true;\n } catch (adError) {\n // An error may be thrown if there was a problem with the\n // VAST response\n this.onAdError(adError);\n }\n }).catch(() => {});\n });\n\n _defineProperty$1(this, \"resumeContent\", () => {\n // Hide the advertisement container\n this.elements.container.style.zIndex = ''; // Ad is stopped\n\n this.playing = false; // Play video\n\n silencePromise(this.player.media.play());\n });\n\n _defineProperty$1(this, \"pauseContent\", () => {\n // Show the advertisement container\n this.elements.container.style.zIndex = 3; // Ad is playing\n\n this.playing = true; // Pause our video.\n\n this.player.media.pause();\n });\n\n _defineProperty$1(this, \"cancel\", () => {\n // Pause our video\n if (this.initialized) {\n this.resumeContent();\n } // Tell our instance that we're done for now\n\n\n this.trigger('error'); // Re-create our adsManager\n\n this.loadAds();\n });\n\n _defineProperty$1(this, \"loadAds\", () => {\n // Tell our adsManager to go bye bye\n this.managerPromise.then(() => {\n // Destroy our adsManager\n if (this.manager) {\n this.manager.destroy();\n } // Re-set our adsManager promises\n\n\n this.managerPromise = new Promise(resolve => {\n this.on('loaded', resolve);\n this.player.debug.log(this.manager);\n }); // Now that the manager has been destroyed set it to also be un-initialized\n\n this.initialized = false; // Now request some new advertisements\n\n this.requestAds();\n }).catch(() => {});\n });\n\n _defineProperty$1(this, \"trigger\", (event, ...args) => {\n const handlers = this.events[event];\n\n if (is.array(handlers)) {\n handlers.forEach(handler => {\n if (is.function(handler)) {\n handler.apply(this, args);\n }\n });\n }\n });\n\n _defineProperty$1(this, \"on\", (event, callback) => {\n if (!is.array(this.events[event])) {\n this.events[event] = [];\n }\n\n this.events[event].push(callback);\n return this;\n });\n\n _defineProperty$1(this, \"startSafetyTimer\", (time, from) => {\n this.player.debug.log(`Safety timer invoked from: ${from}`);\n this.safetyTimer = setTimeout(() => {\n this.cancel();\n this.clearSafetyTimer('startSafetyTimer()');\n }, time);\n });\n\n _defineProperty$1(this, \"clearSafetyTimer\", from => {\n if (!is.nullOrUndefined(this.safetyTimer)) {\n this.player.debug.log(`Safety timer cleared from: ${from}`);\n clearTimeout(this.safetyTimer);\n this.safetyTimer = null;\n }\n });\n\n this.player = player;\n this.config = player.config.ads;\n this.playing = false;\n this.initialized = false;\n this.elements = {\n container: null,\n displayContainer: null\n };\n this.manager = null;\n this.loader = null;\n this.cuePoints = null;\n this.events = {};\n this.safetyTimer = null;\n this.countdownTimer = null; // Setup a promise to resolve when the IMA manager is ready\n\n this.managerPromise = new Promise((resolve, reject) => {\n // The ad is loaded and ready\n this.on('loaded', resolve); // Ads failed\n\n this.on('error', reject);\n });\n this.load();\n }\n\n get enabled() {\n const {\n config\n } = this;\n return this.player.isHTML5 && this.player.isVideo && config.enabled && (!is.empty(config.publisherId) || is.url(config.tagUrl));\n }\n /**\n * Load the IMA SDK\n */\n\n\n // Build the tag URL\n get tagUrl() {\n const {\n config\n } = this;\n\n if (is.url(config.tagUrl)) {\n return config.tagUrl;\n }\n\n const params = {\n AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',\n AV_CHANNELID: '5a0458dc28a06145e4519d21',\n AV_URL: window.location.hostname,\n cb: Date.now(),\n AV_WIDTH: 640,\n AV_HEIGHT: 480,\n AV_CDIM2: config.publisherId\n };\n const base = 'https://go.aniview.com/api/adserver6/vast/';\n return `${base}?${buildUrlParams(params)}`;\n }\n /**\n * In order for the SDK to display ads for our video, we need to tell it where to put them,\n * so here we define our ad container. This div is set up to render on top of the video player.\n * Using the code below, we tell the SDK to render ads within that div. We also provide a\n * handle to the content video player - the SDK will poll the current time of our player to\n * properly place mid-rolls. After we create the ad display container, we initialize it. On\n * mobile devices, this initialization is done as the result of a user action.\n */\n\n\n}\n\nconst parseVtt = vttDataString => {\n const processedList = [];\n const frames = vttDataString.split(/\\r\\n\\r\\n|\\n\\n|\\r\\r/);\n frames.forEach(frame => {\n const result = {};\n const lines = frame.split(/\\r\\n|\\n|\\r/);\n lines.forEach(line => {\n if (!is.number(result.startTime)) {\n // The line with start and end times on it is the first line of interest\n 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\n\n if (matchTimes) {\n result.startTime = Number(matchTimes[1] || 0) * 60 * 60 + Number(matchTimes[2]) * 60 + Number(matchTimes[3]) + Number(`0.${matchTimes[4]}`);\n result.endTime = Number(matchTimes[6] || 0) * 60 * 60 + Number(matchTimes[7]) * 60 + Number(matchTimes[8]) + Number(`0.${matchTimes[9]}`);\n }\n } else if (!is.empty(line.trim()) && is.empty(result.text)) {\n // If we already have the startTime, then we're definitely up to the text line(s)\n const lineSplit = line.trim().split('#xywh=');\n [result.text] = lineSplit; // If there's content in lineSplit[1], then we have sprites. If not, then it's just one frame per image\n\n if (lineSplit[1]) {\n [result.x, result.y, result.w, result.h] = lineSplit[1].split(',');\n }\n }\n });\n\n if (result.text) {\n processedList.push(result);\n }\n });\n return processedList;\n};\n/**\n * Preview thumbnails for seek hover and scrubbing\n * Seeking: Hover over the seek bar (desktop only): shows a small preview container above the seek bar\n * 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\n *\n * Notes:\n * - 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\n * - 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\n * - 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\n */\n\n\nconst fitRatio = (ratio, outer) => {\n const targetRatio = outer.width / outer.height;\n const result = {};\n\n if (ratio > targetRatio) {\n result.width = outer.width;\n result.height = 1 / ratio * outer.width;\n } else {\n result.height = outer.height;\n result.width = ratio * outer.height;\n }\n\n return result;\n};\n\nclass PreviewThumbnails {\n /**\n * PreviewThumbnails constructor.\n * @param {Plyr} player\n * @return {PreviewThumbnails}\n */\n constructor(player) {\n _defineProperty$1(this, \"load\", () => {\n // Toggle the regular seek tooltip\n if (this.player.elements.display.seekTooltip) {\n this.player.elements.display.seekTooltip.hidden = this.enabled;\n }\n\n if (!this.enabled) {\n return;\n }\n\n this.getThumbnails().then(() => {\n if (!this.enabled) {\n return;\n } // Render DOM elements\n\n\n this.render(); // Check to see if thumb container size was specified manually in CSS\n\n this.determineContainerAutoSizing();\n this.loaded = true;\n });\n });\n\n _defineProperty$1(this, \"getThumbnails\", () => {\n return new Promise(resolve => {\n const {\n src\n } = this.player.config.previewThumbnails;\n\n if (is.empty(src)) {\n throw new Error('Missing previewThumbnails.src config attribute');\n } // Resolve promise\n\n\n const sortAndResolve = () => {\n // Sort smallest to biggest (e.g., [120p, 480p, 1080p])\n this.thumbnails.sort((x, y) => x.height - y.height);\n this.player.debug.log('Preview thumbnails', this.thumbnails);\n resolve();\n }; // Via callback()\n\n\n if (is.function(src)) {\n src(thumbnails => {\n this.thumbnails = thumbnails;\n sortAndResolve();\n });\n } // VTT urls\n else {\n // If string, convert into single-element list\n 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\n\n const promises = urls.map(u => this.getThumbnail(u)); // Resolve\n\n Promise.all(promises).then(sortAndResolve);\n }\n });\n });\n\n _defineProperty$1(this, \"getThumbnail\", url => {\n return new Promise(resolve => {\n fetch(url).then(response => {\n const thumbnail = {\n frames: parseVtt(response),\n height: null,\n urlPrefix: ''\n }; // If the URLs don't start with '/', then we need to set their relative path to be the location of the VTT file\n // If the URLs do start with '/', then they obviously don't need a prefix, so it will remain blank\n // If the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file\n\n if (!thumbnail.frames[0].text.startsWith('/') && !thumbnail.frames[0].text.startsWith('http://') && !thumbnail.frames[0].text.startsWith('https://')) {\n thumbnail.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1);\n } // Download the first frame, so that we can determine/set the height of this thumbnailsDef\n\n\n const tempImage = new Image();\n\n tempImage.onload = () => {\n thumbnail.height = tempImage.naturalHeight;\n thumbnail.width = tempImage.naturalWidth;\n this.thumbnails.push(thumbnail);\n resolve();\n };\n\n tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;\n });\n });\n });\n\n _defineProperty$1(this, \"startMove\", event => {\n if (!this.loaded) {\n return;\n }\n\n if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {\n return;\n } // Wait until media has a duration\n\n\n if (!this.player.media.duration) {\n return;\n }\n\n if (event.type === 'touchmove') {\n // Calculate seek hover position as approx video seconds\n this.seekTime = this.player.media.duration * (this.player.elements.inputs.seek.value / 100);\n } else {\n // Calculate seek hover position as approx video seconds\n const clientRect = this.player.elements.progress.getBoundingClientRect();\n const percentage = 100 / clientRect.width * (event.pageX - clientRect.left);\n this.seekTime = this.player.media.duration * (percentage / 100);\n\n if (this.seekTime < 0) {\n // The mousemove fires for 10+px out to the left\n this.seekTime = 0;\n }\n\n if (this.seekTime > this.player.media.duration - 1) {\n // Took 1 second off the duration for safety, because different players can disagree on the real duration of a video\n this.seekTime = this.player.media.duration - 1;\n }\n\n this.mousePosX = event.pageX; // Set time text inside image container\n\n this.elements.thumb.time.innerText = formatTime(this.seekTime);\n } // Download and show image\n\n\n this.showImageAtCurrentTime();\n });\n\n _defineProperty$1(this, \"endMove\", () => {\n this.toggleThumbContainer(false, true);\n });\n\n _defineProperty$1(this, \"startScrubbing\", event => {\n // Only act on left mouse button (0), or touch device (event.button does not exist or is false)\n if (is.nullOrUndefined(event.button) || event.button === false || event.button === 0) {\n this.mouseDown = true; // Wait until media has a duration\n\n if (this.player.media.duration) {\n this.toggleScrubbingContainer(true);\n this.toggleThumbContainer(false, true); // Download and show image\n\n this.showImageAtCurrentTime();\n }\n }\n });\n\n _defineProperty$1(this, \"endScrubbing\", () => {\n this.mouseDown = false; // Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview\n\n if (Math.ceil(this.lastTime) === Math.ceil(this.player.media.currentTime)) {\n // The video was already seeked/loaded at the chosen time - hide immediately\n this.toggleScrubbingContainer(false);\n } else {\n // The video hasn't seeked yet. Wait for that\n once.call(this.player, this.player.media, 'timeupdate', () => {\n // Re-check mousedown - we might have already started scrubbing again\n if (!this.mouseDown) {\n this.toggleScrubbingContainer(false);\n }\n });\n }\n });\n\n _defineProperty$1(this, \"listeners\", () => {\n // 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\n this.player.on('play', () => {\n this.toggleThumbContainer(false, true);\n });\n this.player.on('seeked', () => {\n this.toggleThumbContainer(false);\n });\n this.player.on('timeupdate', () => {\n this.lastTime = this.player.media.currentTime;\n });\n });\n\n _defineProperty$1(this, \"render\", () => {\n // Create HTML element: plyr__preview-thumbnail-container\n this.elements.thumb.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.thumbContainer\n }); // Wrapper for the image for styling\n\n this.elements.thumb.imageContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.imageContainer\n });\n this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer); // Create HTML element, parent+span: time text (e.g., 01:32:00)\n\n const timeContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.timeContainer\n });\n this.elements.thumb.time = createElement('span', {}, '00:00');\n timeContainer.appendChild(this.elements.thumb.time);\n this.elements.thumb.container.appendChild(timeContainer); // Inject the whole thumb\n\n if (is.element(this.player.elements.progress)) {\n this.player.elements.progress.appendChild(this.elements.thumb.container);\n } // Create HTML element: plyr__preview-scrubbing-container\n\n\n this.elements.scrubbing.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.scrubbingContainer\n });\n this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);\n });\n\n _defineProperty$1(this, \"destroy\", () => {\n if (this.elements.thumb.container) {\n this.elements.thumb.container.remove();\n }\n\n if (this.elements.scrubbing.container) {\n this.elements.scrubbing.container.remove();\n }\n });\n\n _defineProperty$1(this, \"showImageAtCurrentTime\", () => {\n if (this.mouseDown) {\n this.setScrubbingContainerSize();\n } else {\n this.setThumbContainerSizeAndPos();\n } // Find the desired thumbnail index\n // TODO: Handle a video longer than the thumbs where thumbNum is null\n\n\n const thumbNum = this.thumbnails[0].frames.findIndex(frame => this.seekTime >= frame.startTime && this.seekTime <= frame.endTime);\n const hasThumb = thumbNum >= 0;\n let qualityIndex = 0; // Show the thumb container if we're not scrubbing\n\n if (!this.mouseDown) {\n this.toggleThumbContainer(hasThumb);\n } // No matching thumb found\n\n\n if (!hasThumb) {\n return;\n } // Check to see if we've already downloaded higher quality versions of this image\n\n\n this.thumbnails.forEach((thumbnail, index) => {\n if (this.loadedImages.includes(thumbnail.frames[thumbNum].text)) {\n qualityIndex = index;\n }\n }); // Only proceed if either thumbnum or thumbfilename has changed\n\n if (thumbNum !== this.showingThumb) {\n this.showingThumb = thumbNum;\n this.loadImage(qualityIndex);\n }\n });\n\n _defineProperty$1(this, \"loadImage\", (qualityIndex = 0) => {\n const thumbNum = this.showingThumb;\n const thumbnail = this.thumbnails[qualityIndex];\n const {\n urlPrefix\n } = thumbnail;\n const frame = thumbnail.frames[thumbNum];\n const thumbFilename = thumbnail.frames[thumbNum].text;\n const thumbUrl = urlPrefix + thumbFilename;\n\n if (!this.currentImageElement || this.currentImageElement.dataset.filename !== thumbFilename) {\n // If we're already loading a previous image, remove its onload handler - we don't want it to load after this one\n // Only do this if not using sprites. Without sprites we really want to show as many images as possible, as a best-effort\n if (this.loadingImage && this.usingSprites) {\n this.loadingImage.onload = null;\n } // We're building and adding a new image. In other implementations of similar functionality (YouTube), background image\n // is instead used. But this causes issues with larger images in Firefox and Safari - switching between background\n // images causes a flicker. Putting a new image over the top does not\n\n\n const previewImage = new Image();\n previewImage.src = thumbUrl;\n previewImage.dataset.index = thumbNum;\n previewImage.dataset.filename = thumbFilename;\n this.showingThumbFilename = thumbFilename;\n 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...\n\n previewImage.onload = () => this.showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, true);\n\n this.loadingImage = previewImage;\n this.removeOldImages(previewImage);\n } else {\n // Update the existing image\n this.showImage(this.currentImageElement, frame, qualityIndex, thumbNum, thumbFilename, false);\n this.currentImageElement.dataset.index = thumbNum;\n this.removeOldImages(this.currentImageElement);\n }\n });\n\n _defineProperty$1(this, \"showImage\", (previewImage, frame, qualityIndex, thumbNum, thumbFilename, newImage = true) => {\n this.player.debug.log(`Showing thumb: ${thumbFilename}. num: ${thumbNum}. qual: ${qualityIndex}. newimg: ${newImage}`);\n this.setImageSizeAndOffset(previewImage, frame);\n\n if (newImage) {\n this.currentImageContainer.appendChild(previewImage);\n this.currentImageElement = previewImage;\n\n if (!this.loadedImages.includes(thumbFilename)) {\n this.loadedImages.push(thumbFilename);\n }\n } // Preload images before and after the current one\n // Show higher quality of the same frame\n // 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\n\n\n this.preloadNearby(thumbNum, true).then(this.preloadNearby(thumbNum, false)).then(this.getHigherQuality(qualityIndex, previewImage, frame, thumbFilename));\n });\n\n _defineProperty$1(this, \"removeOldImages\", currentImage => {\n // Get a list of all images, convert it from a DOM list to an array\n Array.from(this.currentImageContainer.children).forEach(image => {\n if (image.tagName.toLowerCase() !== 'img') {\n return;\n }\n\n const removeDelay = this.usingSprites ? 500 : 1000;\n\n if (image.dataset.index !== currentImage.dataset.index && !image.dataset.deleting) {\n // 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\n // First set attribute 'deleting' to prevent multi-handling of this on repeat firing of this function\n // eslint-disable-next-line no-param-reassign\n image.dataset.deleting = true; // This has to be set before the timeout - to prevent issues switching between hover and scrub\n\n const {\n currentImageContainer\n } = this;\n setTimeout(() => {\n currentImageContainer.removeChild(image);\n this.player.debug.log(`Removing thumb: ${image.dataset.filename}`);\n }, removeDelay);\n }\n });\n });\n\n _defineProperty$1(this, \"preloadNearby\", (thumbNum, forward = true) => {\n return new Promise(resolve => {\n setTimeout(() => {\n const oldThumbFilename = this.thumbnails[0].frames[thumbNum].text;\n\n if (this.showingThumbFilename === oldThumbFilename) {\n // 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\n let thumbnailsClone;\n\n if (forward) {\n thumbnailsClone = this.thumbnails[0].frames.slice(thumbNum);\n } else {\n thumbnailsClone = this.thumbnails[0].frames.slice(0, thumbNum).reverse();\n }\n\n let foundOne = false;\n thumbnailsClone.forEach(frame => {\n const newThumbFilename = frame.text;\n\n if (newThumbFilename !== oldThumbFilename) {\n // Found one with a different filename. Make sure it hasn't already been loaded on this page visit\n if (!this.loadedImages.includes(newThumbFilename)) {\n foundOne = true;\n this.player.debug.log(`Preloading thumb filename: ${newThumbFilename}`);\n const {\n urlPrefix\n } = this.thumbnails[0];\n const thumbURL = urlPrefix + newThumbFilename;\n const previewImage = new Image();\n previewImage.src = thumbURL;\n\n previewImage.onload = () => {\n this.player.debug.log(`Preloaded thumb filename: ${newThumbFilename}`);\n if (!this.loadedImages.includes(newThumbFilename)) this.loadedImages.push(newThumbFilename); // We don't resolve until the thumb is loaded\n\n resolve();\n };\n }\n }\n }); // If there are none to preload then we want to resolve immediately\n\n if (!foundOne) {\n resolve();\n }\n }\n }, 300);\n });\n });\n\n _defineProperty$1(this, \"getHigherQuality\", (currentQualityIndex, previewImage, frame, thumbFilename) => {\n if (currentQualityIndex < this.thumbnails.length - 1) {\n // 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\n let previewImageHeight = previewImage.naturalHeight;\n\n if (this.usingSprites) {\n previewImageHeight = frame.h;\n }\n\n if (previewImageHeight < this.thumbContainerHeight) {\n // Recurse back to the loadImage function - show a higher quality one, but only if the viewer is on this frame for a while\n setTimeout(() => {\n // Make sure the mouse hasn't already moved on and started hovering at another image\n if (this.showingThumbFilename === thumbFilename) {\n this.player.debug.log(`Showing higher quality thumb for: ${thumbFilename}`);\n this.loadImage(currentQualityIndex + 1);\n }\n }, 300);\n }\n }\n });\n\n _defineProperty$1(this, \"toggleThumbContainer\", (toggle = false, clearShowing = false) => {\n const className = this.player.config.classNames.previewThumbnails.thumbContainerShown;\n this.elements.thumb.container.classList.toggle(className, toggle);\n\n if (!toggle && clearShowing) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n });\n\n _defineProperty$1(this, \"toggleScrubbingContainer\", (toggle = false) => {\n const className = this.player.config.classNames.previewThumbnails.scrubbingContainerShown;\n this.elements.scrubbing.container.classList.toggle(className, toggle);\n\n if (!toggle) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n });\n\n _defineProperty$1(this, \"determineContainerAutoSizing\", () => {\n if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) {\n // This will prevent auto sizing in this.setThumbContainerSizeAndPos()\n this.sizeSpecifiedInCSS = true;\n }\n });\n\n _defineProperty$1(this, \"setThumbContainerSizeAndPos\", () => {\n if (!this.sizeSpecifiedInCSS) {\n const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${this.thumbContainerHeight}px`;\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (this.elements.thumb.imageContainer.clientHeight > 20 && this.elements.thumb.imageContainer.clientWidth < 20) {\n const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (this.elements.thumb.imageContainer.clientHeight < 20 && this.elements.thumb.imageContainer.clientWidth > 20) {\n const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`;\n }\n\n this.setThumbContainerPos();\n });\n\n _defineProperty$1(this, \"setThumbContainerPos\", () => {\n const seekbarRect = this.player.elements.progress.getBoundingClientRect();\n const plyrRect = this.player.elements.container.getBoundingClientRect();\n const {\n container\n } = this.elements.thumb; // Find the lowest and highest desired left-position, so we don't slide out the side of the video container\n\n const minVal = plyrRect.left - seekbarRect.left + 10;\n const maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10; // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth\n\n let previewPos = this.mousePosX - seekbarRect.left - container.clientWidth / 2;\n\n if (previewPos < minVal) {\n previewPos = minVal;\n }\n\n if (previewPos > maxVal) {\n previewPos = maxVal;\n }\n\n container.style.left = `${previewPos}px`;\n });\n\n _defineProperty$1(this, \"setScrubbingContainerSize\", () => {\n const {\n width,\n height\n } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight\n });\n this.elements.scrubbing.container.style.width = `${width}px`;\n this.elements.scrubbing.container.style.height = `${height}px`;\n });\n\n _defineProperty$1(this, \"setImageSizeAndOffset\", (previewImage, frame) => {\n if (!this.usingSprites) {\n return;\n } // Find difference between height and preview container height\n\n\n const multiplier = this.thumbContainerHeight / frame.h; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.left = `-${frame.x * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.top = `-${frame.y * multiplier}px`;\n });\n\n this.player = player;\n this.thumbnails = [];\n this.loaded = false;\n this.lastMouseMoveTime = Date.now();\n this.mouseDown = false;\n this.loadedImages = [];\n this.elements = {\n thumb: {},\n scrubbing: {}\n };\n this.load();\n }\n\n get enabled() {\n return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;\n }\n\n get currentImageContainer() {\n if (this.mouseDown) {\n return this.elements.scrubbing.container;\n }\n\n return this.elements.thumb.imageContainer;\n }\n\n get usingSprites() {\n return Object.keys(this.thumbnails[0].frames[0]).includes('w');\n }\n\n get thumbAspectRatio() {\n if (this.usingSprites) {\n return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;\n }\n\n return this.thumbnails[0].width / this.thumbnails[0].height;\n }\n\n get thumbContainerHeight() {\n if (this.mouseDown) {\n const {\n height\n } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight\n });\n return height;\n } // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset)\n\n\n if (this.sizeSpecifiedInCSS) {\n return this.elements.thumb.imageContainer.clientHeight;\n }\n\n return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);\n }\n\n get currentImageElement() {\n if (this.mouseDown) {\n return this.currentScrubbingImageElement;\n }\n\n return this.currentThumbnailImageElement;\n }\n\n set currentImageElement(element) {\n if (this.mouseDown) {\n this.currentScrubbingImageElement = element;\n } else {\n this.currentThumbnailImageElement = element;\n }\n }\n\n}\n\n// ==========================================================================\nconst source = {\n // Add elements to HTML5 media (source, tracks, etc)\n insertElements(type, attributes) {\n if (is.string(attributes)) {\n insertElement(type, this.media, {\n src: attributes\n });\n } else if (is.array(attributes)) {\n attributes.forEach(attribute => {\n insertElement(type, this.media, attribute);\n });\n }\n },\n\n // Update source\n // Sources are not checked for support so be careful\n change(input) {\n if (!getDeep(input, 'sources.length')) {\n this.debug.warn('Invalid source format');\n return;\n } // Cancel current network requests\n\n\n html5.cancelRequests.call(this); // Destroy instance and re-setup\n\n this.destroy.call(this, () => {\n // Reset quality options\n this.options.quality = []; // Remove elements\n\n removeElement(this.media);\n this.media = null; // Reset class name\n\n if (is.element(this.elements.container)) {\n this.elements.container.removeAttribute('class');\n } // Set the type and provider\n\n\n const {\n sources,\n type\n } = input;\n const [{\n provider = providers.html5,\n src\n }] = sources;\n const tagName = provider === 'html5' ? type : 'div';\n const attributes = provider === 'html5' ? {} : {\n src\n };\n Object.assign(this, {\n provider,\n type,\n // Check for support\n supported: support.check(type, provider, this.config.playsinline),\n // Create new element\n media: createElement(tagName, attributes)\n }); // Inject the new element\n\n this.elements.container.appendChild(this.media); // Autoplay the new source?\n\n if (is.boolean(input.autoplay)) {\n this.config.autoplay = input.autoplay;\n } // Set attributes for audio and video\n\n\n if (this.isHTML5) {\n if (this.config.crossorigin) {\n this.media.setAttribute('crossorigin', '');\n }\n\n if (this.config.autoplay) {\n this.media.setAttribute('autoplay', '');\n }\n\n if (!is.empty(input.poster)) {\n this.poster = input.poster;\n }\n\n if (this.config.loop.active) {\n this.media.setAttribute('loop', '');\n }\n\n if (this.config.muted) {\n this.media.setAttribute('muted', '');\n }\n\n if (this.config.playsinline) {\n this.media.setAttribute('playsinline', '');\n }\n } // Restore class hook\n\n\n ui.addStyleHook.call(this); // Set new sources for html5\n\n if (this.isHTML5) {\n source.insertElements.call(this, 'source', sources);\n } // Set video title\n\n\n this.config.title = input.title; // Set up from scratch\n\n media.setup.call(this); // HTML5 stuff\n\n if (this.isHTML5) {\n // Setup captions\n if (Object.keys(input).includes('tracks')) {\n source.insertElements.call(this, 'track', input.tracks);\n }\n } // If HTML5 or embed but not fully supported, setupInterface and call ready now\n\n\n if (this.isHTML5 || this.isEmbed && !this.supported.ui) {\n // Setup interface\n ui.build.call(this);\n } // Load HTML5 sources\n\n\n if (this.isHTML5) {\n this.media.load();\n } // Update previewThumbnails config & reload plugin\n\n\n if (!is.empty(input.previewThumbnails)) {\n Object.assign(this.config.previewThumbnails, input.previewThumbnails); // Cleanup previewThumbnails plugin if it was loaded\n\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n } // Create new instance if it is still enabled\n\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n } // Update the fullscreen support\n\n\n this.fullscreen.update();\n }, true);\n }\n\n};\n\n/**\n * Returns a number whose value is limited to the given range.\n *\n * Example: limit the output of this computation to between 0 and 255\n * (x * 255).clamp(0, 255)\n *\n * @param {Number} input\n * @param {Number} min The lower boundary of the output range\n * @param {Number} max The upper boundary of the output range\n * @returns A number in the range [min, max]\n * @type Number\n */\nfunction clamp(input = 0, min = 0, max = 255) {\n return Math.min(Math.max(input, min), max);\n}\n\n// TODO: Use a WeakMap for private globals\n// const globals = new WeakMap();\n// Plyr instance\n\nclass Plyr {\n constructor(target, options) {\n _defineProperty$1(this, \"play\", () => {\n if (!is.function(this.media.play)) {\n return null;\n } // Intecept play with ads\n\n\n if (this.ads && this.ads.enabled) {\n this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play()));\n } // Return the promise (for HTML5)\n\n\n return this.media.play();\n });\n\n _defineProperty$1(this, \"pause\", () => {\n if (!this.playing || !is.function(this.media.pause)) {\n return null;\n }\n\n return this.media.pause();\n });\n\n _defineProperty$1(this, \"togglePlay\", input => {\n // Toggle based on current state if nothing passed\n const toggle = is.boolean(input) ? input : !this.playing;\n\n if (toggle) {\n return this.play();\n }\n\n return this.pause();\n });\n\n _defineProperty$1(this, \"stop\", () => {\n if (this.isHTML5) {\n this.pause();\n this.restart();\n } else if (is.function(this.media.stop)) {\n this.media.stop();\n }\n });\n\n _defineProperty$1(this, \"restart\", () => {\n this.currentTime = 0;\n });\n\n _defineProperty$1(this, \"rewind\", seekTime => {\n this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime;\n });\n\n _defineProperty$1(this, \"forward\", seekTime => {\n this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime;\n });\n\n _defineProperty$1(this, \"increaseVolume\", step => {\n const volume = this.media.muted ? 0 : this.volume;\n this.volume = volume + (is.number(step) ? step : 0);\n });\n\n _defineProperty$1(this, \"decreaseVolume\", step => {\n this.increaseVolume(-step);\n });\n\n _defineProperty$1(this, \"airplay\", () => {\n // Show dialog if supported\n if (support.airplay) {\n this.media.webkitShowPlaybackTargetPicker();\n }\n });\n\n _defineProperty$1(this, \"toggleControls\", toggle => {\n // Don't toggle if missing UI support or if it's audio\n if (this.supported.ui && !this.isAudio) {\n // Get state before change\n const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls); // Negate the argument if not undefined since adding the class to hides the controls\n\n const force = typeof toggle === 'undefined' ? undefined : !toggle; // Apply and get updated state\n\n const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force); // Close menu\n\n if (hiding && is.array(this.config.controls) && this.config.controls.includes('settings') && !is.empty(this.config.settings)) {\n controls.toggleMenu.call(this, false);\n } // Trigger event on change\n\n\n if (hiding !== isHidden) {\n const eventName = hiding ? 'controlshidden' : 'controlsshown';\n triggerEvent.call(this, this.media, eventName);\n }\n\n return !hiding;\n }\n\n return false;\n });\n\n _defineProperty$1(this, \"on\", (event, callback) => {\n on.call(this, this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"once\", (event, callback) => {\n once.call(this, this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"off\", (event, callback) => {\n off(this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"destroy\", (callback, soft = false) => {\n if (!this.ready) {\n return;\n }\n\n const done = () => {\n // Reset overflow (incase destroyed while in fullscreen)\n document.body.style.overflow = ''; // GC for embed\n\n this.embed = null; // If it's a soft destroy, make minimal changes\n\n if (soft) {\n if (Object.keys(this.elements).length) {\n // Remove elements\n removeElement(this.elements.buttons.play);\n removeElement(this.elements.captions);\n removeElement(this.elements.controls);\n removeElement(this.elements.wrapper); // Clear for GC\n\n this.elements.buttons.play = null;\n this.elements.captions = null;\n this.elements.controls = null;\n this.elements.wrapper = null;\n } // Callback\n\n\n if (is.function(callback)) {\n callback();\n }\n } else {\n // Unbind listeners\n unbindListeners.call(this); // Cancel current network requests\n\n html5.cancelRequests.call(this); // Replace the container with the original element provided\n\n replaceElement(this.elements.original, this.elements.container); // Event\n\n triggerEvent.call(this, this.elements.original, 'destroyed', true); // Callback\n\n if (is.function(callback)) {\n callback.call(this.elements.original);\n } // Reset state\n\n\n this.ready = false; // Clear for garbage collection\n\n setTimeout(() => {\n this.elements = null;\n this.media = null;\n }, 200);\n }\n }; // Stop playback\n\n\n this.stop(); // Clear timeouts\n\n clearTimeout(this.timers.loading);\n clearTimeout(this.timers.controls);\n clearTimeout(this.timers.resized); // Provider specific stuff\n\n if (this.isHTML5) {\n // Restore native video controls\n ui.toggleNativeControls.call(this, true); // Clean up\n\n done();\n } else if (this.isYouTube) {\n // Clear timers\n clearInterval(this.timers.buffering);\n clearInterval(this.timers.playing); // Destroy YouTube API\n\n if (this.embed !== null && is.function(this.embed.destroy)) {\n this.embed.destroy();\n } // Clean up\n\n\n done();\n } else if (this.isVimeo) {\n // Destroy Vimeo API\n // then clean up (wait, to prevent postmessage errors)\n if (this.embed !== null) {\n this.embed.unload().then(done);\n } // Vimeo does not always return\n\n\n setTimeout(done, 200);\n }\n });\n\n _defineProperty$1(this, \"supports\", type => support.mime.call(this, type));\n\n this.timers = {}; // State\n\n this.ready = false;\n this.loading = false;\n this.failed = false; // Touch device\n\n this.touch = support.touch; // Set the media element\n\n this.media = target; // String selector passed\n\n if (is.string(this.media)) {\n this.media = document.querySelectorAll(this.media);\n } // jQuery, NodeList or Array passed, use first element\n\n\n if (window.jQuery && this.media instanceof jQuery || is.nodeList(this.media) || is.array(this.media)) {\n // eslint-disable-next-line\n this.media = this.media[0];\n } // Set config\n\n\n this.config = extend({}, defaults, Plyr.defaults, options || {}, (() => {\n try {\n return JSON.parse(this.media.getAttribute('data-plyr-config'));\n } catch (_) {\n return {};\n }\n })()); // Elements cache\n\n this.elements = {\n container: null,\n fullscreen: null,\n captions: null,\n buttons: {},\n display: {},\n progress: {},\n inputs: {},\n settings: {\n popup: null,\n menu: null,\n panels: {},\n buttons: {}\n }\n }; // Captions\n\n this.captions = {\n active: null,\n currentTrack: -1,\n meta: new WeakMap()\n }; // Fullscreen\n\n this.fullscreen = {\n active: false\n }; // Options\n\n this.options = {\n speed: [],\n quality: []\n }; // Debugging\n // TODO: move to globals\n\n this.debug = new Console(this.config.debug); // Log config options and support\n\n this.debug.log('Config', this.config);\n this.debug.log('Support', support); // We need an element to setup\n\n if (is.nullOrUndefined(this.media) || !is.element(this.media)) {\n this.debug.error('Setup failed: no suitable element passed');\n return;\n } // Bail if the element is initialized\n\n\n if (this.media.plyr) {\n this.debug.warn('Target already setup');\n return;\n } // Bail if not enabled\n\n\n if (!this.config.enabled) {\n this.debug.error('Setup failed: disabled by config');\n return;\n } // Bail if disabled or no basic support\n // You may want to disable certain UAs etc\n\n\n if (!support.check().api) {\n this.debug.error('Setup failed: no support');\n return;\n } // Cache original element state for .destroy()\n\n\n const clone = this.media.cloneNode(true);\n clone.autoplay = false;\n this.elements.original = clone; // Set media type based on tag or data attribute\n // Supported: video, audio, vimeo, youtube\n\n const _type = this.media.tagName.toLowerCase(); // Embed properties\n\n\n let iframe = null;\n let url = null; // Different setup based on type\n\n switch (_type) {\n case 'div':\n // Find the frame\n iframe = this.media.querySelector('iframe'); // <iframe> type\n\n if (is.element(iframe)) {\n // Detect provider\n url = parseUrl(iframe.getAttribute('src'));\n this.provider = getProviderByUrl(url.toString()); // Rework elements\n\n this.elements.container = this.media;\n this.media = iframe; // Reset classname\n\n this.elements.container.className = ''; // Get attributes from URL and set config\n\n if (url.search.length) {\n const truthy = ['1', 'true'];\n\n if (truthy.includes(url.searchParams.get('autoplay'))) {\n this.config.autoplay = true;\n }\n\n if (truthy.includes(url.searchParams.get('loop'))) {\n this.config.loop.active = true;\n } // TODO: replace fullscreen.iosNative with this playsinline config option\n // YouTube requires the playsinline in the URL\n\n\n if (this.isYouTube) {\n this.config.playsinline = truthy.includes(url.searchParams.get('playsinline'));\n this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language?\n } else {\n this.config.playsinline = true;\n }\n }\n } else {\n // <div> with attributes\n this.provider = this.media.getAttribute(this.config.attributes.embed.provider); // Remove attribute\n\n this.media.removeAttribute(this.config.attributes.embed.provider);\n } // Unsupported or missing provider\n\n\n if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) {\n this.debug.error('Setup failed: Invalid provider');\n return;\n } // Audio will come later for external providers\n\n\n this.type = types.video;\n break;\n\n case 'video':\n case 'audio':\n this.type = _type;\n this.provider = providers.html5; // Get config from attributes\n\n if (this.media.hasAttribute('crossorigin')) {\n this.config.crossorigin = true;\n }\n\n if (this.media.hasAttribute('autoplay')) {\n this.config.autoplay = true;\n }\n\n if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) {\n this.config.playsinline = true;\n }\n\n if (this.media.hasAttribute('muted')) {\n this.config.muted = true;\n }\n\n if (this.media.hasAttribute('loop')) {\n this.config.loop.active = true;\n }\n\n break;\n\n default:\n this.debug.error('Setup failed: unsupported type');\n return;\n } // Check for support again but with type\n\n\n this.supported = support.check(this.type, this.provider, this.config.playsinline); // If no support for even API, bail\n\n if (!this.supported.api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n this.eventListeners = []; // Create listeners\n\n this.listeners = new Listeners(this); // Setup local storage for user settings\n\n this.storage = new Storage(this); // Store reference\n\n this.media.plyr = this; // Wrap media\n\n if (!is.element(this.elements.container)) {\n this.elements.container = createElement('div', {\n tabindex: 0\n });\n wrap(this.media, this.elements.container);\n } // Migrate custom properties from media to container (so they work 😉)\n\n\n ui.migrateStyles.call(this); // Add style hook\n\n ui.addStyleHook.call(this); // Setup media\n\n media.setup.call(this); // Listen for events if debugging\n\n if (this.config.debug) {\n on.call(this, this.elements.container, this.config.events.join(' '), event => {\n this.debug.log(`event: ${event.type}`);\n });\n } // Setup fullscreen\n\n\n this.fullscreen = new Fullscreen(this); // Setup interface\n // If embed but not fully supported, build interface now to avoid flash of controls\n\n if (this.isHTML5 || this.isEmbed && !this.supported.ui) {\n ui.build.call(this);\n } // Container listeners\n\n\n this.listeners.container(); // Global listeners\n\n this.listeners.global(); // Setup ads if provided\n\n if (this.config.ads.enabled) {\n this.ads = new Ads(this);\n } // Autoplay if required\n\n\n if (this.isHTML5 && this.config.autoplay) {\n this.once('canplay', () => silencePromise(this.play()));\n } // Seek time will be recorded (in listeners.js) so we can prevent hiding controls for a few seconds after seek\n\n\n this.lastSeekTime = 0; // Setup preview thumbnails if enabled\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n } // ---------------------------------------\n // API\n // ---------------------------------------\n\n /**\n * Types and provider helpers\n */\n\n\n get isHTML5() {\n return this.provider === providers.html5;\n }\n\n get isEmbed() {\n return this.isYouTube || this.isVimeo;\n }\n\n get isYouTube() {\n return this.provider === providers.youtube;\n }\n\n get isVimeo() {\n return this.provider === providers.vimeo;\n }\n\n get isVideo() {\n return this.type === types.video;\n }\n\n get isAudio() {\n return this.type === types.audio;\n }\n /**\n * Play the media, or play the advertisement (if they are not blocked)\n */\n\n\n /**\n * Get playing state\n */\n get playing() {\n return Boolean(this.ready && !this.paused && !this.ended);\n }\n /**\n * Get paused state\n */\n\n\n get paused() {\n return Boolean(this.media.paused);\n }\n /**\n * Get stopped state\n */\n\n\n get stopped() {\n return Boolean(this.paused && this.currentTime === 0);\n }\n /**\n * Get ended state\n */\n\n\n get ended() {\n return Boolean(this.media.ended);\n }\n /**\n * Toggle playback based on current status\n * @param {Boolean} input\n */\n\n\n /**\n * Seek to a time\n * @param {Number} input - where to seek to in seconds. Defaults to 0 (the start)\n */\n set currentTime(input) {\n // Bail if media duration isn't available yet\n if (!this.duration) {\n return;\n } // Validate input\n\n\n const inputIsValid = is.number(input) && input > 0; // Set\n\n this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0; // Logging\n\n this.debug.log(`Seeking to ${this.currentTime} seconds`);\n }\n /**\n * Get current time\n */\n\n\n get currentTime() {\n return Number(this.media.currentTime);\n }\n /**\n * Get buffered\n */\n\n\n get buffered() {\n const {\n buffered\n } = this.media; // YouTube / Vimeo return a float between 0-1\n\n if (is.number(buffered)) {\n return buffered;\n } // HTML5\n // TODO: Handle buffered chunks of the media\n // (i.e. seek to another section buffers only that section)\n\n\n if (buffered && buffered.length && this.duration > 0) {\n return buffered.end(0) / this.duration;\n }\n\n return 0;\n }\n /**\n * Get seeking status\n */\n\n\n get seeking() {\n return Boolean(this.media.seeking);\n }\n /**\n * Get the duration of the current media\n */\n\n\n get duration() {\n // Faux duration set via config\n const fauxDuration = parseFloat(this.config.duration); // Media duration can be NaN or Infinity before the media has loaded\n\n const realDuration = (this.media || {}).duration;\n const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration; // If config duration is funky, use regular duration\n\n return fauxDuration || duration;\n }\n /**\n * Set the player volume\n * @param {Number} value - must be between 0 and 1. Defaults to the value from local storage and config.volume if not set in storage\n */\n\n\n set volume(value) {\n let volume = value;\n const max = 1;\n const min = 0;\n\n if (is.string(volume)) {\n volume = Number(volume);\n } // Load volume from storage if no value specified\n\n\n if (!is.number(volume)) {\n volume = this.storage.get('volume');\n } // Use config if all else fails\n\n\n if (!is.number(volume)) {\n ({\n volume\n } = this.config);\n } // Maximum is volumeMax\n\n\n if (volume > max) {\n volume = max;\n } // Minimum is volumeMin\n\n\n if (volume < min) {\n volume = min;\n } // Update config\n\n\n this.config.volume = volume; // Set the player volume\n\n this.media.volume = volume; // If muted, and we're increasing volume manually, reset muted state\n\n if (!is.empty(value) && this.muted && volume > 0) {\n this.muted = false;\n }\n }\n /**\n * Get the current player volume\n */\n\n\n get volume() {\n return Number(this.media.volume);\n }\n /**\n * Increase volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n\n\n /**\n * Set muted state\n * @param {Boolean} mute\n */\n set muted(mute) {\n let toggle = mute; // Load muted state from storage\n\n if (!is.boolean(toggle)) {\n toggle = this.storage.get('muted');\n } // Use config if all else fails\n\n\n if (!is.boolean(toggle)) {\n toggle = this.config.muted;\n } // Update config\n\n\n this.config.muted = toggle; // Set mute on the player\n\n this.media.muted = toggle;\n }\n /**\n * Get current muted state\n */\n\n\n get muted() {\n return Boolean(this.media.muted);\n }\n /**\n * Check if the media has audio\n */\n\n\n get hasAudio() {\n // Assume yes for all non HTML5 (as we can't tell...)\n if (!this.isHTML5) {\n return true;\n }\n\n if (this.isAudio) {\n return true;\n } // Get audio tracks\n\n\n return Boolean(this.media.mozHasAudio) || Boolean(this.media.webkitAudioDecodedByteCount) || Boolean(this.media.audioTracks && this.media.audioTracks.length);\n }\n /**\n * Set playback speed\n * @param {Number} speed - the speed of playback (0.5-2.0)\n */\n\n\n set speed(input) {\n let speed = null;\n\n if (is.number(input)) {\n speed = input;\n }\n\n if (!is.number(speed)) {\n speed = this.storage.get('speed');\n }\n\n if (!is.number(speed)) {\n speed = this.config.speed.selected;\n } // Clamp to min/max\n\n\n const {\n minimumSpeed: min,\n maximumSpeed: max\n } = this;\n speed = clamp(speed, min, max); // Update config\n\n this.config.speed.selected = speed; // Set media speed\n\n setTimeout(() => {\n if (this.media) {\n this.media.playbackRate = speed;\n }\n }, 0);\n }\n /**\n * Get current playback speed\n */\n\n\n get speed() {\n return Number(this.media.playbackRate);\n }\n /**\n * Get the minimum allowed speed\n */\n\n\n get minimumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.min(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 0.5;\n } // https://stackoverflow.com/a/32320020/1191319\n\n\n return 0.0625;\n }\n /**\n * Get the maximum allowed speed\n */\n\n\n get maximumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.max(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 2;\n } // https://stackoverflow.com/a/32320020/1191319\n\n\n return 16;\n }\n /**\n * Set playback quality\n * Currently HTML5 & YouTube only\n * @param {Number} input - Quality level\n */\n\n\n set quality(input) {\n const config = this.config.quality;\n const options = this.options.quality;\n\n if (!options.length) {\n return;\n }\n\n let quality = [!is.empty(input) && Number(input), this.storage.get('quality'), config.selected, config.default].find(is.number);\n let updateStorage = true;\n\n if (!options.includes(quality)) {\n const value = closest(options, quality);\n this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`);\n quality = value; // Don't update storage if quality is not supported\n\n updateStorage = false;\n } // Update config\n\n\n config.selected = quality; // Set quality\n\n this.media.quality = quality; // Save to storage\n\n if (updateStorage) {\n this.storage.set({\n quality\n });\n }\n }\n /**\n * Get current quality level\n */\n\n\n get quality() {\n return this.media.quality;\n }\n /**\n * Toggle loop\n * TODO: Finish fancy new logic. Set the indicator on load as user may pass loop as config\n * @param {Boolean} input - Whether to loop or not\n */\n\n\n set loop(input) {\n const toggle = is.boolean(input) ? input : this.config.loop.active;\n this.config.loop.active = toggle;\n this.media.loop = toggle; // Set default to be a true toggle\n\n /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle';\n switch (type) {\n case 'start':\n if (this.config.loop.end && this.config.loop.end <= this.currentTime) {\n this.config.loop.end = null;\n }\n this.config.loop.start = this.currentTime;\n // this.config.loop.indicator.start = this.elements.display.played.value;\n break;\n case 'end':\n if (this.config.loop.start >= this.currentTime) {\n return this;\n }\n this.config.loop.end = this.currentTime;\n // this.config.loop.indicator.end = this.elements.display.played.value;\n break;\n case 'all':\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n this.config.loop.indicator.start = 0;\n this.config.loop.indicator.end = 100;\n break;\n case 'toggle':\n if (this.config.loop.active) {\n this.config.loop.start = 0;\n this.config.loop.end = null;\n } else {\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n }\n break;\n default:\n this.config.loop.start = 0;\n this.config.loop.end = null;\n break;\n } */\n }\n /**\n * Get current loop state\n */\n\n\n get loop() {\n return Boolean(this.media.loop);\n }\n /**\n * Set new media source\n * @param {Object} input - The new source object (see docs)\n */\n\n\n set source(input) {\n source.change.call(this, input);\n }\n /**\n * Get current source\n */\n\n\n get source() {\n return this.media.currentSrc;\n }\n /**\n * Get a download URL (either source or custom)\n */\n\n\n get download() {\n const {\n download\n } = this.config.urls;\n return is.url(download) ? download : this.source;\n }\n /**\n * Set the download URL\n */\n\n\n set download(input) {\n if (!is.url(input)) {\n return;\n }\n\n this.config.urls.download = input;\n controls.setDownloadUrl.call(this);\n }\n /**\n * Set the poster image for a video\n * @param {String} input - the URL for the new poster image\n */\n\n\n set poster(input) {\n if (!this.isVideo) {\n this.debug.warn('Poster can only be set for video');\n return;\n }\n\n ui.setPoster.call(this, input, false).catch(() => {});\n }\n /**\n * Get the current poster image\n */\n\n\n get poster() {\n if (!this.isVideo) {\n return null;\n }\n\n return this.media.getAttribute('poster') || this.media.getAttribute('data-poster');\n }\n /**\n * Get the current aspect ratio in use\n */\n\n\n get ratio() {\n if (!this.isVideo) {\n return null;\n }\n\n const ratio = reduceAspectRatio(getAspectRatio.call(this));\n return is.array(ratio) ? ratio.join(':') : ratio;\n }\n /**\n * Set video aspect ratio\n */\n\n\n set ratio(input) {\n if (!this.isVideo) {\n this.debug.warn('Aspect ratio can only be set for video');\n return;\n }\n\n if (!is.string(input) || !validateAspectRatio(input)) {\n this.debug.error(`Invalid aspect ratio specified (${input})`);\n return;\n }\n\n this.config.ratio = reduceAspectRatio(input);\n setAspectRatio.call(this);\n }\n /**\n * Set the autoplay state\n * @param {Boolean} input - Whether to autoplay or not\n */\n\n\n set autoplay(input) {\n const toggle = is.boolean(input) ? input : this.config.autoplay;\n this.config.autoplay = toggle;\n }\n /**\n * Get the current autoplay state\n */\n\n\n get autoplay() {\n return Boolean(this.config.autoplay);\n }\n /**\n * Toggle captions\n * @param {Boolean} input - Whether to enable captions\n */\n\n\n toggleCaptions(input) {\n captions.toggle.call(this, input, false);\n }\n /**\n * Set the caption track by index\n * @param {Number} - Caption index\n */\n\n\n set currentTrack(input) {\n captions.set.call(this, input, false);\n captions.setup();\n }\n /**\n * Get the current caption track index (-1 if disabled)\n */\n\n\n get currentTrack() {\n const {\n toggled,\n currentTrack\n } = this.captions;\n return toggled ? currentTrack : -1;\n }\n /**\n * Set the wanted language for captions\n * Since tracks can be added later it won't update the actual caption track until there is a matching track\n * @param {String} - Two character ISO language code (e.g. EN, FR, PT, etc)\n */\n\n\n set language(input) {\n captions.setLanguage.call(this, input, false);\n }\n /**\n * Get the current track's language\n */\n\n\n get language() {\n return (captions.getCurrentTrack.call(this) || {}).language;\n }\n /**\n * Toggle picture-in-picture playback on WebKit/MacOS\n * TODO: update player with state, support, enabled\n * TODO: detect outside changes\n */\n\n\n set pip(input) {\n // Bail if no support\n if (!support.pip) {\n return;\n } // Toggle based on current state if not passed\n\n\n const toggle = is.boolean(input) ? input : !this.pip; // Toggle based on current state\n // Safari\n\n if (is.function(this.media.webkitSetPresentationMode)) {\n this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive);\n } // Chrome\n\n\n if (is.function(this.media.requestPictureInPicture)) {\n if (!this.pip && toggle) {\n this.media.requestPictureInPicture();\n } else if (this.pip && !toggle) {\n document.exitPictureInPicture();\n }\n }\n }\n /**\n * Get the current picture-in-picture state\n */\n\n\n get pip() {\n if (!support.pip) {\n return null;\n } // Safari\n\n\n if (!is.empty(this.media.webkitPresentationMode)) {\n return this.media.webkitPresentationMode === pip.active;\n } // Chrome\n\n\n return this.media === document.pictureInPictureElement;\n }\n /**\n * Sets the preview thubmnails for the current source\n */\n\n\n setPreviewThumbnails(thumbnailSource) {\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n Object.assign(this.config.previewThumbnails, thumbnailSource); // Create new instance if it is still enabled\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n /**\n * Trigger the airplay dialog\n * TODO: update player with state, support, enabled\n */\n\n\n /**\n * Check for support\n * @param {String} type - Player type (audio/video)\n * @param {String} provider - Provider (html5/youtube/vimeo)\n * @param {Boolean} inline - Where player has `playsinline` sttribute\n */\n static supported(type, provider, inline) {\n return support.check(type, provider, inline);\n }\n /**\n * Load an SVG sprite into the page\n * @param {String} url - URL for the SVG sprite\n * @param {String} [id] - Unique ID\n */\n\n\n static loadSprite(url, id) {\n return loadSprite(url, id);\n }\n /**\n * Setup multiple instances\n * @param {*} selector\n * @param {Object} options\n */\n\n\n static setup(selector, options = {}) {\n let targets = null;\n\n if (is.string(selector)) {\n targets = Array.from(document.querySelectorAll(selector));\n } else if (is.nodeList(selector)) {\n targets = Array.from(selector);\n } else if (is.array(selector)) {\n targets = selector.filter(is.element);\n }\n\n if (is.empty(targets)) {\n return null;\n }\n\n return targets.map(t => new Plyr(t, options));\n }\n\n}\n\nPlyr.defaults = cloneDeep(defaults);\n\nexport { Plyr as default };\n","function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var defaults={addCSS:!0,thumbWidth:15,watch:!0};function matches(e,t){return function(){return Array.from(document.querySelectorAll(t)).includes(this)}.call(e,t)}function trigger(e,t){if(e&&t){var n=new Event(t,{bubbles:!0});e.dispatchEvent(n)}}var getConstructor=function(e){return null!=e?e.constructor:null},instanceOf=function(e,t){return!!(e&&t&&e instanceof t)},isNullOrUndefined=function(e){return null==e},isObject=function(e){return getConstructor(e)===Object},isNumber=function(e){return getConstructor(e)===Number&&!Number.isNaN(e)},isString=function(e){return getConstructor(e)===String},isBoolean=function(e){return getConstructor(e)===Boolean},isFunction=function(e){return getConstructor(e)===Function},isArray=function(e){return Array.isArray(e)},isNodeList=function(e){return instanceOf(e,NodeList)},isElement=function(e){return instanceOf(e,Element)},isEvent=function(e){return instanceOf(e,Event)},isEmpty=function(e){return isNullOrUndefined(e)||(isString(e)||isArray(e)||isNodeList(e))&&!e.length||isObject(e)&&!Object.keys(e).length},is={nullOrUndefined:isNullOrUndefined,object:isObject,number:isNumber,string:isString,boolean:isBoolean,function:isFunction,array:isArray,nodeList:isNodeList,element:isElement,event:isEvent,empty:isEmpty};function getDecimalPlaces(e){var t=\"\".concat(e).match(/(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0}function round(e,t){if(1>t){var n=getDecimalPlaces(t);return parseFloat(e.toFixed(n))}return Math.round(e/t)*t}var RangeTouch=function(){function e(t,n){_classCallCheck(this,e),is.element(t)?this.element=t:is.string(t)&&(this.element=document.querySelector(t)),is.element(this.element)&&is.empty(this.element.rangeTouch)&&(this.config=_objectSpread2({},defaults,{},n),this.init())}return _createClass(e,[{key:\"init\",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect=\"none\",this.element.style.webKitUserSelect=\"none\",this.element.style.touchAction=\"manipulation\"),this.listeners(!0),this.element.rangeTouch=this)}},{key:\"destroy\",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect=\"\",this.element.style.webKitUserSelect=\"\",this.element.style.touchAction=\"\"),this.listeners(!1),this.element.rangeTouch=null)}},{key:\"listeners\",value:function(e){var t=this,n=e?\"addEventListener\":\"removeEventListener\";[\"touchstart\",\"touchmove\",\"touchend\"].forEach((function(e){t.element[n](e,(function(e){return t.set(e)}),!1)}))}},{key:\"get\",value:function(t){if(!e.enabled||!is.event(t))return null;var n,r=t.target,i=t.changedTouches[0],o=parseFloat(r.getAttribute(\"min\"))||0,s=parseFloat(r.getAttribute(\"max\"))||100,u=parseFloat(r.getAttribute(\"step\"))||1,c=r.getBoundingClientRect(),a=100/c.width*(this.config.thumbWidth/2)/100;return 0>(n=100/c.width*(i.clientX-c.left))?n=0:100<n&&(n=100),50>n?n-=(100-2*n)*a:50<n&&(n+=2*(n-50)*a),o+round(n/100*(s-o),u)}},{key:\"set\",value:function(t){e.enabled&&is.event(t)&&!t.target.disabled&&(t.preventDefault(),t.target.value=this.get(t),trigger(t.target,\"touchend\"===t.type?\"change\":\"input\"))}}],[{key:\"setup\",value:function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r=null;if(is.empty(t)||is.string(t)?r=Array.from(document.querySelectorAll(is.string(t)?t:'input[type=\"range\"]')):is.element(t)?r=[t]:is.nodeList(t)?r=Array.from(t):is.array(t)&&(r=t.filter(is.element)),is.empty(r))return null;var i=_objectSpread2({},defaults,{},n);if(is.string(t)&&i.watch){var o=new MutationObserver((function(n){Array.from(n).forEach((function(n){Array.from(n.addedNodes).forEach((function(n){is.element(n)&&matches(n,t)&&new e(n,i)}))}))}));o.observe(document.body,{childList:!0,subtree:!0})}return r.map((function(t){return new e(t,n)}))}},{key:\"enabled\",get:function(){return\"ontouchstart\"in document.documentElement}}]),e}();export default RangeTouch;","// ==========================================================================\n// Type checking utils\n// ==========================================================================\n\nconst getConstructor = (input) => (input !== null && typeof input !== 'undefined' ? input.constructor : null);\nconst instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor);\nconst isNullOrUndefined = (input) => input === null || typeof input === 'undefined';\nconst isObject = (input) => getConstructor(input) === Object;\nconst isNumber = (input) => getConstructor(input) === Number && !Number.isNaN(input);\nconst isString = (input) => getConstructor(input) === String;\nconst isBoolean = (input) => getConstructor(input) === Boolean;\nconst isFunction = (input) => getConstructor(input) === Function;\nconst isArray = (input) => Array.isArray(input);\nconst isWeakMap = (input) => instanceOf(input, WeakMap);\nconst isNodeList = (input) => instanceOf(input, NodeList);\nconst isTextNode = (input) => getConstructor(input) === Text;\nconst isEvent = (input) => instanceOf(input, Event);\nconst isKeyboardEvent = (input) => instanceOf(input, KeyboardEvent);\nconst isCue = (input) => instanceOf(input, window.TextTrackCue) || instanceOf(input, window.VTTCue);\nconst isTrack = (input) => instanceOf(input, TextTrack) || (!isNullOrUndefined(input) && isString(input.kind));\nconst isPromise = (input) => instanceOf(input, Promise) && isFunction(input.then);\n\nconst isElement = (input) =>\n input !== null &&\n typeof input === 'object' &&\n input.nodeType === 1 &&\n typeof input.style === 'object' &&\n typeof input.ownerDocument === 'object';\n\nconst isEmpty = (input) =>\n isNullOrUndefined(input) ||\n ((isString(input) || isArray(input) || isNodeList(input)) && !input.length) ||\n (isObject(input) && !Object.keys(input).length);\n\nconst isUrl = (input) => {\n // Accept a URL object\n if (instanceOf(input, window.URL)) {\n return true;\n }\n\n // Must be string from here\n if (!isString(input)) {\n return false;\n }\n\n // Add the protocol if required\n let string = input;\n if (!input.startsWith('http://') || !input.startsWith('https://')) {\n string = `http://${input}`;\n }\n\n try {\n return !isEmpty(new URL(string).hostname);\n } catch (_) {\n return false;\n }\n};\n\nexport default {\n nullOrUndefined: isNullOrUndefined,\n object: isObject,\n number: isNumber,\n string: isString,\n boolean: isBoolean,\n function: isFunction,\n array: isArray,\n weakMap: isWeakMap,\n nodeList: isNodeList,\n element: isElement,\n textNode: isTextNode,\n event: isEvent,\n keyboardEvent: isKeyboardEvent,\n cue: isCue,\n track: isTrack,\n promise: isPromise,\n url: isUrl,\n empty: isEmpty,\n};\n","// ==========================================================================\n// Animation utils\n// ==========================================================================\n\nimport is from './is';\n\nexport const transitionEndEvent = (() => {\n const element = document.createElement('span');\n\n const events = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend',\n };\n\n const type = Object.keys(events).find((event) => element.style[event] !== undefined);\n\n return is.string(type) ? events[type] : false;\n})();\n\n// Force repaint of element\nexport function repaint(element, delay) {\n setTimeout(() => {\n try {\n // eslint-disable-next-line no-param-reassign\n element.hidden = true;\n\n // eslint-disable-next-line no-unused-expressions\n element.offsetHeight;\n\n // eslint-disable-next-line no-param-reassign\n element.hidden = false;\n } catch (_) {\n // Do nothing\n }\n }, delay);\n}\n","// ==========================================================================\n// Browser sniffing\n// Unfortunately, due to mixed support, UA sniffing is required\n// ==========================================================================\n\nconst browser = {\n isIE: Boolean(window.document.documentMode),\n isEdge: window.navigator.userAgent.includes('Edge'),\n isWebkit: 'WebkitAppearance' in document.documentElement.style && !/Edge/.test(navigator.userAgent),\n isIPhone: /(iPhone|iPod)/gi.test(navigator.platform),\n isIos:\n (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) ||\n /(iPad|iPhone|iPod)/gi.test(navigator.platform),\n};\n\nexport default browser;\n","// ==========================================================================\n// Object utils\n// ==========================================================================\n\nimport is from './is';\n\n// Clone nested objects\nexport function cloneDeep(object) {\n return JSON.parse(JSON.stringify(object));\n}\n\n// Get a nested value in an object\nexport function getDeep(object, path) {\n return path.split('.').reduce((obj, key) => obj && obj[key], object);\n}\n\n// Deep extend destination object with N more objects\nexport function extend(target = {}, ...sources) {\n if (!sources.length) {\n return target;\n }\n\n const source = sources.shift();\n\n if (!is.object(source)) {\n return target;\n }\n\n Object.keys(source).forEach((key) => {\n if (is.object(source[key])) {\n if (!Object.keys(target).includes(key)) {\n Object.assign(target, { [key]: {} });\n }\n\n extend(target[key], source[key]);\n } else {\n Object.assign(target, { [key]: source[key] });\n }\n });\n\n return extend(target, ...sources);\n}\n","// ==========================================================================\n// Element utils\n// ==========================================================================\n\nimport is from './is';\nimport { extend } from './objects';\n\n// Wrap an element\nexport function wrap(elements, wrapper) {\n // Convert `elements` to an array, if necessary.\n const targets = elements.length ? elements : [elements];\n\n // Loops backwards to prevent having to clone the wrapper on the\n // first element (see `child` below).\n Array.from(targets)\n .reverse()\n .forEach((element, index) => {\n const child = index > 0 ? wrapper.cloneNode(true) : wrapper;\n // Cache the current parent and sibling.\n const parent = element.parentNode;\n const sibling = element.nextSibling;\n\n // Wrap the element (is automatically removed from its current\n // parent).\n child.appendChild(element);\n\n // If the element had a sibling, insert the wrapper before\n // the sibling to maintain the HTML structure; otherwise, just\n // append it to the parent.\n if (sibling) {\n parent.insertBefore(child, sibling);\n } else {\n parent.appendChild(child);\n }\n });\n}\n\n// Set attributes\nexport function setAttributes(element, attributes) {\n if (!is.element(element) || is.empty(attributes)) {\n return;\n }\n\n // Assume null and undefined attributes should be left out,\n // Setting them would otherwise convert them to \"null\" and \"undefined\"\n Object.entries(attributes)\n .filter(([, value]) => !is.nullOrUndefined(value))\n .forEach(([key, value]) => element.setAttribute(key, value));\n}\n\n// Create a DocumentFragment\nexport function createElement(type, attributes, text) {\n // Create a new <element>\n const element = document.createElement(type);\n\n // Set all passed attributes\n if (is.object(attributes)) {\n setAttributes(element, attributes);\n }\n\n // Add text node\n if (is.string(text)) {\n element.innerText = text;\n }\n\n // Return built element\n return element;\n}\n\n// Inaert an element after another\nexport function insertAfter(element, target) {\n if (!is.element(element) || !is.element(target)) {\n return;\n }\n\n target.parentNode.insertBefore(element, target.nextSibling);\n}\n\n// Insert a DocumentFragment\nexport function insertElement(type, parent, attributes, text) {\n if (!is.element(parent)) {\n return;\n }\n\n parent.appendChild(createElement(type, attributes, text));\n}\n\n// Remove element(s)\nexport function removeElement(element) {\n if (is.nodeList(element) || is.array(element)) {\n Array.from(element).forEach(removeElement);\n return;\n }\n\n if (!is.element(element) || !is.element(element.parentNode)) {\n return;\n }\n\n element.parentNode.removeChild(element);\n}\n\n// Remove all child elements\nexport function emptyElement(element) {\n if (!is.element(element)) {\n return;\n }\n\n let { length } = element.childNodes;\n\n while (length > 0) {\n element.removeChild(element.lastChild);\n length -= 1;\n }\n}\n\n// Replace element\nexport function replaceElement(newChild, oldChild) {\n if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) {\n return null;\n }\n\n oldChild.parentNode.replaceChild(newChild, oldChild);\n\n return newChild;\n}\n\n// Get an attribute object from a string selector\nexport function getAttributesFromSelector(sel, existingAttributes) {\n // For example:\n // '.test' to { class: 'test' }\n // '#test' to { id: 'test' }\n // '[data-test=\"test\"]' to { 'data-test': 'test' }\n\n if (!is.string(sel) || is.empty(sel)) {\n return {};\n }\n\n const attributes = {};\n const existing = extend({}, existingAttributes);\n\n sel.split(',').forEach((s) => {\n // Remove whitespace\n const selector = s.trim();\n const className = selector.replace('.', '');\n const stripped = selector.replace(/[[\\]]/g, '');\n // Get the parts and value\n const parts = stripped.split('=');\n const [key] = parts;\n const value = parts.length > 1 ? parts[1].replace(/[\"']/g, '') : '';\n // Get the first character\n const start = selector.charAt(0);\n\n switch (start) {\n case '.':\n // Add to existing classname\n if (is.string(existing.class)) {\n attributes.class = `${existing.class} ${className}`;\n } else {\n attributes.class = className;\n }\n break;\n\n case '#':\n // ID selector\n attributes.id = selector.replace('#', '');\n break;\n\n case '[':\n // Attribute selector\n attributes[key] = value;\n\n break;\n\n default:\n break;\n }\n });\n\n return extend(existing, attributes);\n}\n\n// Toggle hidden\nexport function toggleHidden(element, hidden) {\n if (!is.element(element)) {\n return;\n }\n\n let hide = hidden;\n\n if (!is.boolean(hide)) {\n hide = !element.hidden;\n }\n\n // eslint-disable-next-line no-param-reassign\n element.hidden = hide;\n}\n\n// Mirror Element.classList.toggle, with IE compatibility for \"force\" argument\nexport function toggleClass(element, className, force) {\n if (is.nodeList(element)) {\n return Array.from(element).map((e) => toggleClass(e, className, force));\n }\n\n if (is.element(element)) {\n let method = 'toggle';\n if (typeof force !== 'undefined') {\n method = force ? 'add' : 'remove';\n }\n\n element.classList[method](className);\n return element.classList.contains(className);\n }\n\n return false;\n}\n\n// Has class name\nexport function hasClass(element, className) {\n return is.element(element) && element.classList.contains(className);\n}\n\n// Element matches selector\nexport function matches(element, selector) {\n const { prototype } = Element;\n\n function match() {\n return Array.from(document.querySelectorAll(selector)).includes(this);\n }\n\n const method =\n prototype.matches ||\n prototype.webkitMatchesSelector ||\n prototype.mozMatchesSelector ||\n prototype.msMatchesSelector ||\n match;\n\n return method.call(element, selector);\n}\n\n// Closest ancestor element matching selector (also tests element itself)\nexport function closest(element, selector) {\n const { prototype } = Element;\n\n // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill\n function closestElement() {\n let el = this;\n\n do {\n if (matches.matches(el, selector)) return el;\n el = el.parentElement || el.parentNode;\n } while (el !== null && el.nodeType === 1);\n return null;\n }\n\n const method = prototype.closest || closestElement;\n\n return method.call(element, selector);\n}\n\n// Find all elements\nexport function getElements(selector) {\n return this.elements.container.querySelectorAll(selector);\n}\n\n// Find a single element\nexport function getElement(selector) {\n return this.elements.container.querySelector(selector);\n}\n\n// Set focus and tab focus class\nexport function setFocus(element = null, tabFocus = false) {\n if (!is.element(element)) {\n return;\n }\n\n // Set regular focus\n element.focus({ preventScroll: true });\n\n // If we want to mimic keyboard focus via tab\n if (tabFocus) {\n toggleClass(element, this.config.classNames.tabFocus);\n }\n}\n","// ==========================================================================\n// Plyr support checks\n// ==========================================================================\n\nimport { transitionEndEvent } from './utils/animation';\nimport browser from './utils/browser';\nimport { createElement } from './utils/elements';\nimport is from './utils/is';\n\n// Default codecs for checking mimetype support\nconst defaultCodecs = {\n 'audio/ogg': 'vorbis',\n 'audio/wav': '1',\n 'video/webm': 'vp8, vorbis',\n 'video/mp4': 'avc1.42E01E, mp4a.40.2',\n 'video/ogg': 'theora',\n};\n\n// Check for feature support\nconst support = {\n // Basic support\n audio: 'canPlayType' in document.createElement('audio'),\n video: 'canPlayType' in document.createElement('video'),\n\n // Check for support\n // Basic functionality vs full UI\n check(type, provider, playsinline) {\n const canPlayInline = browser.isIPhone && playsinline && support.playsinline;\n const api = support[type] || provider !== 'html5';\n const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline);\n\n return {\n api,\n ui,\n };\n },\n\n // Picture-in-picture support\n // Safari & Chrome only currently\n pip: (() => {\n if (browser.isIPhone) {\n return false;\n }\n\n // Safari\n // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls\n if (is.function(createElement('video').webkitSetPresentationMode)) {\n return true;\n }\n\n // Chrome\n // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture\n if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) {\n return true;\n }\n\n return false;\n })(),\n\n // Airplay support\n // Safari only currently\n airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent),\n\n // Inline playback support\n // https://webkit.org/blog/6784/new-video-policies-for-ios/\n playsinline: 'playsInline' in document.createElement('video'),\n\n // Check for mime type support against a player instance\n // Credits: http://diveintohtml5.info/everything.html\n // Related: http://www.leanbackplayer.com/test/h5mt.html\n mime(input) {\n if (is.empty(input)) {\n return false;\n }\n\n const [mediaType] = input.split('/');\n let type = input;\n\n // Verify we're using HTML5 and there's no media type mismatch\n if (!this.isHTML5 || mediaType !== this.type) {\n return false;\n }\n\n // Add codec if required\n if (Object.keys(defaultCodecs).includes(type)) {\n type += `; codecs=\"${defaultCodecs[input]}\"`;\n }\n\n try {\n return Boolean(type && this.media.canPlayType(type).replace(/no/, ''));\n } catch (_) {\n return false;\n }\n },\n\n // Check for textTracks support\n textTracks: 'textTracks' in document.createElement('video'),\n\n // <input type=\"range\"> Sliders\n rangeInput: (() => {\n const range = document.createElement('input');\n range.type = 'range';\n return range.type === 'range';\n })(),\n\n // Touch\n // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event\n touch: 'ontouchstart' in document.documentElement,\n\n // Detect transitions support\n transitions: transitionEndEvent !== false,\n\n // Reduced motion iOS & MacOS setting\n // https://webkit.org/blog/7551/responsive-design-for-motion/\n reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches,\n};\n\nexport default support;\n","// ==========================================================================\n// Event utils\n// ==========================================================================\n\nimport is from './is';\n\n// Check for passive event listener support\n// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md\n// https://www.youtube.com/watch?v=NPM6172J22g\nconst supportsPassiveListeners = (() => {\n // Test via a getter in the options object to see if the passive property is accessed\n let supported = false;\n try {\n const options = Object.defineProperty({}, 'passive', {\n get() {\n supported = true;\n return null;\n },\n });\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n } catch (_) {\n // Do nothing\n }\n\n return supported;\n})();\n\n// Toggle event listener\nexport function toggleListener(element, event, callback, toggle = false, passive = true, capture = false) {\n // Bail if no element, event, or callback\n if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) {\n return;\n }\n\n // Allow multiple events\n const events = event.split(' ');\n // Build options\n // Default to just the capture boolean for browsers with no passive listener support\n let options = capture;\n\n // If passive events listeners are supported\n if (supportsPassiveListeners) {\n options = {\n // Whether the listener can be passive (i.e. default never prevented)\n passive,\n // Whether the listener is a capturing listener or not\n capture,\n };\n }\n\n // If a single node is passed, bind the event listener\n events.forEach((type) => {\n if (this && this.eventListeners && toggle) {\n // Cache event listener\n this.eventListeners.push({ element, type, callback, options });\n }\n\n element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options);\n });\n}\n\n// Bind event handler\nexport function on(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, true, passive, capture);\n}\n\n// Unbind event handler\nexport function off(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, false, passive, capture);\n}\n\n// Bind once-only event handler\nexport function once(element, events = '', callback, passive = true, capture = false) {\n const onceCallback = (...args) => {\n off(element, events, onceCallback, passive, capture);\n callback.apply(this, args);\n };\n\n toggleListener.call(this, element, events, onceCallback, true, passive, capture);\n}\n\n// Trigger event\nexport function triggerEvent(element, type = '', bubbles = false, detail = {}) {\n // Bail if no element\n if (!is.element(element) || is.empty(type)) {\n return;\n }\n\n // Create and dispatch the event\n const event = new CustomEvent(type, {\n bubbles,\n detail: { ...detail, plyr: this },\n });\n\n // Dispatch the event\n element.dispatchEvent(event);\n}\n\n// Unbind all cached event listeners\nexport function unbindListeners() {\n if (this && this.eventListeners) {\n this.eventListeners.forEach((item) => {\n const { element, type, callback, options } = item;\n element.removeEventListener(type, callback, options);\n });\n\n this.eventListeners = [];\n }\n}\n\n// Run method when / if player is ready\nexport function ready() {\n return new Promise((resolve) =>\n this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve),\n ).then(() => {});\n}\n","import is from './is';\n/**\n * Silence a Promise-like object.\n * This is useful for avoiding non-harmful, but potentially confusing \"uncaught\n * play promise\" rejection error messages.\n * @param {Object} value An object that may or may not be `Promise`-like.\n */\nexport function silencePromise(value) {\n if (is.promise(value)) {\n value.then(null, () => {});\n }\n}\n\nexport default { silencePromise };\n","// ==========================================================================\n// Array utils\n// ==========================================================================\n\nimport is from './is';\n\n// Remove duplicates in an array\nexport function dedupe(array) {\n if (!is.array(array)) {\n return array;\n }\n\n return array.filter((item, index) => array.indexOf(item) === index);\n}\n\n// Get the closest value in an array\nexport function closest(array, value) {\n if (!is.array(array) || !array.length) {\n return null;\n }\n\n return array.reduce((prev, curr) => (Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev));\n}\n","// ==========================================================================\n// Style utils\n// ==========================================================================\n\nimport { closest } from './arrays';\nimport is from './is';\n\n// Check support for a CSS declaration\nexport function supportsCSS(declaration) {\n if (!window || !window.CSS) {\n return false;\n }\n\n return window.CSS.supports(declaration);\n}\n\n// Standard/common aspect ratios\nconst standardRatios = [\n [1, 1],\n [4, 3],\n [3, 4],\n [5, 4],\n [4, 5],\n [3, 2],\n [2, 3],\n [16, 10],\n [10, 16],\n [16, 9],\n [9, 16],\n [21, 9],\n [9, 21],\n [32, 9],\n [9, 32],\n].reduce((out, [x, y]) => ({ ...out, [x / y]: [x, y] }), {});\n\n// Validate an aspect ratio\nexport function validateAspectRatio(input) {\n if (!is.array(input) && (!is.string(input) || !input.includes(':'))) {\n return false;\n }\n\n const ratio = is.array(input) ? input : input.split(':');\n\n return ratio.map(Number).every(is.number);\n}\n\n// Reduce an aspect ratio to it's lowest form\nexport function reduceAspectRatio(ratio) {\n if (!is.array(ratio) || !ratio.every(is.number)) {\n return null;\n }\n\n const [width, height] = ratio;\n const getDivider = (w, h) => (h === 0 ? w : getDivider(h, w % h));\n const divider = getDivider(width, height);\n\n return [width / divider, height / divider];\n}\n\n// Calculate an aspect ratio\nexport function getAspectRatio(input) {\n const parse = (ratio) => (validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null);\n // Try provided ratio\n let ratio = parse(input);\n\n // Get from config\n if (ratio === null) {\n ratio = parse(this.config.ratio);\n }\n\n // Get from embed\n if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) {\n ({ ratio } = this.embed);\n }\n\n // Get from HTML5 video\n if (ratio === null && this.isHTML5) {\n const { videoWidth, videoHeight } = this.media;\n ratio = [videoWidth, videoHeight];\n }\n\n return reduceAspectRatio(ratio);\n}\n\n// Set aspect ratio for responsive container\nexport function setAspectRatio(input) {\n if (!this.isVideo) {\n return {};\n }\n\n const { wrapper } = this.elements;\n const ratio = getAspectRatio.call(this, input);\n\n if (!is.array(ratio)) {\n return {};\n }\n\n const [x, y] = reduceAspectRatio(ratio);\n const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`);\n const padding = (100 / x) * y;\n\n if (useNative) {\n wrapper.style.aspectRatio = `${x}/${y}`;\n } else {\n wrapper.style.paddingBottom = `${padding}%`;\n }\n\n // For Vimeo we have an extra <div> to hide the standard controls and UI\n if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) {\n const height = (100 / this.media.offsetWidth) * parseInt(window.getComputedStyle(this.media).paddingBottom, 10);\n const offset = (height - padding) / (height / 50);\n\n if (this.fullscreen.active) {\n wrapper.style.paddingBottom = null;\n } else {\n this.media.style.transform = `translateY(-${offset}%)`;\n }\n } else if (this.isHTML5) {\n wrapper.classList.add(this.config.classNames.videoFixedRatio);\n }\n\n return { padding, ratio };\n}\n\n// Round an aspect ratio to closest standard ratio\nexport function roundAspectRatio(x, y, tolerance = 0.05) {\n const ratio = x / y;\n const closestRatio = closest(Object.keys(standardRatios), ratio);\n\n // Check match is within tolerance\n if (Math.abs(closestRatio - ratio) <= tolerance) {\n return standardRatios[closestRatio];\n }\n\n // No match\n return [x, y];\n}\n\n// Get the size of the viewport\n// https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions\nexport function getViewportSize() {\n const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);\n const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);\n return [width, height];\n}\n","// ==========================================================================\n// Plyr HTML5 helpers\n// ==========================================================================\n\nimport support from './support';\nimport { removeElement } from './utils/elements';\nimport { triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\nimport { setAspectRatio } from './utils/style';\n\nconst html5 = {\n getSources() {\n if (!this.isHTML5) {\n return [];\n }\n\n const sources = Array.from(this.media.querySelectorAll('source'));\n\n // Filter out unsupported sources (if type is specified)\n return sources.filter((source) => {\n const type = source.getAttribute('type');\n\n if (is.empty(type)) {\n return true;\n }\n\n return support.mime.call(this, type);\n });\n },\n\n // Get quality levels\n getQualityOptions() {\n // Whether we're forcing all options (e.g. for streaming)\n if (this.config.quality.forced) {\n return this.config.quality.options;\n }\n\n // Get sizes from <source> elements\n return html5.getSources\n .call(this)\n .map((source) => Number(source.getAttribute('data-res')))\n .filter(Boolean);\n },\n\n setup() {\n if (!this.isHTML5) {\n return;\n }\n\n const player = this;\n\n // Set speed options from config\n player.options.speed = player.config.speed.options;\n\n // Set aspect ratio if fixed\n if (!is.empty(this.config.ratio)) {\n setAspectRatio.call(player);\n }\n\n // Quality\n Object.defineProperty(player.media, 'quality', {\n get() {\n // Get sources\n const sources = html5.getSources.call(player);\n const source = sources.find((s) => s.getAttribute('src') === player.source);\n\n // Return size, if match is found\n return source && Number(source.getAttribute('data-res'));\n },\n set(input) {\n if (player.quality === input) {\n return;\n }\n\n // If we're using an external handler...\n if (player.config.quality.forced && is.function(player.config.quality.onChange)) {\n player.config.quality.onChange(input);\n } else {\n // Get sources\n const sources = html5.getSources.call(player);\n // Get first match for requested size\n const source = sources.find((s) => Number(s.getAttribute('data-res')) === input);\n\n // No matching source found\n if (!source) {\n return;\n }\n\n // Get current state\n const { currentTime, paused, preload, readyState, playbackRate } = player.media;\n\n // Set new source\n player.media.src = source.getAttribute('src');\n\n // Prevent loading if preload=\"none\" and the current source isn't loaded (#1044)\n if (preload !== 'none' || readyState) {\n // Restore time\n player.once('loadedmetadata', () => {\n player.speed = playbackRate;\n player.currentTime = currentTime;\n\n // Resume playing\n if (!paused) {\n silencePromise(player.play());\n }\n });\n\n // Load new source\n player.media.load();\n }\n }\n\n // Trigger change event\n triggerEvent.call(player, player.media, 'qualitychange', false, {\n quality: input,\n });\n },\n });\n },\n\n // Cancel current network requests\n // See https://github.com/sampotts/plyr/issues/174\n cancelRequests() {\n if (!this.isHTML5) {\n return;\n }\n\n // Remove child sources\n removeElement(html5.getSources.call(this));\n\n // Set blank video src attribute\n // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error\n // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection\n this.media.setAttribute('src', this.config.blankVideo);\n\n // Load the new empty source\n // This will cancel existing requests\n // See https://github.com/sampotts/plyr/issues/174\n this.media.load();\n\n // Debugging\n this.debug.log('Cancelled network requests');\n },\n};\n\nexport default html5;\n","// ==========================================================================\n// String utils\n// ==========================================================================\n\nimport is from './is';\n\n// Generate a random ID\nexport function generateId(prefix) {\n return `${prefix}-${Math.floor(Math.random() * 10000)}`;\n}\n\n// Format string\nexport function format(input, ...args) {\n if (is.empty(input)) {\n return input;\n }\n\n return input.toString().replace(/{(\\d+)}/g, (match, i) => args[i].toString());\n}\n\n// Get percentage\nexport function getPercentage(current, max) {\n if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) {\n return 0;\n }\n\n return ((current / max) * 100).toFixed(2);\n}\n\n// Replace all occurances of a string in a string\nexport const replaceAll = (input = '', find = '', replace = '') =>\n input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\\]/\\\\])/g, '\\\\$1'), 'g'), replace.toString());\n\n// Convert to title case\nexport const toTitleCase = (input = '') =>\n input.toString().replace(/\\w\\S*/g, (text) => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase());\n\n// Convert string to pascalCase\nexport function toPascalCase(input = '') {\n let string = input.toString();\n\n // Convert kebab case\n string = replaceAll(string, '-', ' ');\n\n // Convert snake case\n string = replaceAll(string, '_', ' ');\n\n // Convert to title case\n string = toTitleCase(string);\n\n // Convert to pascal case\n return replaceAll(string, ' ', '');\n}\n\n// Convert string to pascalCase\nexport function toCamelCase(input = '') {\n let string = input.toString();\n\n // Convert to pascal case\n string = toPascalCase(string);\n\n // Convert first character to lowercase\n return string.charAt(0).toLowerCase() + string.slice(1);\n}\n\n// Remove HTML from a string\nexport function stripHTML(source) {\n const fragment = document.createDocumentFragment();\n const element = document.createElement('div');\n fragment.appendChild(element);\n element.innerHTML = source;\n return fragment.firstChild.innerText;\n}\n\n// Like outerHTML, but also works for DocumentFragment\nexport function getHTML(element) {\n const wrapper = document.createElement('div');\n wrapper.appendChild(element);\n return wrapper.innerHTML;\n}\n","// ==========================================================================\n// Plyr internationalization\n// ==========================================================================\n\nimport is from './is';\nimport { getDeep } from './objects';\nimport { replaceAll } from './strings';\n\n// Skip i18n for abbreviations and brand names\nconst resources = {\n pip: 'PIP',\n airplay: 'AirPlay',\n html5: 'HTML5',\n vimeo: 'Vimeo',\n youtube: 'YouTube',\n};\n\nconst i18n = {\n get(key = '', config = {}) {\n if (is.empty(key) || is.empty(config)) {\n return '';\n }\n\n let string = getDeep(config.i18n, key);\n\n if (is.empty(string)) {\n if (Object.keys(resources).includes(key)) {\n return resources[key];\n }\n\n return '';\n }\n\n const replace = {\n '{seektime}': config.seekTime,\n '{title}': config.title,\n };\n\n Object.entries(replace).forEach(([k, v]) => {\n string = replaceAll(string, k, v);\n });\n\n return string;\n },\n};\n\nexport default i18n;\n","// ==========================================================================\n// Plyr storage\n// ==========================================================================\n\nimport is from './utils/is';\nimport { extend } from './utils/objects';\n\nclass Storage {\n constructor(player) {\n this.enabled = player.config.storage.enabled;\n this.key = player.config.storage.key;\n }\n\n // Check for actual support (see if we can use it)\n static get supported() {\n try {\n if (!('localStorage' in window)) {\n return false;\n }\n\n const test = '___test';\n\n // Try to use it (it might be disabled, e.g. user is in private mode)\n // see: https://github.com/sampotts/plyr/issues/131\n window.localStorage.setItem(test, test);\n window.localStorage.removeItem(test);\n\n return true;\n } catch (_) {\n return false;\n }\n }\n\n get = (key) => {\n if (!Storage.supported || !this.enabled) {\n return null;\n }\n\n const store = window.localStorage.getItem(this.key);\n\n if (is.empty(store)) {\n return null;\n }\n\n const json = JSON.parse(store);\n\n return is.string(key) && key.length ? json[key] : json;\n };\n\n set = (object) => {\n // Bail if we don't have localStorage support or it's disabled\n if (!Storage.supported || !this.enabled) {\n return;\n }\n\n // Can only store objectst\n if (!is.object(object)) {\n return;\n }\n\n // Get current storage\n let storage = this.get();\n\n // Default to empty object\n if (is.empty(storage)) {\n storage = {};\n }\n\n // Update the working copy of the values\n extend(storage, object);\n\n // Update storage\n try {\n window.localStorage.setItem(this.key, JSON.stringify(storage));\n } catch (_) {\n // Do nothing\n }\n };\n}\n\nexport default Storage;\n","// ==========================================================================\n// Fetch wrapper\n// Using XHR to avoid issues with older browsers\n// ==========================================================================\n\nexport default function fetch(url, responseType = 'text') {\n return new Promise((resolve, reject) => {\n try {\n const request = new XMLHttpRequest();\n\n // Check for CORS support\n if (!('withCredentials' in request)) {\n return;\n }\n\n request.addEventListener('load', () => {\n if (responseType === 'text') {\n try {\n resolve(JSON.parse(request.responseText));\n } catch (_) {\n resolve(request.responseText);\n }\n } else {\n resolve(request.response);\n }\n });\n\n request.addEventListener('error', () => {\n throw new Error(request.status);\n });\n\n request.open('GET', url, true);\n\n // Set the required response type\n request.responseType = responseType;\n\n request.send();\n } catch (error) {\n reject(error);\n }\n });\n}\n","// ==========================================================================\n// Sprite loader\n// ==========================================================================\n\nimport Storage from '../storage';\nimport fetch from './fetch';\nimport is from './is';\n\n// Load an external SVG sprite\nexport default function loadSprite(url, id) {\n if (!is.string(url)) {\n return;\n }\n\n const prefix = 'cache';\n const hasId = is.string(id);\n let isCached = false;\n const exists = () => document.getElementById(id) !== null;\n\n const update = (container, data) => {\n // eslint-disable-next-line no-param-reassign\n container.innerHTML = data;\n\n // Check again incase of race condition\n if (hasId && exists()) {\n return;\n }\n\n // Inject the SVG to the body\n document.body.insertAdjacentElement('afterbegin', container);\n };\n\n // Only load once if ID set\n if (!hasId || !exists()) {\n const useStorage = Storage.supported;\n // Create container\n const container = document.createElement('div');\n container.setAttribute('hidden', '');\n\n if (hasId) {\n container.setAttribute('id', id);\n }\n\n // Check in cache\n if (useStorage) {\n const cached = window.localStorage.getItem(`${prefix}-${id}`);\n isCached = cached !== null;\n\n if (isCached) {\n const data = JSON.parse(cached);\n update(container, data.content);\n }\n }\n\n // Get the sprite\n fetch(url)\n .then((result) => {\n if (is.empty(result)) {\n return;\n }\n\n if (useStorage) {\n try {\n window.localStorage.setItem(\n `${prefix}-${id}`,\n JSON.stringify({\n content: result,\n }),\n );\n } catch (_) {\n // Do nothing\n }\n }\n\n update(container, result);\n })\n .catch(() => {});\n }\n}\n","// ==========================================================================\n// Time utils\n// ==========================================================================\n\nimport is from './is';\n\n// Time helpers\nexport const getHours = (value) => Math.trunc((value / 60 / 60) % 60, 10);\nexport const getMinutes = (value) => Math.trunc((value / 60) % 60, 10);\nexport const getSeconds = (value) => Math.trunc(value % 60, 10);\n\n// Format time to UI friendly string\nexport function formatTime(time = 0, displayHours = false, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return formatTime(undefined, displayHours, inverted);\n }\n\n // Format time component to add leading zero\n const format = (value) => `0${value}`.slice(-2);\n // Breakdown to hours, mins, secs\n let hours = getHours(time);\n const mins = getMinutes(time);\n const secs = getSeconds(time);\n\n // Do we need to display hours?\n if (displayHours || hours > 0) {\n hours = `${hours}:`;\n } else {\n hours = '';\n }\n\n // Render\n return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`;\n}\n","// ==========================================================================\n// Plyr controls\n// TODO: This needs to be split into smaller files and cleaned up\n// ==========================================================================\n\nimport RangeTouch from 'rangetouch';\n\nimport captions from './captions';\nimport html5 from './html5';\nimport support from './support';\nimport { repaint, transitionEndEvent } from './utils/animation';\nimport { dedupe } from './utils/arrays';\nimport browser from './utils/browser';\nimport {\n createElement,\n emptyElement,\n getAttributesFromSelector,\n getElement,\n getElements,\n hasClass,\n matches,\n removeElement,\n setAttributes,\n setFocus,\n toggleClass,\n toggleHidden,\n} from './utils/elements';\nimport { off, on } from './utils/events';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport loadSprite from './utils/load-sprite';\nimport { extend } from './utils/objects';\nimport { getPercentage, replaceAll, toCamelCase, toTitleCase } from './utils/strings';\nimport { formatTime, getHours } from './utils/time';\n\n// TODO: Don't export a massive object - break down and create class\nconst controls = {\n // Get icon URL\n getIconUrl() {\n const url = new URL(this.config.iconUrl, window.location);\n const host = window.location.host ? window.location.host : window.top.location.host;\n const cors = url.host !== host || (browser.isIE && !window.svg4everybody);\n\n return {\n url: this.config.iconUrl,\n cors,\n };\n },\n\n // Find the UI controls\n findElements() {\n try {\n this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper);\n\n // Buttons\n this.elements.buttons = {\n play: getElements.call(this, this.config.selectors.buttons.play),\n pause: getElement.call(this, this.config.selectors.buttons.pause),\n restart: getElement.call(this, this.config.selectors.buttons.restart),\n rewind: getElement.call(this, this.config.selectors.buttons.rewind),\n fastForward: getElement.call(this, this.config.selectors.buttons.fastForward),\n mute: getElement.call(this, this.config.selectors.buttons.mute),\n pip: getElement.call(this, this.config.selectors.buttons.pip),\n airplay: getElement.call(this, this.config.selectors.buttons.airplay),\n settings: getElement.call(this, this.config.selectors.buttons.settings),\n captions: getElement.call(this, this.config.selectors.buttons.captions),\n fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen),\n };\n\n // Progress\n this.elements.progress = getElement.call(this, this.config.selectors.progress);\n\n // Inputs\n this.elements.inputs = {\n seek: getElement.call(this, this.config.selectors.inputs.seek),\n volume: getElement.call(this, this.config.selectors.inputs.volume),\n };\n\n // Display\n this.elements.display = {\n buffer: getElement.call(this, this.config.selectors.display.buffer),\n currentTime: getElement.call(this, this.config.selectors.display.currentTime),\n duration: getElement.call(this, this.config.selectors.display.duration),\n };\n\n // Seek tooltip\n if (is.element(this.elements.progress)) {\n this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`);\n }\n\n return true;\n } catch (error) {\n // Log it\n this.debug.warn('It looks like there is a problem with your custom controls HTML', error);\n\n // Restore native video controls\n this.toggleNativeControls(true);\n\n return false;\n }\n },\n\n // Create <svg> icon\n createIcon(type, attributes) {\n const namespace = 'http://www.w3.org/2000/svg';\n const iconUrl = controls.getIconUrl.call(this);\n const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`;\n // Create <svg>\n const icon = document.createElementNS(namespace, 'svg');\n setAttributes(\n icon,\n extend(attributes, {\n 'aria-hidden': 'true',\n focusable: 'false',\n }),\n );\n\n // Create the <use> to reference sprite\n const use = document.createElementNS(namespace, 'use');\n const path = `${iconPath}-${type}`;\n\n // Set `href` attributes\n // https://github.com/sampotts/plyr/issues/460\n // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href\n if ('href' in use) {\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path);\n }\n\n // Always set the older attribute even though it's \"deprecated\" (it'll be around for ages)\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path);\n\n // Add <use> to <svg>\n icon.appendChild(use);\n\n return icon;\n },\n\n // Create hidden text label\n createLabel(key, attr = {}) {\n const text = i18n.get(key, this.config);\n const attributes = { ...attr, class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ') };\n\n return createElement('span', attributes, text);\n },\n\n // Create a badge\n createBadge(text) {\n if (is.empty(text)) {\n return null;\n }\n\n const badge = createElement('span', {\n class: this.config.classNames.menu.value,\n });\n\n badge.appendChild(\n createElement(\n 'span',\n {\n class: this.config.classNames.menu.badge,\n },\n text,\n ),\n );\n\n return badge;\n },\n\n // Create a <button>\n createButton(buttonType, attr) {\n const attributes = extend({}, attr);\n let type = toCamelCase(buttonType);\n\n const props = {\n element: 'button',\n toggle: false,\n label: null,\n icon: null,\n labelPressed: null,\n iconPressed: null,\n };\n\n ['element', 'icon', 'label'].forEach((key) => {\n if (Object.keys(attributes).includes(key)) {\n props[key] = attributes[key];\n delete attributes[key];\n }\n });\n\n // Default to 'button' type to prevent form submission\n if (props.element === 'button' && !Object.keys(attributes).includes('type')) {\n attributes.type = 'button';\n }\n\n // Set class name\n if (Object.keys(attributes).includes('class')) {\n if (!attributes.class.split(' ').some((c) => c === this.config.classNames.control)) {\n extend(attributes, {\n class: `${attributes.class} ${this.config.classNames.control}`,\n });\n }\n } else {\n attributes.class = this.config.classNames.control;\n }\n\n // Large play button\n switch (buttonType) {\n case 'play':\n props.toggle = true;\n props.label = 'play';\n props.labelPressed = 'pause';\n props.icon = 'play';\n props.iconPressed = 'pause';\n break;\n\n case 'mute':\n props.toggle = true;\n props.label = 'mute';\n props.labelPressed = 'unmute';\n props.icon = 'volume';\n props.iconPressed = 'muted';\n break;\n\n case 'captions':\n props.toggle = true;\n props.label = 'enableCaptions';\n props.labelPressed = 'disableCaptions';\n props.icon = 'captions-off';\n props.iconPressed = 'captions-on';\n break;\n\n case 'fullscreen':\n props.toggle = true;\n props.label = 'enterFullscreen';\n props.labelPressed = 'exitFullscreen';\n props.icon = 'enter-fullscreen';\n props.iconPressed = 'exit-fullscreen';\n break;\n\n case 'play-large':\n attributes.class += ` ${this.config.classNames.control}--overlaid`;\n type = 'play';\n props.label = 'play';\n props.icon = 'play';\n break;\n\n default:\n if (is.empty(props.label)) {\n props.label = type;\n }\n if (is.empty(props.icon)) {\n props.icon = buttonType;\n }\n }\n\n const button = createElement(props.element);\n\n // Setup toggle icon and labels\n if (props.toggle) {\n // Icon\n button.appendChild(\n controls.createIcon.call(this, props.iconPressed, {\n class: 'icon--pressed',\n }),\n );\n button.appendChild(\n controls.createIcon.call(this, props.icon, {\n class: 'icon--not-pressed',\n }),\n );\n\n // Label/Tooltip\n button.appendChild(\n controls.createLabel.call(this, props.labelPressed, {\n class: 'label--pressed',\n }),\n );\n button.appendChild(\n controls.createLabel.call(this, props.label, {\n class: 'label--not-pressed',\n }),\n );\n } else {\n button.appendChild(controls.createIcon.call(this, props.icon));\n button.appendChild(controls.createLabel.call(this, props.label));\n }\n\n // Merge and set attributes\n extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes));\n setAttributes(button, attributes);\n\n // We have multiple play buttons\n if (type === 'play') {\n if (!is.array(this.elements.buttons[type])) {\n this.elements.buttons[type] = [];\n }\n\n this.elements.buttons[type].push(button);\n } else {\n this.elements.buttons[type] = button;\n }\n\n return button;\n },\n\n // Create an <input type='range'>\n createRange(type, attributes) {\n // Seek input\n const input = createElement(\n 'input',\n extend(\n getAttributesFromSelector(this.config.selectors.inputs[type]),\n {\n type: 'range',\n min: 0,\n max: 100,\n step: 0.01,\n value: 0,\n autocomplete: 'off',\n // A11y fixes for https://github.com/sampotts/plyr/issues/905\n role: 'slider',\n 'aria-label': i18n.get(type, this.config),\n 'aria-valuemin': 0,\n 'aria-valuemax': 100,\n 'aria-valuenow': 0,\n },\n attributes,\n ),\n );\n\n this.elements.inputs[type] = input;\n\n // Set the fill for webkit now\n controls.updateRangeFill.call(this, input);\n\n // Improve support on touch devices\n RangeTouch.setup(input);\n\n return input;\n },\n\n // Create a <progress>\n createProgress(type, attributes) {\n const progress = createElement(\n 'progress',\n extend(\n getAttributesFromSelector(this.config.selectors.display[type]),\n {\n min: 0,\n max: 100,\n value: 0,\n role: 'progressbar',\n 'aria-hidden': true,\n },\n attributes,\n ),\n );\n\n // Create the label inside\n if (type !== 'volume') {\n progress.appendChild(createElement('span', null, '0'));\n\n const suffixKey = {\n played: 'played',\n buffer: 'buffered',\n }[type];\n const suffix = suffixKey ? i18n.get(suffixKey, this.config) : '';\n\n progress.innerText = `% ${suffix.toLowerCase()}`;\n }\n\n this.elements.display[type] = progress;\n\n return progress;\n },\n\n // Create time display\n createTime(type, attrs) {\n const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs);\n\n const container = createElement(\n 'div',\n extend(attributes, {\n class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(),\n 'aria-label': i18n.get(type, this.config),\n }),\n '00:00',\n );\n\n // Reference for updates\n this.elements.display[type] = container;\n\n return container;\n },\n\n // Bind keyboard shortcuts for a menu item\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n bindMenuItemShortcuts(menuItem, type) {\n // Navigate through menus via arrow keys and space\n on.call(\n this,\n menuItem,\n 'keydown keyup',\n (event) => {\n // We only care about space and ⬆️ ⬇️️ ➡️\n if (![32, 38, 39, 40].includes(event.which)) {\n return;\n }\n\n // Prevent play / seek\n event.preventDefault();\n event.stopPropagation();\n\n // We're just here to prevent the keydown bubbling\n if (event.type === 'keydown') {\n return;\n }\n\n const isRadioButton = matches(menuItem, '[role=\"menuitemradio\"]');\n\n // Show the respective menu\n if (!isRadioButton && [32, 39].includes(event.which)) {\n controls.showMenuPanel.call(this, type, true);\n } else {\n let target;\n\n if (event.which !== 32) {\n if (event.which === 40 || (isRadioButton && event.which === 39)) {\n target = menuItem.nextElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.firstElementChild;\n }\n } else {\n target = menuItem.previousElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.lastElementChild;\n }\n }\n\n setFocus.call(this, target, true);\n }\n }\n },\n false,\n );\n\n // Enter will fire a `click` event but we still need to manage focus\n // So we bind to keyup which fires after and set focus here\n on.call(this, menuItem, 'keyup', (event) => {\n if (event.which !== 13) {\n return;\n }\n\n controls.focusFirstMenuItem.call(this, null, true);\n });\n },\n\n // Create a settings menu item\n createMenuItem({ value, list, type, title, badge = null, checked = false }) {\n const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]);\n\n const menuItem = createElement(\n 'button',\n extend(attributes, {\n type: 'button',\n role: 'menuitemradio',\n class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(),\n 'aria-checked': checked,\n value,\n }),\n );\n\n const flex = createElement('span');\n\n // We have to set as HTML incase of special characters\n flex.innerHTML = title;\n\n if (is.element(badge)) {\n flex.appendChild(badge);\n }\n\n menuItem.appendChild(flex);\n\n // Replicate radio button behaviour\n Object.defineProperty(menuItem, 'checked', {\n enumerable: true,\n get() {\n return menuItem.getAttribute('aria-checked') === 'true';\n },\n set(check) {\n // Ensure exclusivity\n if (check) {\n Array.from(menuItem.parentNode.children)\n .filter((node) => matches(node, '[role=\"menuitemradio\"]'))\n .forEach((node) => node.setAttribute('aria-checked', 'false'));\n }\n\n menuItem.setAttribute('aria-checked', check ? 'true' : 'false');\n },\n });\n\n this.listeners.bind(\n menuItem,\n 'click keyup',\n (event) => {\n if (is.keyboardEvent(event) && event.which !== 32) {\n return;\n }\n\n event.preventDefault();\n event.stopPropagation();\n\n menuItem.checked = true;\n\n switch (type) {\n case 'language':\n this.currentTrack = Number(value);\n break;\n\n case 'quality':\n this.quality = value;\n break;\n\n case 'speed':\n this.speed = parseFloat(value);\n break;\n\n default:\n break;\n }\n\n controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event));\n },\n type,\n false,\n );\n\n controls.bindMenuItemShortcuts.call(this, menuItem, type);\n\n list.appendChild(menuItem);\n },\n\n // Format a time for display\n formatTime(time = 0, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return time;\n }\n\n // Always display hours if duration is over an hour\n const forceHours = getHours(this.duration) > 0;\n\n return formatTime(time, forceHours, inverted);\n },\n\n // Update the displayed time\n updateTimeDisplay(target = null, time = 0, inverted = false) {\n // Bail if there's no element to display or the value isn't a number\n if (!is.element(target) || !is.number(time)) {\n return;\n }\n\n // eslint-disable-next-line no-param-reassign\n target.innerText = controls.formatTime(time, inverted);\n },\n\n // Update volume UI and storage\n updateVolume() {\n if (!this.supported.ui) {\n return;\n }\n\n // Update range\n if (is.element(this.elements.inputs.volume)) {\n controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);\n }\n\n // Update mute state\n if (is.element(this.elements.buttons.mute)) {\n this.elements.buttons.mute.pressed = this.muted || this.volume === 0;\n }\n },\n\n // Update seek value and lower fill\n setRange(target, value = 0) {\n if (!is.element(target)) {\n return;\n }\n\n // eslint-disable-next-line\n target.value = value;\n\n // Webkit range fill\n controls.updateRangeFill.call(this, target);\n },\n\n // Update <progress> elements\n updateProgress(event) {\n if (!this.supported.ui || !is.event(event)) {\n return;\n }\n\n let value = 0;\n\n const setProgress = (target, input) => {\n const val = is.number(input) ? input : 0;\n const progress = is.element(target) ? target : this.elements.display.buffer;\n\n // Update value and label\n if (is.element(progress)) {\n progress.value = val;\n\n // Update text label inside\n const label = progress.getElementsByTagName('span')[0];\n if (is.element(label)) {\n label.childNodes[0].nodeValue = val;\n }\n }\n };\n\n if (event) {\n switch (event.type) {\n // Video playing\n case 'timeupdate':\n case 'seeking':\n case 'seeked':\n value = getPercentage(this.currentTime, this.duration);\n\n // Set seek range value only if it's a 'natural' time event\n if (event.type === 'timeupdate') {\n controls.setRange.call(this, this.elements.inputs.seek, value);\n }\n\n break;\n\n // Check buffer status\n case 'playing':\n case 'progress':\n setProgress(this.elements.display.buffer, this.buffered * 100);\n\n break;\n\n default:\n break;\n }\n }\n },\n\n // Webkit polyfill for lower fill range\n updateRangeFill(target) {\n // Get range from event if event passed\n const range = is.event(target) ? target.target : target;\n\n // Needs to be a valid <input type='range'>\n if (!is.element(range) || range.getAttribute('type') !== 'range') {\n return;\n }\n\n // Set aria values for https://github.com/sampotts/plyr/issues/905\n if (matches(range, this.config.selectors.inputs.seek)) {\n range.setAttribute('aria-valuenow', this.currentTime);\n const currentTime = controls.formatTime(this.currentTime);\n const duration = controls.formatTime(this.duration);\n const format = i18n.get('seekLabel', this.config);\n range.setAttribute(\n 'aria-valuetext',\n format.replace('{currentTime}', currentTime).replace('{duration}', duration),\n );\n } else if (matches(range, this.config.selectors.inputs.volume)) {\n const percent = range.value * 100;\n range.setAttribute('aria-valuenow', percent);\n range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`);\n } else {\n range.setAttribute('aria-valuenow', range.value);\n }\n\n // WebKit only\n if (!browser.isWebkit) {\n return;\n }\n\n // Set CSS custom property\n range.style.setProperty('--value', `${(range.value / range.max) * 100}%`);\n },\n\n // Update hover tooltip for seeking\n updateSeekTooltip(event) {\n // Bail if setting not true\n if (\n !this.config.tooltips.seek ||\n !is.element(this.elements.inputs.seek) ||\n !is.element(this.elements.display.seekTooltip) ||\n this.duration === 0\n ) {\n return;\n }\n\n const visible = `${this.config.classNames.tooltip}--visible`;\n const toggle = (show) => toggleClass(this.elements.display.seekTooltip, visible, show);\n\n // Hide on touch\n if (this.touch) {\n toggle(false);\n return;\n }\n\n // Determine percentage, if already visible\n let percent = 0;\n const clientRect = this.elements.progress.getBoundingClientRect();\n\n if (is.event(event)) {\n percent = (100 / clientRect.width) * (event.pageX - clientRect.left);\n } else if (hasClass(this.elements.display.seekTooltip, visible)) {\n percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);\n } else {\n return;\n }\n\n // Set bounds\n if (percent < 0) {\n percent = 0;\n } else if (percent > 100) {\n percent = 100;\n }\n\n // Display the time a click would seek to\n controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, (this.duration / 100) * percent);\n\n // Set position\n this.elements.display.seekTooltip.style.left = `${percent}%`;\n\n // Show/hide the tooltip\n // If the event is a moues in/out and percentage is inside bounds\n if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) {\n toggle(event.type === 'mouseenter');\n }\n },\n\n // Handle time change event\n timeUpdate(event) {\n // Only invert if only one time element is displayed and used for both duration and currentTime\n const invert = !is.element(this.elements.display.duration) && this.config.invertTime;\n\n // Duration\n controls.updateTimeDisplay.call(\n this,\n this.elements.display.currentTime,\n invert ? this.duration - this.currentTime : this.currentTime,\n invert,\n );\n\n // Ignore updates while seeking\n if (event && event.type === 'timeupdate' && this.media.seeking) {\n return;\n }\n\n // Playing progress\n controls.updateProgress.call(this, event);\n },\n\n // Show the duration on metadataloaded or durationchange events\n durationUpdate() {\n // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false\n if (!this.supported.ui || (!this.config.invertTime && this.currentTime)) {\n return;\n }\n\n // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar.\n // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415\n // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062\n // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338\n if (this.duration >= 2 ** 32) {\n toggleHidden(this.elements.display.currentTime, true);\n toggleHidden(this.elements.progress, true);\n return;\n }\n\n // Update ARIA values\n if (is.element(this.elements.inputs.seek)) {\n this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration);\n }\n\n // If there's a spot to display duration\n const hasDuration = is.element(this.elements.display.duration);\n\n // If there's only one time display, display duration there\n if (!hasDuration && this.config.displayDuration && this.paused) {\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);\n }\n\n // If there's a duration element, update content\n if (hasDuration) {\n controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);\n }\n\n // Update the tooltip (if visible)\n controls.updateSeekTooltip.call(this);\n },\n\n // Hide/show a tab\n toggleMenuButton(setting, toggle) {\n toggleHidden(this.elements.settings.buttons[setting], !toggle);\n },\n\n // Update the selected setting\n updateSetting(setting, container, input) {\n const pane = this.elements.settings.panels[setting];\n let value = null;\n let list = container;\n\n if (setting === 'captions') {\n value = this.currentTrack;\n } else {\n value = !is.empty(input) ? input : this[setting];\n\n // Get default\n if (is.empty(value)) {\n value = this.config[setting].default;\n }\n\n // Unsupported value\n if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) {\n this.debug.warn(`Unsupported value of '${value}' for ${setting}`);\n return;\n }\n\n // Disabled value\n if (!this.config[setting].options.includes(value)) {\n this.debug.warn(`Disabled value of '${value}' for ${setting}`);\n return;\n }\n }\n\n // Get the list if we need to\n if (!is.element(list)) {\n list = pane && pane.querySelector('[role=\"menu\"]');\n }\n\n // If there's no list it means it's not been rendered...\n if (!is.element(list)) {\n return;\n }\n\n // Update the label\n const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`);\n label.innerHTML = controls.getLabel.call(this, setting, value);\n\n // Find the radio option and check it\n const target = list && list.querySelector(`[value=\"${value}\"]`);\n\n if (is.element(target)) {\n target.checked = true;\n }\n },\n\n // Translate a value into a nice label\n getLabel(setting, value) {\n switch (setting) {\n case 'speed':\n return value === 1 ? i18n.get('normal', this.config) : `${value}×`;\n\n case 'quality':\n if (is.number(value)) {\n const label = i18n.get(`qualityLabel.${value}`, this.config);\n\n if (!label.length) {\n return `${value}p`;\n }\n\n return label;\n }\n\n return toTitleCase(value);\n\n case 'captions':\n return captions.getLabel.call(this);\n\n default:\n return null;\n }\n },\n\n // Set the quality menu\n setQualityMenu(options) {\n // Menu required\n if (!is.element(this.elements.settings.panels.quality)) {\n return;\n }\n\n const type = 'quality';\n const list = this.elements.settings.panels.quality.querySelector('[role=\"menu\"]');\n\n // Set options if passed and filter based on uniqueness and config\n if (is.array(options)) {\n this.options.quality = dedupe(options).filter((quality) => this.config.quality.options.includes(quality));\n }\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1;\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If we're hiding, nothing more to do\n if (!toggle) {\n return;\n }\n\n // Get the badge HTML for HD, 4K etc\n const getBadge = (quality) => {\n const label = i18n.get(`qualityBadge.${quality}`, this.config);\n\n if (!label.length) {\n return null;\n }\n\n return controls.createBadge.call(this, label);\n };\n\n // Sort options by the config and then render options\n this.options.quality\n .sort((a, b) => {\n const sorting = this.config.quality.options;\n return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1;\n })\n .forEach((quality) => {\n controls.createMenuItem.call(this, {\n value: quality,\n list,\n type,\n title: controls.getLabel.call(this, 'quality', quality),\n badge: getBadge(quality),\n });\n });\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Set the looping options\n /* setLoopMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.loop)) {\n return;\n }\n\n const options = ['start', 'end', 'all', 'reset'];\n const list = this.elements.settings.panels.loop.querySelector('[role=\"menu\"]');\n\n // Show the pane and tab\n toggleHidden(this.elements.settings.buttons.loop, false);\n toggleHidden(this.elements.settings.panels.loop, false);\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.loop.options);\n controls.toggleMenuButton.call(this, 'loop', toggle);\n\n // Empty the menu\n emptyElement(list);\n\n options.forEach(option => {\n const item = createElement('li');\n\n const button = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.loop), {\n type: 'button',\n class: this.config.classNames.control,\n 'data-plyr-loop-action': option,\n }),\n i18n.get(option, this.config)\n );\n\n if (['start', 'end'].includes(option)) {\n const badge = controls.createBadge.call(this, '00:00');\n button.appendChild(badge);\n }\n\n item.appendChild(button);\n list.appendChild(item);\n });\n }, */\n\n // Get current selected caption language\n // TODO: rework this to user the getter in the API?\n\n // Set a list of available captions languages\n setCaptionsMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.captions)) {\n return;\n }\n\n // TODO: Captions or language? Currently it's mixed\n const type = 'captions';\n const list = this.elements.settings.panels.captions.querySelector('[role=\"menu\"]');\n const tracks = captions.getTracks.call(this);\n const toggle = Boolean(tracks.length);\n\n // Toggle the pane and tab\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If there's no captions, bail\n if (!toggle) {\n return;\n }\n\n // Generate options data\n const options = tracks.map((track, value) => ({\n value,\n checked: this.captions.toggled && this.currentTrack === value,\n title: captions.getLabel.call(this, track),\n badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()),\n list,\n type: 'language',\n }));\n\n // Add the \"Disabled\" option to turn off captions\n options.unshift({\n value: -1,\n checked: !this.captions.toggled,\n title: i18n.get('disabled', this.config),\n list,\n type: 'language',\n });\n\n // Generate options\n options.forEach(controls.createMenuItem.bind(this));\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Set a list of available captions languages\n setSpeedMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.speed)) {\n return;\n }\n\n const type = 'speed';\n const list = this.elements.settings.panels.speed.querySelector('[role=\"menu\"]');\n\n // Filter out invalid speeds\n this.options.speed = this.options.speed.filter((o) => o >= this.minimumSpeed && o <= this.maximumSpeed);\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1;\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If we're hiding, nothing more to do\n if (!toggle) {\n return;\n }\n\n // Create items\n this.options.speed.forEach((speed) => {\n controls.createMenuItem.call(this, {\n value: speed,\n list,\n type,\n title: controls.getLabel.call(this, 'speed', speed),\n });\n });\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Check if we need to hide/show the settings menu\n checkMenu() {\n const { buttons } = this.elements.settings;\n const visible = !is.empty(buttons) && Object.values(buttons).some((button) => !button.hidden);\n\n toggleHidden(this.elements.settings.menu, !visible);\n },\n\n // Focus the first menu item in a given (or visible) menu\n focusFirstMenuItem(pane, tabFocus = false) {\n if (this.elements.settings.popup.hidden) {\n return;\n }\n\n let target = pane;\n\n if (!is.element(target)) {\n target = Object.values(this.elements.settings.panels).find((p) => !p.hidden);\n }\n\n const firstItem = target.querySelector('[role^=\"menuitem\"]');\n\n setFocus.call(this, firstItem, tabFocus);\n },\n\n // Show/hide menu\n toggleMenu(input) {\n const { popup } = this.elements.settings;\n const button = this.elements.buttons.settings;\n\n // Menu and button are required\n if (!is.element(popup) || !is.element(button)) {\n return;\n }\n\n // True toggle by default\n const { hidden } = popup;\n let show = hidden;\n\n if (is.boolean(input)) {\n show = input;\n } else if (is.keyboardEvent(input) && input.which === 27) {\n show = false;\n } else if (is.event(input)) {\n // If Plyr is in a shadowDOM, the event target is set to the component, instead of the\n // Element in the shadowDOM. The path, if available, is complete.\n const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target;\n const isMenuItem = popup.contains(target);\n\n // If the click was inside the menu or if the click\n // wasn't the button or menu item and we're trying to\n // show the menu (a doc click shouldn't show the menu)\n if (isMenuItem || (!isMenuItem && input.target !== button && show)) {\n return;\n }\n }\n\n // Set button attributes\n button.setAttribute('aria-expanded', show);\n\n // Show the actual popup\n toggleHidden(popup, !show);\n\n // Add class hook\n toggleClass(this.elements.container, this.config.classNames.menu.open, show);\n\n // Focus the first item if key interaction\n if (show && is.keyboardEvent(input)) {\n controls.focusFirstMenuItem.call(this, null, true);\n } else if (!show && !hidden) {\n // If closing, re-focus the button\n setFocus.call(this, button, is.keyboardEvent(input));\n }\n },\n\n // Get the natural size of a menu panel\n getMenuSize(tab) {\n const clone = tab.cloneNode(true);\n clone.style.position = 'absolute';\n clone.style.opacity = 0;\n clone.removeAttribute('hidden');\n\n // Append to parent so we get the \"real\" size\n tab.parentNode.appendChild(clone);\n\n // Get the sizes before we remove\n const width = clone.scrollWidth;\n const height = clone.scrollHeight;\n\n // Remove from the DOM\n removeElement(clone);\n\n return {\n width,\n height,\n };\n },\n\n // Show a panel in the menu\n showMenuPanel(type = '', tabFocus = false) {\n const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`);\n\n // Nothing to show, bail\n if (!is.element(target)) {\n return;\n }\n\n // Hide all other panels\n const container = target.parentNode;\n const current = Array.from(container.children).find((node) => !node.hidden);\n\n // If we can do fancy animations, we'll animate the height/width\n if (support.transitions && !support.reducedMotion) {\n // Set the current width as a base\n container.style.width = `${current.scrollWidth}px`;\n container.style.height = `${current.scrollHeight}px`;\n\n // Get potential sizes\n const size = controls.getMenuSize.call(this, target);\n\n // Restore auto height/width\n const restore = (event) => {\n // We're only bothered about height and width on the container\n if (event.target !== container || !['width', 'height'].includes(event.propertyName)) {\n return;\n }\n\n // Revert back to auto\n container.style.width = '';\n container.style.height = '';\n\n // Only listen once\n off.call(this, container, transitionEndEvent, restore);\n };\n\n // Listen for the transition finishing and restore auto height/width\n on.call(this, container, transitionEndEvent, restore);\n\n // Set dimensions to target\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n }\n\n // Set attributes on current tab\n toggleHidden(current, true);\n\n // Set attributes on target\n toggleHidden(target, false);\n\n // Focus the first item\n controls.focusFirstMenuItem.call(this, target, tabFocus);\n },\n\n // Set the download URL\n setDownloadUrl() {\n const button = this.elements.buttons.download;\n\n // Bail if no button\n if (!is.element(button)) {\n return;\n }\n\n // Set attribute\n button.setAttribute('href', this.download);\n },\n\n // Build the default HTML\n create(data) {\n const {\n bindMenuItemShortcuts,\n createButton,\n createProgress,\n createRange,\n createTime,\n setQualityMenu,\n setSpeedMenu,\n showMenuPanel,\n } = controls;\n this.elements.controls = null;\n\n // Larger overlaid play button\n if (is.array(this.config.controls) && this.config.controls.includes('play-large')) {\n this.elements.container.appendChild(createButton.call(this, 'play-large'));\n }\n\n // Create the container\n const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper));\n this.elements.controls = container;\n\n // Default item attributes\n const defaultAttributes = { class: 'plyr__controls__item' };\n\n // Loop through controls in order\n dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach((control) => {\n // Restart button\n if (control === 'restart') {\n container.appendChild(createButton.call(this, 'restart', defaultAttributes));\n }\n\n // Rewind button\n if (control === 'rewind') {\n container.appendChild(createButton.call(this, 'rewind', defaultAttributes));\n }\n\n // Play/Pause button\n if (control === 'play') {\n container.appendChild(createButton.call(this, 'play', defaultAttributes));\n }\n\n // Fast forward button\n if (control === 'fast-forward') {\n container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes));\n }\n\n // Progress\n if (control === 'progress') {\n const progressContainer = createElement('div', {\n class: `${defaultAttributes.class} plyr__progress__container`,\n });\n\n const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress));\n\n // Seek range slider\n progress.appendChild(\n createRange.call(this, 'seek', {\n id: `plyr-seek-${data.id}`,\n }),\n );\n\n // Buffer progress\n progress.appendChild(createProgress.call(this, 'buffer'));\n\n // TODO: Add loop display indicator\n\n // Seek tooltip\n if (this.config.tooltips.seek) {\n const tooltip = createElement(\n 'span',\n {\n class: this.config.classNames.tooltip,\n },\n '00:00',\n );\n\n progress.appendChild(tooltip);\n this.elements.display.seekTooltip = tooltip;\n }\n\n this.elements.progress = progress;\n progressContainer.appendChild(this.elements.progress);\n container.appendChild(progressContainer);\n }\n\n // Media current time display\n if (control === 'current-time') {\n container.appendChild(createTime.call(this, 'currentTime', defaultAttributes));\n }\n\n // Media duration display\n if (control === 'duration') {\n container.appendChild(createTime.call(this, 'duration', defaultAttributes));\n }\n\n // Volume controls\n if (control === 'mute' || control === 'volume') {\n let { volume } = this.elements;\n\n // Create the volume container if needed\n if (!is.element(volume) || !container.contains(volume)) {\n volume = createElement(\n 'div',\n extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__volume`.trim(),\n }),\n );\n\n this.elements.volume = volume;\n\n container.appendChild(volume);\n }\n\n // Toggle mute button\n if (control === 'mute') {\n volume.appendChild(createButton.call(this, 'mute'));\n }\n\n // Volume range control\n // Ignored on iOS as it's handled globally\n // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html\n if (control === 'volume' && !browser.isIos) {\n // Set the attributes\n const attributes = {\n max: 1,\n step: 0.05,\n value: this.config.volume,\n };\n\n // Create the volume range slider\n volume.appendChild(\n createRange.call(\n this,\n 'volume',\n extend(attributes, {\n id: `plyr-volume-${data.id}`,\n }),\n ),\n );\n }\n }\n\n // Toggle captions button\n if (control === 'captions') {\n container.appendChild(createButton.call(this, 'captions', defaultAttributes));\n }\n\n // Settings button / menu\n if (control === 'settings' && !is.empty(this.config.settings)) {\n const wrapper = createElement(\n 'div',\n extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__menu`.trim(),\n hidden: '',\n }),\n );\n\n wrapper.appendChild(\n createButton.call(this, 'settings', {\n 'aria-haspopup': true,\n 'aria-controls': `plyr-settings-${data.id}`,\n 'aria-expanded': false,\n }),\n );\n\n const popup = createElement('div', {\n class: 'plyr__menu__container',\n id: `plyr-settings-${data.id}`,\n hidden: '',\n });\n\n const inner = createElement('div');\n\n const home = createElement('div', {\n id: `plyr-settings-${data.id}-home`,\n });\n\n // Create the menu\n const menu = createElement('div', {\n role: 'menu',\n });\n\n home.appendChild(menu);\n inner.appendChild(home);\n this.elements.settings.panels.home = home;\n\n // Build the menu items\n this.config.settings.forEach((type) => {\n // TODO: bundle this with the createMenuItem helper and bindings\n const menuItem = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.settings), {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`,\n role: 'menuitem',\n 'aria-haspopup': true,\n hidden: '',\n }),\n );\n\n // Bind menu shortcuts for keyboard users\n bindMenuItemShortcuts.call(this, menuItem, type);\n\n // Show menu on click\n on.call(this, menuItem, 'click', () => {\n showMenuPanel.call(this, type, false);\n });\n\n const flex = createElement('span', null, i18n.get(type, this.config));\n\n const value = createElement('span', {\n class: this.config.classNames.menu.value,\n });\n\n // Speed contains HTML entities\n value.innerHTML = data[type];\n\n flex.appendChild(value);\n menuItem.appendChild(flex);\n menu.appendChild(menuItem);\n\n // Build the panes\n const pane = createElement('div', {\n id: `plyr-settings-${data.id}-${type}`,\n hidden: '',\n });\n\n // Back button\n const backButton = createElement('button', {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--back`,\n });\n\n // Visible label\n backButton.appendChild(\n createElement(\n 'span',\n {\n 'aria-hidden': true,\n },\n i18n.get(type, this.config),\n ),\n );\n\n // Screen reader label\n backButton.appendChild(\n createElement(\n 'span',\n {\n class: this.config.classNames.hidden,\n },\n i18n.get('menuBack', this.config),\n ),\n );\n\n // Go back via keyboard\n on.call(\n this,\n pane,\n 'keydown',\n (event) => {\n // We only care about <-\n if (event.which !== 37) {\n return;\n }\n\n // Prevent seek\n event.preventDefault();\n event.stopPropagation();\n\n // Show the respective menu\n showMenuPanel.call(this, 'home', true);\n },\n false,\n );\n\n // Go back via button click\n on.call(this, backButton, 'click', () => {\n showMenuPanel.call(this, 'home', false);\n });\n\n // Add to pane\n pane.appendChild(backButton);\n\n // Menu\n pane.appendChild(\n createElement('div', {\n role: 'menu',\n }),\n );\n\n inner.appendChild(pane);\n\n this.elements.settings.buttons[type] = menuItem;\n this.elements.settings.panels[type] = pane;\n });\n\n popup.appendChild(inner);\n wrapper.appendChild(popup);\n container.appendChild(wrapper);\n\n this.elements.settings.popup = popup;\n this.elements.settings.menu = wrapper;\n }\n\n // Picture in picture button\n if (control === 'pip' && support.pip) {\n container.appendChild(createButton.call(this, 'pip', defaultAttributes));\n }\n\n // Airplay button\n if (control === 'airplay' && support.airplay) {\n container.appendChild(createButton.call(this, 'airplay', defaultAttributes));\n }\n\n // Download button\n if (control === 'download') {\n const attributes = extend({}, defaultAttributes, {\n element: 'a',\n href: this.download,\n target: '_blank',\n });\n\n // Set download attribute for HTML5 only\n if (this.isHTML5) {\n attributes.download = '';\n }\n\n const { download } = this.config.urls;\n\n if (!is.url(download) && this.isEmbed) {\n extend(attributes, {\n icon: `logo-${this.provider}`,\n label: this.provider,\n });\n }\n\n container.appendChild(createButton.call(this, 'download', attributes));\n }\n\n // Toggle fullscreen button\n if (control === 'fullscreen') {\n container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes));\n }\n });\n\n // Set available quality levels\n if (this.isHTML5) {\n setQualityMenu.call(this, html5.getQualityOptions.call(this));\n }\n\n setSpeedMenu.call(this);\n\n return container;\n },\n\n // Insert controls\n inject() {\n // Sprite\n if (this.config.loadSprite) {\n const icon = controls.getIconUrl.call(this);\n\n // Only load external sprite using AJAX\n if (icon.cors) {\n loadSprite(icon.url, 'sprite-plyr');\n }\n }\n\n // Create a unique ID\n this.id = Math.floor(Math.random() * 10000);\n\n // Null by default\n let container = null;\n this.elements.controls = null;\n\n // Set template properties\n const props = {\n id: this.id,\n seektime: this.config.seekTime,\n title: this.config.title,\n };\n let update = true;\n\n // If function, run it and use output\n if (is.function(this.config.controls)) {\n this.config.controls = this.config.controls.call(this, props);\n }\n\n // Convert falsy controls to empty array (primarily for empty strings)\n if (!this.config.controls) {\n this.config.controls = [];\n }\n\n if (is.element(this.config.controls) || is.string(this.config.controls)) {\n // HTMLElement or Non-empty string passed as the option\n container = this.config.controls;\n } else {\n // Create controls\n container = controls.create.call(this, {\n id: this.id,\n seektime: this.config.seekTime,\n speed: this.speed,\n quality: this.quality,\n captions: captions.getLabel.call(this),\n // TODO: Looping\n // loop: 'None',\n });\n update = false;\n }\n\n // Replace props with their value\n const replace = (input) => {\n let result = input;\n\n Object.entries(props).forEach(([key, value]) => {\n result = replaceAll(result, `{${key}}`, value);\n });\n\n return result;\n };\n\n // Update markup\n if (update) {\n if (is.string(this.config.controls)) {\n container = replace(container);\n }\n }\n\n // Controls container\n let target;\n\n // Inject to custom location\n if (is.string(this.config.selectors.controls.container)) {\n target = document.querySelector(this.config.selectors.controls.container);\n }\n\n // Inject into the container by default\n if (!is.element(target)) {\n target = this.elements.container;\n }\n\n // Inject controls HTML (needs to be before captions, hence \"afterbegin\")\n const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML';\n target[insertMethod]('afterbegin', container);\n\n // Find the elements if need be\n if (!is.element(this.elements.controls)) {\n controls.findElements.call(this);\n }\n\n // Add pressed property to buttons\n if (!is.empty(this.elements.buttons)) {\n const addProperty = (button) => {\n const className = this.config.classNames.controlPressed;\n Object.defineProperty(button, 'pressed', {\n enumerable: true,\n get() {\n return hasClass(button, className);\n },\n set(pressed = false) {\n toggleClass(button, className, pressed);\n },\n });\n };\n\n // Toggle classname when pressed property is set\n Object.values(this.elements.buttons)\n .filter(Boolean)\n .forEach((button) => {\n if (is.array(button) || is.nodeList(button)) {\n Array.from(button).filter(Boolean).forEach(addProperty);\n } else {\n addProperty(button);\n }\n });\n }\n\n // Edge sometimes doesn't finish the paint so force a repaint\n if (browser.isEdge) {\n repaint(target);\n }\n\n // Setup tooltips\n if (this.config.tooltips.controls) {\n const { classNames, selectors } = this.config;\n const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`;\n const labels = getElements.call(this, selector);\n\n Array.from(labels).forEach((label) => {\n toggleClass(label, this.config.classNames.hidden, false);\n toggleClass(label, this.config.classNames.tooltip, true);\n });\n }\n },\n};\n\nexport default controls;\n","// ==========================================================================\n// URL utils\n// ==========================================================================\n\nimport is from './is';\n\n/**\n * Parse a string to a URL object\n * @param {String} input - the URL to be parsed\n * @param {Boolean} safe - failsafe parsing\n */\nexport function parseUrl(input, safe = true) {\n let url = input;\n\n if (safe) {\n const parser = document.createElement('a');\n parser.href = url;\n url = parser.href;\n }\n\n try {\n return new URL(url);\n } catch (_) {\n return null;\n }\n}\n\n// Convert object to URLSearchParams\nexport function buildUrlParams(input) {\n const params = new URLSearchParams();\n\n if (is.object(input)) {\n Object.entries(input).forEach(([key, value]) => {\n params.set(key, value);\n });\n }\n\n return params;\n}\n","// ==========================================================================\n// Plyr Captions\n// TODO: Create as class\n// ==========================================================================\n\nimport controls from './controls';\nimport support from './support';\nimport { dedupe } from './utils/arrays';\nimport browser from './utils/browser';\nimport {\n createElement,\n emptyElement,\n getAttributesFromSelector,\n insertAfter,\n removeElement,\n toggleClass,\n} from './utils/elements';\nimport { on, triggerEvent } from './utils/events';\nimport fetch from './utils/fetch';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport { getHTML } from './utils/strings';\nimport { parseUrl } from './utils/urls';\n\nconst captions = {\n // Setup captions\n setup() {\n // Requires UI support\n if (!this.supported.ui) {\n return;\n }\n\n // Only Vimeo and HTML5 video supported at this point\n if (!this.isVideo || this.isYouTube || (this.isHTML5 && !support.textTracks)) {\n // Clear menu and hide\n if (\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n this.config.settings.includes('captions')\n ) {\n controls.setCaptionsMenu.call(this);\n }\n\n return;\n }\n\n // Inject the container\n if (!is.element(this.elements.captions)) {\n this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions));\n\n insertAfter(this.elements.captions, this.elements.wrapper);\n }\n\n // Fix IE captions if CORS is used\n // Fetch captions and inject as blobs instead (data URIs not supported!)\n if (browser.isIE && window.URL) {\n const elements = this.media.querySelectorAll('track');\n\n Array.from(elements).forEach((track) => {\n const src = track.getAttribute('src');\n const url = parseUrl(src);\n\n if (\n url !== null &&\n url.hostname !== window.location.href.hostname &&\n ['http:', 'https:'].includes(url.protocol)\n ) {\n fetch(src, 'blob')\n .then((blob) => {\n track.setAttribute('src', window.URL.createObjectURL(blob));\n })\n .catch(() => {\n removeElement(track);\n });\n }\n });\n }\n\n // Get and set initial data\n // The \"preferred\" options are not realized unless / until the wanted language has a match\n // * languages: Array of user's browser languages.\n // * language: The language preferred by user settings or config\n // * active: The state preferred by user settings or config\n // * toggled: The real captions state\n\n const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en'];\n const languages = dedupe(browserLanguages.map((language) => language.split('-')[0]));\n let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase();\n\n // Use first browser language when language is 'auto'\n if (language === 'auto') {\n [language] = languages;\n }\n\n let active = this.storage.get('captions');\n if (!is.boolean(active)) {\n ({ active } = this.config.captions);\n }\n\n Object.assign(this.captions, {\n toggled: false,\n active,\n language,\n languages,\n });\n\n // Watch changes to textTracks and update captions menu\n if (this.isHTML5) {\n const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack';\n on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this));\n }\n\n // Update available languages in list next tick (the event must not be triggered before the listeners)\n setTimeout(captions.update.bind(this), 0);\n },\n\n // Update available language options in settings based on tracks\n update() {\n const tracks = captions.getTracks.call(this, true);\n // Get the wanted language\n const { active, language, meta, currentTrackNode } = this.captions;\n const languageExists = Boolean(tracks.find((track) => track.language === language));\n\n // Handle tracks (add event listener and \"pseudo\"-default)\n if (this.isHTML5 && this.isVideo) {\n tracks\n .filter((track) => !meta.get(track))\n .forEach((track) => {\n this.debug.log('Track added', track);\n\n // Attempt to store if the original dom element was \"default\"\n meta.set(track, {\n default: track.mode === 'showing',\n });\n\n // Turn off native caption rendering to avoid double captions\n // Note: mode='hidden' forces a track to download. To ensure every track\n // isn't downloaded at once, only 'showing' tracks should be reassigned\n // eslint-disable-next-line no-param-reassign\n if (track.mode === 'showing') {\n // eslint-disable-next-line no-param-reassign\n track.mode = 'hidden';\n }\n\n // Add event listener for cue changes\n on.call(this, track, 'cuechange', () => captions.updateCues.call(this));\n });\n }\n\n // Update language first time it matches, or if the previous matching track was removed\n if ((languageExists && this.language !== language) || !tracks.includes(currentTrackNode)) {\n captions.setLanguage.call(this, language);\n captions.toggle.call(this, active && languageExists);\n }\n\n // Enable or disable captions based on track length\n if (this.elements) {\n toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks));\n }\n\n // Update available languages in list\n if (\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n this.config.settings.includes('captions')\n ) {\n controls.setCaptionsMenu.call(this);\n }\n },\n\n // Toggle captions display\n // Used internally for the toggleCaptions method, with the passive option forced to false\n toggle(input, passive = true) {\n // If there's no full support\n if (!this.supported.ui) {\n return;\n }\n\n const { toggled } = this.captions; // Current state\n const activeClass = this.config.classNames.captions.active;\n // Get the next state\n // If the method is called without parameter, toggle based on current value\n const active = is.nullOrUndefined(input) ? !toggled : input;\n\n // Update state and trigger event\n if (active !== toggled) {\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.active = active;\n this.storage.set({ captions: active });\n }\n\n // Force language if the call isn't passive and there is no matching language to toggle to\n if (!this.language && active && !passive) {\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true);\n\n // Override user preferences to avoid switching languages if a matching track is added\n this.captions.language = track.language;\n\n // Set caption, but don't store in localStorage as user preference\n captions.set.call(this, tracks.indexOf(track));\n return;\n }\n\n // Toggle button if it's enabled\n if (this.elements.buttons.captions) {\n this.elements.buttons.captions.pressed = active;\n }\n\n // Add class hook\n toggleClass(this.elements.container, activeClass, active);\n\n this.captions.toggled = active;\n\n // Update settings menu\n controls.updateSetting.call(this, 'captions');\n\n // Trigger event (not used internally)\n triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled');\n }\n\n // Wait for the call stack to clear before setting mode='hidden'\n // on the active track - forcing the browser to download it\n setTimeout(() => {\n if (active && this.captions.toggled) {\n this.captions.currentTrackNode.mode = 'hidden';\n }\n });\n },\n\n // Set captions by track index\n // Used internally for the currentTrack setter with the passive option forced to false\n set(index, passive = true) {\n const tracks = captions.getTracks.call(this);\n\n // Disable captions if setting to -1\n if (index === -1) {\n captions.toggle.call(this, false, passive);\n return;\n }\n\n if (!is.number(index)) {\n this.debug.warn('Invalid caption argument', index);\n return;\n }\n\n if (!(index in tracks)) {\n this.debug.warn('Track not found', index);\n return;\n }\n\n if (this.captions.currentTrack !== index) {\n this.captions.currentTrack = index;\n const track = tracks[index];\n const { language } = track || {};\n\n // Store reference to node for invalidation on remove\n this.captions.currentTrackNode = track;\n\n // Update settings menu\n controls.updateSetting.call(this, 'captions');\n\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.language = language;\n this.storage.set({ language });\n }\n\n // Handle Vimeo captions\n if (this.isVimeo) {\n this.embed.enableTextTrack(language);\n }\n\n // Trigger event\n triggerEvent.call(this, this.media, 'languagechange');\n }\n\n // Show captions\n captions.toggle.call(this, true, passive);\n\n if (this.isHTML5 && this.isVideo) {\n // If we change the active track while a cue is already displayed we need to update it\n captions.updateCues.call(this);\n }\n },\n\n // Set captions by language\n // Used internally for the language setter with the passive option forced to false\n setLanguage(input, passive = true) {\n if (!is.string(input)) {\n this.debug.warn('Invalid language argument', input);\n return;\n }\n // Normalize\n const language = input.toLowerCase();\n this.captions.language = language;\n\n // Set currentTrack\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [language]);\n captions.set.call(this, tracks.indexOf(track), passive);\n },\n\n // Get current valid caption tracks\n // If update is false it will also ignore tracks without metadata\n // This is used to \"freeze\" the language options when captions.update is false\n getTracks(update = false) {\n // Handle media or textTracks missing or null\n const tracks = Array.from((this.media || {}).textTracks || []);\n // For HTML5, use cache instead of current tracks when it exists (if captions.update is false)\n // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata)\n return tracks\n .filter((track) => !this.isHTML5 || update || this.captions.meta.has(track))\n .filter((track) => ['captions', 'subtitles'].includes(track.kind));\n },\n\n // Match tracks based on languages and get the first\n findTrack(languages, force = false) {\n const tracks = captions.getTracks.call(this);\n const sortIsDefault = (track) => Number((this.captions.meta.get(track) || {}).default);\n const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a));\n let track;\n\n languages.every((language) => {\n track = sorted.find((t) => t.language === language);\n return !track; // Break iteration if there is a match\n });\n\n // If no match is found but is required, get first\n return track || (force ? sorted[0] : undefined);\n },\n\n // Get the current track\n getCurrentTrack() {\n return captions.getTracks.call(this)[this.currentTrack];\n },\n\n // Get UI label for track\n getLabel(track) {\n let currentTrack = track;\n\n if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) {\n currentTrack = captions.getCurrentTrack.call(this);\n }\n\n if (is.track(currentTrack)) {\n if (!is.empty(currentTrack.label)) {\n return currentTrack.label;\n }\n\n if (!is.empty(currentTrack.language)) {\n return track.language.toUpperCase();\n }\n\n return i18n.get('enabled', this.config);\n }\n\n return i18n.get('disabled', this.config);\n },\n\n // Update captions using current track's active cues\n // Also optional array argument in case there isn't any track (ex: vimeo)\n updateCues(input) {\n // Requires UI\n if (!this.supported.ui) {\n return;\n }\n\n if (!is.element(this.elements.captions)) {\n this.debug.warn('No captions element to render to');\n return;\n }\n\n // Only accept array or empty input\n if (!is.nullOrUndefined(input) && !Array.isArray(input)) {\n this.debug.warn('updateCues: Invalid input', input);\n return;\n }\n\n let cues = input;\n\n // Get cues from track\n if (!cues) {\n const track = captions.getCurrentTrack.call(this);\n\n cues = Array.from((track || {}).activeCues || [])\n .map((cue) => cue.getCueAsHTML())\n .map(getHTML);\n }\n\n // Set new caption text\n const content = cues.map((cueText) => cueText.trim()).join('\\n');\n const changed = content !== this.elements.captions.innerHTML;\n\n if (changed) {\n // Empty the container and create a new child element\n emptyElement(this.elements.captions);\n const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption));\n caption.innerHTML = content;\n this.elements.captions.appendChild(caption);\n\n // Trigger event\n triggerEvent.call(this, this.media, 'cuechange');\n }\n },\n};\n\nexport default captions;\n","// ==========================================================================\n// Plyr default config\n// ==========================================================================\n\nconst defaults = {\n // Disable\n enabled: true,\n\n // Custom media title\n title: '',\n\n // Logging to console\n debug: false,\n\n // Auto play (if supported)\n autoplay: false,\n\n // Only allow one media playing at once (vimeo only)\n autopause: true,\n\n // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present)\n // TODO: Remove iosNative fullscreen option in favour of this (logic needs work)\n playsinline: true,\n\n // Default time to skip when rewind/fast forward\n seekTime: 10,\n\n // Default volume\n volume: 1,\n muted: false,\n\n // Pass a custom duration\n duration: null,\n\n // Display the media duration on load in the current time position\n // If you have opted to display both duration and currentTime, this is ignored\n displayDuration: true,\n\n // Invert the current time to be a countdown\n invertTime: true,\n\n // Clicking the currentTime inverts it's value to show time left rather than elapsed\n toggleInvert: true,\n\n // Force an aspect ratio\n // The format must be `'w:h'` (e.g. `'16:9'`)\n ratio: null,\n\n // Click video container to play/pause\n clickToPlay: true,\n\n // Auto hide the controls\n hideControls: true,\n\n // Reset to start when playback ended\n resetOnEnd: false,\n\n // Disable the standard context menu\n disableContextMenu: true,\n\n // Sprite (for icons)\n loadSprite: true,\n iconPrefix: 'plyr',\n iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg',\n\n // Blank video (used to prevent errors on source change)\n blankVideo: 'https://cdn.plyr.io/static/blank.mp4',\n\n // Quality default\n quality: {\n default: 576,\n // The options to display in the UI, if available for the source media\n options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240],\n forced: false,\n onChange: null,\n },\n\n // Set loops\n loop: {\n active: false,\n // start: null,\n // end: null,\n },\n\n // Speed default and options to display\n speed: {\n selected: 1,\n // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x)\n options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4],\n },\n\n // Keyboard shortcut settings\n keyboard: {\n focused: true,\n global: false,\n },\n\n // Display tooltips\n tooltips: {\n controls: false,\n seek: true,\n },\n\n // Captions settings\n captions: {\n active: false,\n language: 'auto',\n // Listen to new tracks added after Plyr is initialized.\n // This is needed for streaming captions, but may result in unselectable options\n update: false,\n },\n\n // Fullscreen settings\n fullscreen: {\n enabled: true, // Allow fullscreen?\n fallback: true, // Fallback using full viewport/window\n iosNative: false, // Use the native fullscreen in iOS (disables custom controls)\n // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode\n // Non-ancestors of the player element will be ignored\n // container: null, // defaults to the player element\n },\n\n // Local storage\n storage: {\n enabled: true,\n key: 'plyr',\n },\n\n // Default controls\n controls: [\n 'play-large',\n // 'restart',\n // 'rewind',\n 'play',\n // 'fast-forward',\n 'progress',\n 'current-time',\n // 'duration',\n 'mute',\n 'volume',\n 'captions',\n 'settings',\n 'pip',\n 'airplay',\n // 'download',\n 'fullscreen',\n ],\n settings: ['captions', 'quality', 'speed'],\n\n // Localisation\n i18n: {\n restart: 'Restart',\n rewind: 'Rewind {seektime}s',\n play: 'Play',\n pause: 'Pause',\n fastForward: 'Forward {seektime}s',\n seek: 'Seek',\n seekLabel: '{currentTime} of {duration}',\n played: 'Played',\n buffered: 'Buffered',\n currentTime: 'Current time',\n duration: 'Duration',\n volume: 'Volume',\n mute: 'Mute',\n unmute: 'Unmute',\n enableCaptions: 'Enable captions',\n disableCaptions: 'Disable captions',\n download: 'Download',\n enterFullscreen: 'Enter fullscreen',\n exitFullscreen: 'Exit fullscreen',\n frameTitle: 'Player for {title}',\n captions: 'Captions',\n settings: 'Settings',\n pip: 'PIP',\n menuBack: 'Go back to previous menu',\n speed: 'Speed',\n normal: 'Normal',\n quality: 'Quality',\n loop: 'Loop',\n start: 'Start',\n end: 'End',\n all: 'All',\n reset: 'Reset',\n disabled: 'Disabled',\n enabled: 'Enabled',\n advertisement: 'Ad',\n qualityBadge: {\n 2160: '4K',\n 1440: 'HD',\n 1080: 'HD',\n 720: 'HD',\n 576: 'SD',\n 480: 'SD',\n },\n },\n\n // URLs\n urls: {\n download: null,\n vimeo: {\n sdk: 'https://player.vimeo.com/api/player.js',\n iframe: 'https://player.vimeo.com/video/{0}?{1}',\n api: 'https://vimeo.com/api/oembed.json?url={0}',\n },\n youtube: {\n sdk: 'https://www.youtube.com/iframe_api',\n api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}',\n },\n googleIMA: {\n sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js',\n },\n },\n\n // Custom control listeners\n listeners: {\n seek: null,\n play: null,\n pause: null,\n restart: null,\n rewind: null,\n fastForward: null,\n mute: null,\n volume: null,\n captions: null,\n download: null,\n fullscreen: null,\n pip: null,\n airplay: null,\n speed: null,\n quality: null,\n loop: null,\n language: null,\n },\n\n // Events to watch and bubble\n events: [\n // Events to watch on HTML5 media elements and bubble\n // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events\n 'ended',\n 'progress',\n 'stalled',\n 'playing',\n 'waiting',\n 'canplay',\n 'canplaythrough',\n 'loadstart',\n 'loadeddata',\n 'loadedmetadata',\n 'timeupdate',\n 'volumechange',\n 'play',\n 'pause',\n 'error',\n 'seeking',\n 'seeked',\n 'emptied',\n 'ratechange',\n 'cuechange',\n\n // Custom events\n 'download',\n 'enterfullscreen',\n 'exitfullscreen',\n 'captionsenabled',\n 'captionsdisabled',\n 'languagechange',\n 'controlshidden',\n 'controlsshown',\n 'ready',\n\n // YouTube\n 'statechange',\n\n // Quality\n 'qualitychange',\n\n // Ads\n 'adsloaded',\n 'adscontentpause',\n 'adscontentresume',\n 'adstarted',\n 'adsmidpoint',\n 'adscomplete',\n 'adsallcomplete',\n 'adsimpression',\n 'adsclick',\n ],\n\n // Selectors\n // Change these to match your template if using custom HTML\n selectors: {\n editable: 'input, textarea, select, [contenteditable]',\n container: '.plyr',\n controls: {\n container: null,\n wrapper: '.plyr__controls',\n },\n labels: '[data-plyr]',\n buttons: {\n play: '[data-plyr=\"play\"]',\n pause: '[data-plyr=\"pause\"]',\n restart: '[data-plyr=\"restart\"]',\n rewind: '[data-plyr=\"rewind\"]',\n fastForward: '[data-plyr=\"fast-forward\"]',\n mute: '[data-plyr=\"mute\"]',\n captions: '[data-plyr=\"captions\"]',\n download: '[data-plyr=\"download\"]',\n fullscreen: '[data-plyr=\"fullscreen\"]',\n pip: '[data-plyr=\"pip\"]',\n airplay: '[data-plyr=\"airplay\"]',\n settings: '[data-plyr=\"settings\"]',\n loop: '[data-plyr=\"loop\"]',\n },\n inputs: {\n seek: '[data-plyr=\"seek\"]',\n volume: '[data-plyr=\"volume\"]',\n speed: '[data-plyr=\"speed\"]',\n language: '[data-plyr=\"language\"]',\n quality: '[data-plyr=\"quality\"]',\n },\n display: {\n currentTime: '.plyr__time--current',\n duration: '.plyr__time--duration',\n buffer: '.plyr__progress__buffer',\n loop: '.plyr__progress__loop', // Used later\n volume: '.plyr__volume--display',\n },\n progress: '.plyr__progress',\n captions: '.plyr__captions',\n caption: '.plyr__caption',\n },\n\n // Class hooks added to the player in different states\n classNames: {\n type: 'plyr--{0}',\n provider: 'plyr--{0}',\n video: 'plyr__video-wrapper',\n embed: 'plyr__video-embed',\n videoFixedRatio: 'plyr__video-wrapper--fixed-ratio',\n embedContainer: 'plyr__video-embed__container',\n poster: 'plyr__poster',\n posterEnabled: 'plyr__poster-enabled',\n ads: 'plyr__ads',\n control: 'plyr__control',\n controlPressed: 'plyr__control--pressed',\n playing: 'plyr--playing',\n paused: 'plyr--paused',\n stopped: 'plyr--stopped',\n loading: 'plyr--loading',\n hover: 'plyr--hover',\n tooltip: 'plyr__tooltip',\n cues: 'plyr__cues',\n hidden: 'plyr__sr-only',\n hideControls: 'plyr--hide-controls',\n isIos: 'plyr--is-ios',\n isTouch: 'plyr--is-touch',\n uiSupported: 'plyr--full-ui',\n noTransition: 'plyr--no-transition',\n display: {\n time: 'plyr__time',\n },\n menu: {\n value: 'plyr__menu__value',\n badge: 'plyr__badge',\n open: 'plyr--menu-open',\n },\n captions: {\n enabled: 'plyr--captions-enabled',\n active: 'plyr--captions-active',\n },\n fullscreen: {\n enabled: 'plyr--fullscreen-enabled',\n fallback: 'plyr--fullscreen-fallback',\n },\n pip: {\n supported: 'plyr--pip-supported',\n active: 'plyr--pip-active',\n },\n airplay: {\n supported: 'plyr--airplay-supported',\n active: 'plyr--airplay-active',\n },\n tabFocus: 'plyr__tab-focus',\n previewThumbnails: {\n // Tooltip thumbs\n thumbContainer: 'plyr__preview-thumb',\n thumbContainerShown: 'plyr__preview-thumb--is-shown',\n imageContainer: 'plyr__preview-thumb__image-container',\n timeContainer: 'plyr__preview-thumb__time-container',\n // Scrubbing\n scrubbingContainer: 'plyr__preview-scrubbing',\n scrubbingContainerShown: 'plyr__preview-scrubbing--is-shown',\n },\n },\n\n // Embed attributes\n attributes: {\n embed: {\n provider: 'data-plyr-provider',\n id: 'data-plyr-embed-id',\n hash: 'data-plyr-embed-hash',\n },\n },\n\n // Advertisements plugin\n // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio\n ads: {\n enabled: false,\n publisherId: '',\n tagUrl: '',\n },\n\n // Preview Thumbnails plugin\n previewThumbnails: {\n enabled: false,\n src: '',\n },\n\n // Vimeo plugin\n vimeo: {\n byline: false,\n portrait: false,\n title: false,\n speed: true,\n transparent: false,\n // Custom settings from Plyr\n customControls: true,\n referrerPolicy: null, // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy\n // Whether the owner of the video has a Pro or Business account\n // (which allows us to properly hide controls without CSS hacks, etc)\n premium: false,\n },\n\n // YouTube plugin\n youtube: {\n rel: 0, // No related vids\n showinfo: 0, // Hide info\n iv_load_policy: 3, // Hide annotations\n modestbranding: 1, // Hide logos as much as possible (they still show one in the corner when paused)\n // Custom settings from Plyr\n customControls: true,\n noCookie: false, // Whether to use an alternative version of YouTube without cookies\n },\n};\n\nexport default defaults;\n","// ==========================================================================\n// Plyr states\n// ==========================================================================\n\nexport const pip = {\n active: 'picture-in-picture',\n inactive: 'inline',\n};\n\nexport default { pip };\n","// ==========================================================================\n// Plyr supported types and providers\n// ==========================================================================\n\nexport const providers = {\n html5: 'html5',\n youtube: 'youtube',\n vimeo: 'vimeo',\n};\n\nexport const types = {\n audio: 'audio',\n video: 'video',\n};\n\n/**\n * Get provider by URL\n * @param {String} url\n */\nexport function getProviderByUrl(url) {\n // YouTube\n if (/^(https?:\\/\\/)?(www\\.)?(youtube\\.com|youtube-nocookie\\.com|youtu\\.?be)\\/.+$/.test(url)) {\n return providers.youtube;\n }\n\n // Vimeo\n if (/^https?:\\/\\/player.vimeo.com\\/video\\/\\d{0,9}(?=\\b|\\/)/.test(url)) {\n return providers.vimeo;\n }\n\n return null;\n}\n\nexport default { providers, types };\n","// ==========================================================================\n// Console wrapper\n// ==========================================================================\n\nconst noop = () => {};\n\nexport default class Console {\n constructor(enabled = false) {\n this.enabled = window.console && enabled;\n\n if (this.enabled) {\n this.log('Debugging enabled');\n }\n }\n\n get log() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.log, console) : noop;\n }\n\n get warn() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop;\n }\n\n get error() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.error, console) : noop;\n }\n}\n","// ==========================================================================\n// Fullscreen wrapper\n// https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API#prefixing\n// https://webkit.org/blog/7929/designing-websites-for-iphone-x/\n// ==========================================================================\n\nimport browser from './utils/browser';\nimport { closest, getElements, hasClass, toggleClass } from './utils/elements';\nimport { on, triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\n\nclass Fullscreen {\n constructor(player) {\n // Keep reference to parent\n this.player = player;\n\n // Get prefix\n this.prefix = Fullscreen.prefix;\n this.property = Fullscreen.property;\n\n // Scroll position\n this.scrollPosition = { x: 0, y: 0 };\n\n // Force the use of 'full window/browser' rather than fullscreen\n this.forceFallback = player.config.fullscreen.fallback === 'force';\n\n // Get the fullscreen element\n // Checks container is an ancestor, defaults to null\n this.player.elements.fullscreen =\n player.config.fullscreen.container && closest(this.player.elements.container, player.config.fullscreen.container);\n\n // Register event listeners\n // Handle event (incase user presses escape etc)\n on.call(\n this.player,\n document,\n this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`,\n () => {\n // TODO: Filter for target??\n this.onChange();\n },\n );\n\n // Fullscreen toggle on double click\n on.call(this.player, this.player.elements.container, 'dblclick', (event) => {\n // Ignore double click in controls\n if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) {\n return;\n }\n\n this.player.listeners.proxy(event, this.toggle, 'fullscreen');\n });\n\n // Tap focus when in fullscreen\n on.call(this, this.player.elements.container, 'keydown', (event) => this.trapFocus(event));\n\n // Update the UI\n this.update();\n\n // this.toggle = this.toggle.bind(this);\n }\n\n // Determine if native supported\n static get native() {\n return !!(\n document.fullscreenEnabled ||\n document.webkitFullscreenEnabled ||\n document.mozFullScreenEnabled ||\n document.msFullscreenEnabled\n );\n }\n\n // If we're actually using native\n get usingNative() {\n return Fullscreen.native && !this.forceFallback;\n }\n\n // Get the prefix for handlers\n static get prefix() {\n // No prefix\n if (is.function(document.exitFullscreen)) {\n return '';\n }\n\n // Check for fullscreen support by vendor prefix\n let value = '';\n const prefixes = ['webkit', 'moz', 'ms'];\n\n prefixes.some((pre) => {\n if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) {\n value = pre;\n return true;\n }\n\n return false;\n });\n\n return value;\n }\n\n static get property() {\n return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen';\n }\n\n // Determine if fullscreen is enabled\n get enabled() {\n return (\n (Fullscreen.native || this.player.config.fullscreen.fallback) &&\n this.player.config.fullscreen.enabled &&\n this.player.supported.ui &&\n this.player.isVideo\n );\n }\n\n // Get active state\n get active() {\n if (!this.enabled) {\n return false;\n }\n\n // Fallback using classname\n if (!Fullscreen.native || this.forceFallback) {\n return hasClass(this.target, this.player.config.classNames.fullscreen.fallback);\n }\n\n const element = !this.prefix\n ? this.target.getRootNode().fullscreenElement\n : this.target.getRootNode()[`${this.prefix}${this.property}Element`];\n\n return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target;\n }\n\n // Get target element\n get target() {\n return browser.isIos && this.player.config.fullscreen.iosNative\n ? this.player.media\n : this.player.elements.fullscreen || this.player.elements.container;\n }\n\n onChange = () => {\n if (!this.enabled) {\n return;\n }\n\n // Update toggle button\n const button = this.player.elements.buttons.fullscreen;\n if (is.element(button)) {\n button.pressed = this.active;\n }\n\n // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up\n const target = this.target === this.player.media ? this.target : this.player.elements.container;\n // Trigger an event\n triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true);\n };\n\n toggleFallback = (toggle = false) => {\n // Store or restore scroll position\n if (toggle) {\n this.scrollPosition = {\n x: window.scrollX || 0,\n y: window.scrollY || 0,\n };\n } else {\n window.scrollTo(this.scrollPosition.x, this.scrollPosition.y);\n }\n\n // Toggle scroll\n document.body.style.overflow = toggle ? 'hidden' : '';\n\n // Toggle class hook\n toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle);\n\n // Force full viewport on iPhone X+\n if (browser.isIos) {\n let viewport = document.head.querySelector('meta[name=\"viewport\"]');\n const property = 'viewport-fit=cover';\n\n // Inject the viewport meta if required\n if (!viewport) {\n viewport = document.createElement('meta');\n viewport.setAttribute('name', 'viewport');\n }\n\n // Check if the property already exists\n const hasProperty = is.string(viewport.content) && viewport.content.includes(property);\n\n if (toggle) {\n this.cleanupViewport = !hasProperty;\n\n if (!hasProperty) {\n viewport.content += `,${property}`;\n }\n } else if (this.cleanupViewport) {\n viewport.content = viewport.content\n .split(',')\n .filter((part) => part.trim() !== property)\n .join(',');\n }\n }\n\n // Toggle button and fire events\n this.onChange();\n };\n\n // Trap focus inside container\n trapFocus = (event) => {\n // Bail if iOS, not active, not the tab key\n if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) {\n return;\n }\n\n // Get the current focused element\n const focused = document.activeElement;\n const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]');\n const [first] = focusable;\n const last = focusable[focusable.length - 1];\n\n if (focused === last && !event.shiftKey) {\n // Move focus to first element that can be tabbed if Shift isn't used\n first.focus();\n event.preventDefault();\n } else if (focused === first && event.shiftKey) {\n // Move focus to last element that can be tabbed if Shift is used\n last.focus();\n event.preventDefault();\n }\n };\n\n // Update UI\n update = () => {\n if (this.enabled) {\n let mode;\n\n if (this.forceFallback) {\n mode = 'Fallback (forced)';\n } else if (Fullscreen.native) {\n mode = 'Native';\n } else {\n mode = 'Fallback';\n }\n\n this.player.debug.log(`${mode} fullscreen enabled`);\n } else {\n this.player.debug.log('Fullscreen not supported and fallback disabled');\n }\n\n // Add styling hook to show button\n toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled);\n };\n\n // Make an element fullscreen\n enter = () => {\n if (!this.enabled) {\n return;\n }\n\n // iOS native fullscreen doesn't need the request step\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n if (this.player.isVimeo) {\n this.player.embed.requestFullscreen();\n } else {\n this.target.webkitEnterFullscreen();\n }\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(true);\n } else if (!this.prefix) {\n this.target.requestFullscreen({ navigationUI: 'hide' });\n } else if (!is.empty(this.prefix)) {\n this.target[`${this.prefix}Request${this.property}`]();\n }\n };\n\n // Bail from fullscreen\n exit = () => {\n if (!this.enabled) {\n return;\n }\n\n // iOS native fullscreen\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n this.target.webkitExitFullscreen();\n silencePromise(this.player.play());\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(false);\n } else if (!this.prefix) {\n (document.cancelFullScreen || document.exitFullscreen).call(document);\n } else if (!is.empty(this.prefix)) {\n const action = this.prefix === 'moz' ? 'Cancel' : 'Exit';\n document[`${this.prefix}${action}${this.property}`]();\n }\n };\n\n // Toggle state\n toggle = () => {\n if (!this.active) {\n this.enter();\n } else {\n this.exit();\n }\n };\n}\n\nexport default Fullscreen;\n","// ==========================================================================\n// Load image avoiding xhr/fetch CORS issues\n// Server status can't be obtained this way unfortunately, so this uses \"naturalWidth\" to determine if the image has loaded\n// By default it checks if it is at least 1px, but you can add a second argument to change this\n// ==========================================================================\n\nexport default function loadImage(src, minWidth = 1) {\n return new Promise((resolve, reject) => {\n const image = new Image();\n\n const handler = () => {\n delete image.onload;\n delete image.onerror;\n (image.naturalWidth >= minWidth ? resolve : reject)(image);\n };\n\n Object.assign(image, { onload: handler, onerror: handler, src });\n });\n}\n","// ==========================================================================\n// Plyr UI\n// ==========================================================================\n\nimport captions from './captions';\nimport controls from './controls';\nimport support from './support';\nimport browser from './utils/browser';\nimport { getElement, toggleClass } from './utils/elements';\nimport { ready, triggerEvent } from './utils/events';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport loadImage from './utils/load-image';\n\nconst ui = {\n addStyleHook() {\n toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);\n toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);\n },\n\n // Toggle native HTML5 media controls\n toggleNativeControls(toggle = false) {\n if (toggle && this.isHTML5) {\n this.media.setAttribute('controls', '');\n } else {\n this.media.removeAttribute('controls');\n }\n },\n\n // Setup the UI\n build() {\n // Re-attach media element listeners\n // TODO: Use event bubbling?\n this.listeners.media();\n\n // Don't setup interface if no support\n if (!this.supported.ui) {\n this.debug.warn(`Basic support only for ${this.provider} ${this.type}`);\n\n // Restore native controls\n ui.toggleNativeControls.call(this, true);\n\n // Bail\n return;\n }\n\n // Inject custom controls if not present\n if (!is.element(this.elements.controls)) {\n // Inject custom controls\n controls.inject.call(this);\n\n // Re-attach control listeners\n this.listeners.controls();\n }\n\n // Remove native controls\n ui.toggleNativeControls.call(this);\n\n // Setup captions for HTML5\n if (this.isHTML5) {\n captions.setup.call(this);\n }\n\n // Reset volume\n this.volume = null;\n\n // Reset mute state\n this.muted = null;\n\n // Reset loop state\n this.loop = null;\n\n // Reset quality setting\n this.quality = null;\n\n // Reset speed\n this.speed = null;\n\n // Reset volume display\n controls.updateVolume.call(this);\n\n // Reset time display\n controls.timeUpdate.call(this);\n\n // Reset duration display\n controls.durationUpdate.call(this);\n\n // Update the UI\n ui.checkPlaying.call(this);\n\n // Check for picture-in-picture support\n toggleClass(\n this.elements.container,\n this.config.classNames.pip.supported,\n support.pip && this.isHTML5 && this.isVideo,\n );\n\n // Check for airplay support\n toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5);\n\n // Add iOS class\n toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos);\n\n // Add touch class\n toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch);\n\n // Ready for API calls\n this.ready = true;\n\n // Ready event at end of execution stack\n setTimeout(() => {\n triggerEvent.call(this, this.media, 'ready');\n }, 0);\n\n // Set the title\n ui.setTitle.call(this);\n\n // Assure the poster image is set, if the property was added before the element was created\n if (this.poster) {\n ui.setPoster.call(this, this.poster, false).catch(() => {});\n }\n\n // Manually set the duration if user has overridden it.\n // The event listeners for it doesn't get called if preload is disabled (#701)\n if (this.config.duration) {\n controls.durationUpdate.call(this);\n }\n },\n\n // Setup aria attribute for play and iframe title\n setTitle() {\n // Find the current text\n let label = i18n.get('play', this.config);\n\n // If there's a media title set, use that for the label\n if (is.string(this.config.title) && !is.empty(this.config.title)) {\n label += `, ${this.config.title}`;\n }\n\n // If there's a play button, set label\n Array.from(this.elements.buttons.play || []).forEach((button) => {\n button.setAttribute('aria-label', label);\n });\n\n // Set iframe title\n // https://github.com/sampotts/plyr/issues/124\n if (this.isEmbed) {\n const iframe = getElement.call(this, 'iframe');\n\n if (!is.element(iframe)) {\n return;\n }\n\n // Default to media type\n const title = !is.empty(this.config.title) ? this.config.title : 'video';\n const format = i18n.get('frameTitle', this.config);\n\n iframe.setAttribute('title', format.replace('{title}', title));\n }\n },\n\n // Toggle poster\n togglePoster(enable) {\n toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);\n },\n\n // Set the poster image (async)\n // Used internally for the poster setter, with the passive option forced to false\n setPoster(poster, passive = true) {\n // Don't override if call is passive\n if (passive && this.poster) {\n return Promise.reject(new Error('Poster already set'));\n }\n\n // Set property synchronously to respect the call order\n this.media.setAttribute('data-poster', poster);\n\n // Show the poster\n this.elements.poster.removeAttribute('hidden');\n\n // Wait until ui is ready\n return (\n ready\n .call(this)\n // Load image\n .then(() => loadImage(poster))\n .catch((error) => {\n // Hide poster on error unless it's been set by another call\n if (poster === this.poster) {\n ui.togglePoster.call(this, false);\n }\n // Rethrow\n throw error;\n })\n .then(() => {\n // Prevent race conditions\n if (poster !== this.poster) {\n throw new Error('setPoster cancelled by later call to setPoster');\n }\n })\n .then(() => {\n Object.assign(this.elements.poster.style, {\n backgroundImage: `url('${poster}')`,\n // Reset backgroundSize as well (since it can be set to \"cover\" for padded thumbnails for youtube)\n backgroundSize: '',\n });\n\n ui.togglePoster.call(this, true);\n\n return poster;\n })\n );\n },\n\n // Check playing state\n checkPlaying(event) {\n // Class hooks\n toggleClass(this.elements.container, this.config.classNames.playing, this.playing);\n toggleClass(this.elements.container, this.config.classNames.paused, this.paused);\n toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped);\n\n // Set state\n Array.from(this.elements.buttons.play || []).forEach((target) => {\n Object.assign(target, { pressed: this.playing });\n target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config));\n });\n\n // Only update controls on non timeupdate events\n if (is.event(event) && event.type === 'timeupdate') {\n return;\n }\n\n // Toggle controls\n ui.toggleControls.call(this);\n },\n\n // Check if media is loading\n checkLoading(event) {\n this.loading = ['stalled', 'waiting'].includes(event.type);\n\n // Clear timer\n clearTimeout(this.timers.loading);\n\n // Timer to prevent flicker when seeking\n this.timers.loading = setTimeout(\n () => {\n // Update progress bar loading class state\n toggleClass(this.elements.container, this.config.classNames.loading, this.loading);\n\n // Update controls visibility\n ui.toggleControls.call(this);\n },\n this.loading ? 250 : 0,\n );\n },\n\n // Toggle controls based on state and `force` argument\n toggleControls(force) {\n const { controls: controlsElement } = this.elements;\n\n if (controlsElement && this.config.hideControls) {\n // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.)\n const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now();\n\n // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide\n this.toggleControls(\n Boolean(\n force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek,\n ),\n );\n }\n },\n\n // Migrate any custom properties from the media to the parent\n migrateStyles() {\n // Loop through values (as they are the keys when the object is spread 🤔)\n Object.values({ ...this.media.style })\n // We're only fussed about Plyr specific properties\n .filter((key) => !is.empty(key) && is.string(key) && key.startsWith('--plyr'))\n .forEach((key) => {\n // Set on the container\n this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key));\n\n // Clean up from media element\n this.media.style.removeProperty(key);\n });\n\n // Remove attribute if empty\n if (is.empty(this.media.style)) {\n this.media.removeAttribute('style');\n }\n },\n};\n\nexport default ui;\n","// ==========================================================================\n// Plyr Event Listeners\n// ==========================================================================\n\nimport controls from './controls';\nimport ui from './ui';\nimport { repaint } from './utils/animation';\nimport browser from './utils/browser';\nimport { getElement, getElements, matches, toggleClass } from './utils/elements';\nimport { off, on, once, toggleListener, triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\nimport { getAspectRatio, getViewportSize, supportsCSS } from './utils/style';\n\nclass Listeners {\n constructor(player) {\n this.player = player;\n this.lastKey = null;\n this.focusTimer = null;\n this.lastKeyDown = null;\n\n this.handleKey = this.handleKey.bind(this);\n this.toggleMenu = this.toggleMenu.bind(this);\n this.setTabFocus = this.setTabFocus.bind(this);\n this.firstTouch = this.firstTouch.bind(this);\n }\n\n // Handle key presses\n handleKey(event) {\n const { player } = this;\n const { elements } = player;\n const code = event.keyCode ? event.keyCode : event.which;\n const pressed = event.type === 'keydown';\n const repeat = pressed && code === this.lastKey;\n\n // Bail if a modifier key is set\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {\n return;\n }\n\n // If the event is bubbled from the media element\n // Firefox doesn't get the keycode for whatever reason\n if (!is.number(code)) {\n return;\n }\n\n // Seek by the number keys\n const seekByKey = () => {\n // Divide the max duration into 10th's and times by the number value\n player.currentTime = (player.duration / 10) * (code - 48);\n };\n\n // Handle the key on keydown\n // Reset on keyup\n if (pressed) {\n // Check focused element\n // and if the focused element is not editable (e.g. text input)\n // and any that accept key input http://webaim.org/techniques/keyboard/\n const focused = document.activeElement;\n if (is.element(focused)) {\n const { editable } = player.config.selectors;\n const { seek } = elements.inputs;\n\n if (focused !== seek && matches(focused, editable)) {\n return;\n }\n\n if (event.which === 32 && matches(focused, 'button, [role^=\"menuitem\"]')) {\n return;\n }\n }\n\n // Which keycodes should we prevent default\n const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79];\n\n // If the code is found prevent default (e.g. prevent scrolling for arrows)\n if (preventDefault.includes(code)) {\n event.preventDefault();\n event.stopPropagation();\n }\n\n switch (code) {\n case 48:\n case 49:\n case 50:\n case 51:\n case 52:\n case 53:\n case 54:\n case 55:\n case 56:\n case 57:\n // 0-9\n if (!repeat) {\n seekByKey();\n }\n break;\n\n case 32:\n case 75:\n // Space and K key\n if (!repeat) {\n silencePromise(player.togglePlay());\n }\n break;\n\n case 38:\n // Arrow up\n player.increaseVolume(0.1);\n break;\n\n case 40:\n // Arrow down\n player.decreaseVolume(0.1);\n break;\n\n case 77:\n // M key\n if (!repeat) {\n player.muted = !player.muted;\n }\n break;\n\n case 39:\n // Arrow forward\n player.forward();\n break;\n\n case 37:\n // Arrow back\n player.rewind();\n break;\n\n case 70:\n // F key\n player.fullscreen.toggle();\n break;\n\n case 67:\n // C key\n if (!repeat) {\n player.toggleCaptions();\n }\n break;\n\n case 76:\n // L key\n player.loop = !player.loop;\n break;\n\n /* case 73:\n this.setLoop('start');\n break;\n\n case 76:\n this.setLoop();\n break;\n\n case 79:\n this.setLoop('end');\n break; */\n\n default:\n break;\n }\n\n // Escape is handle natively when in full screen\n // So we only need to worry about non native\n if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) {\n player.fullscreen.toggle();\n }\n\n // Store last code for next cycle\n this.lastKey = code;\n } else {\n this.lastKey = null;\n }\n }\n\n // Toggle menu\n toggleMenu(event) {\n controls.toggleMenu.call(this.player, event);\n }\n\n // Device is touch enabled\n firstTouch = () => {\n const { player } = this;\n const { elements } = player;\n\n player.touch = true;\n\n // Add touch class\n toggleClass(elements.container, player.config.classNames.isTouch, true);\n };\n\n setTabFocus = (event) => {\n const { player } = this;\n const { elements } = player;\n\n clearTimeout(this.focusTimer);\n\n // Ignore any key other than tab\n if (event.type === 'keydown' && event.which !== 9) {\n return;\n }\n\n // Store reference to event timeStamp\n if (event.type === 'keydown') {\n this.lastKeyDown = event.timeStamp;\n }\n\n // Remove current classes\n const removeCurrent = () => {\n const className = player.config.classNames.tabFocus;\n const current = getElements.call(player, `.${className}`);\n toggleClass(current, className, false);\n };\n\n // Determine if a key was pressed to trigger this event\n const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20;\n\n // Ignore focus events if a key was pressed prior\n if (event.type === 'focus' && !wasKeyDown) {\n return;\n }\n\n // Remove all current\n removeCurrent();\n\n // Delay the adding of classname until the focus has changed\n // This event fires before the focusin event\n if (event.type !== 'focusout') {\n this.focusTimer = setTimeout(() => {\n const focused = document.activeElement;\n\n // Ignore if current focus element isn't inside the player\n if (!elements.container.contains(focused)) {\n return;\n }\n\n toggleClass(document.activeElement, player.config.classNames.tabFocus, true);\n }, 10);\n }\n };\n\n // Global window & document listeners\n global = (toggle = true) => {\n const { player } = this;\n\n // Keyboard shortcuts\n if (player.config.keyboard.global) {\n toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false);\n }\n\n // Click anywhere closes menu\n toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle);\n\n // Detect touch by events\n once.call(player, document.body, 'touchstart', this.firstTouch);\n\n // Tab focus detection\n toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true);\n };\n\n // Container listeners\n container = () => {\n const { player } = this;\n const { config, elements, timers } = player;\n\n // Keyboard shortcuts\n if (!config.keyboard.global && config.keyboard.focused) {\n on.call(player, elements.container, 'keydown keyup', this.handleKey, false);\n }\n\n // Toggle controls on mouse events and entering fullscreen\n on.call(\n player,\n elements.container,\n 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen',\n (event) => {\n const { controls: controlsElement } = elements;\n\n // Remove button states for fullscreen\n if (controlsElement && event.type === 'enterfullscreen') {\n controlsElement.pressed = false;\n controlsElement.hover = false;\n }\n\n // Show, then hide after a timeout unless another control event occurs\n const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type);\n let delay = 0;\n\n if (show) {\n ui.toggleControls.call(player, true);\n // Use longer timeout for touch devices\n delay = player.touch ? 3000 : 2000;\n }\n\n // Clear timer\n clearTimeout(timers.controls);\n\n // Set new timer to prevent flicker when seeking\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n },\n );\n\n // Set a gutter for Vimeo\n const setGutter = () => {\n if (!player.isVimeo || player.config.vimeo.premium) {\n return;\n }\n\n const target = elements.wrapper;\n const { active } = player.fullscreen;\n const [videoWidth, videoHeight] = getAspectRatio.call(player);\n const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`);\n\n // If not active, remove styles\n if (!active) {\n if (useNativeAspectRatio) {\n target.style.width = null;\n target.style.height = null;\n } else {\n target.style.maxWidth = null;\n target.style.margin = null;\n }\n return;\n }\n\n // Determine which dimension will overflow and constrain view\n const [viewportWidth, viewportHeight] = getViewportSize();\n const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight;\n\n if (useNativeAspectRatio) {\n target.style.width = overflow ? 'auto' : '100%';\n target.style.height = overflow ? '100%' : 'auto';\n } else {\n target.style.maxWidth = overflow ? `${(viewportHeight / videoHeight) * videoWidth}px` : null;\n target.style.margin = overflow ? '0 auto' : null;\n }\n };\n\n // Handle resizing\n const resized = () => {\n clearTimeout(timers.resized);\n timers.resized = setTimeout(setGutter, 50);\n };\n\n on.call(player, elements.container, 'enterfullscreen exitfullscreen', (event) => {\n const { target } = player.fullscreen;\n\n // Ignore events not from target\n if (target !== elements.container) {\n return;\n }\n\n // If it's not an embed and no ratio specified\n if (!player.isEmbed && is.empty(player.config.ratio)) {\n return;\n }\n\n // Set Vimeo gutter\n setGutter();\n\n // Watch for resizes\n const method = event.type === 'enterfullscreen' ? on : off;\n method.call(player, window, 'resize', resized);\n });\n };\n\n // Listen for media events\n media = () => {\n const { player } = this;\n const { elements } = player;\n\n // Time change on media\n on.call(player, player.media, 'timeupdate seeking seeked', (event) => controls.timeUpdate.call(player, event));\n\n // Display duration\n on.call(player, player.media, 'durationchange loadeddata loadedmetadata', (event) =>\n controls.durationUpdate.call(player, event),\n );\n\n // Handle the media finishing\n on.call(player, player.media, 'ended', () => {\n // Show poster on end\n if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) {\n // Restart\n player.restart();\n\n // Call pause otherwise IE11 will start playing the video again\n player.pause();\n }\n });\n\n // Check for buffer progress\n on.call(player, player.media, 'progress playing seeking seeked', (event) =>\n controls.updateProgress.call(player, event),\n );\n\n // Handle volume changes\n on.call(player, player.media, 'volumechange', (event) => controls.updateVolume.call(player, event));\n\n // Handle play/pause\n on.call(player, player.media, 'playing play pause ended emptied timeupdate', (event) =>\n ui.checkPlaying.call(player, event),\n );\n\n // Loading state\n on.call(player, player.media, 'waiting canplay seeked playing', (event) => ui.checkLoading.call(player, event));\n\n // Click video\n if (player.supported.ui && player.config.clickToPlay && !player.isAudio) {\n // Re-fetch the wrapper\n const wrapper = getElement.call(player, `.${player.config.classNames.video}`);\n\n // Bail if there's no wrapper (this should never happen)\n if (!is.element(wrapper)) {\n return;\n }\n\n // On click play, pause or restart\n on.call(player, elements.container, 'click', (event) => {\n const targets = [elements.container, wrapper];\n\n // Ignore if click if not container or in video wrapper\n if (!targets.includes(event.target) && !wrapper.contains(event.target)) {\n return;\n }\n\n // Touch devices will just show controls (if hidden)\n if (player.touch && player.config.hideControls) {\n return;\n }\n\n if (player.ended) {\n this.proxy(event, player.restart, 'restart');\n this.proxy(\n event,\n () => {\n silencePromise(player.play());\n },\n 'play',\n );\n } else {\n this.proxy(\n event,\n () => {\n silencePromise(player.togglePlay());\n },\n 'play',\n );\n }\n });\n }\n\n // Disable right click\n if (player.supported.ui && player.config.disableContextMenu) {\n on.call(\n player,\n elements.wrapper,\n 'contextmenu',\n (event) => {\n event.preventDefault();\n },\n false,\n );\n }\n\n // Volume change\n on.call(player, player.media, 'volumechange', () => {\n // Save to storage\n player.storage.set({\n volume: player.volume,\n muted: player.muted,\n });\n });\n\n // Speed change\n on.call(player, player.media, 'ratechange', () => {\n // Update UI\n controls.updateSetting.call(player, 'speed');\n\n // Save to storage\n player.storage.set({ speed: player.speed });\n });\n\n // Quality change\n on.call(player, player.media, 'qualitychange', (event) => {\n // Update UI\n controls.updateSetting.call(player, 'quality', null, event.detail.quality);\n });\n\n // Update download link when ready and if quality changes\n on.call(player, player.media, 'ready qualitychange', () => {\n controls.setDownloadUrl.call(player);\n });\n\n // Proxy events to container\n // Bubble up key events for Edge\n const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' ');\n\n on.call(player, player.media, proxyEvents, (event) => {\n let { detail = {} } = event;\n\n // Get error details from media\n if (event.type === 'error') {\n detail = player.media.error;\n }\n\n triggerEvent.call(player, elements.container, event.type, true, detail);\n });\n };\n\n // Run default and custom handlers\n proxy = (event, defaultHandler, customHandlerKey) => {\n const { player } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n let returned = true;\n\n // Execute custom handler\n if (hasCustomHandler) {\n returned = customHandler.call(player, event);\n }\n\n // Only call default handler if not prevented in custom handler\n if (returned !== false && is.function(defaultHandler)) {\n defaultHandler.call(player, event);\n }\n };\n\n // Trigger custom and default handlers\n bind = (element, type, defaultHandler, customHandlerKey, passive = true) => {\n const { player } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n\n on.call(\n player,\n element,\n type,\n (event) => this.proxy(event, defaultHandler, customHandlerKey),\n passive && !hasCustomHandler,\n );\n };\n\n // Listen for control events\n controls = () => {\n const { player } = this;\n const { elements } = player;\n // IE doesn't support input event, so we fallback to change\n const inputEvent = browser.isIE ? 'change' : 'input';\n\n // Play/pause toggle\n if (elements.buttons.play) {\n Array.from(elements.buttons.play).forEach((button) => {\n this.bind(\n button,\n 'click',\n () => {\n silencePromise(player.togglePlay());\n },\n 'play',\n );\n });\n }\n\n // Pause\n this.bind(elements.buttons.restart, 'click', player.restart, 'restart');\n\n // Rewind\n this.bind(\n elements.buttons.rewind,\n 'click',\n () => {\n // Record seek time so we can prevent hiding controls for a few seconds after rewind\n player.lastSeekTime = Date.now();\n player.rewind();\n },\n 'rewind',\n );\n\n // Rewind\n this.bind(\n elements.buttons.fastForward,\n 'click',\n () => {\n // Record seek time so we can prevent hiding controls for a few seconds after fast forward\n player.lastSeekTime = Date.now();\n player.forward();\n },\n 'fastForward',\n );\n\n // Mute toggle\n this.bind(\n elements.buttons.mute,\n 'click',\n () => {\n player.muted = !player.muted;\n },\n 'mute',\n );\n\n // Captions toggle\n this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions());\n\n // Download\n this.bind(\n elements.buttons.download,\n 'click',\n () => {\n triggerEvent.call(player, player.media, 'download');\n },\n 'download',\n );\n\n // Fullscreen toggle\n this.bind(\n elements.buttons.fullscreen,\n 'click',\n () => {\n player.fullscreen.toggle();\n },\n 'fullscreen',\n );\n\n // Picture-in-Picture\n this.bind(\n elements.buttons.pip,\n 'click',\n () => {\n player.pip = 'toggle';\n },\n 'pip',\n );\n\n // Airplay\n this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay');\n\n // Settings menu - click toggle\n this.bind(\n elements.buttons.settings,\n 'click',\n (event) => {\n // Prevent the document click listener closing the menu\n event.stopPropagation();\n event.preventDefault();\n\n controls.toggleMenu.call(player, event);\n },\n null,\n false,\n ); // Can't be passive as we're preventing default\n\n // Settings menu - keyboard toggle\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n this.bind(\n elements.buttons.settings,\n 'keyup',\n (event) => {\n const code = event.which;\n\n // We only care about space and return\n if (![13, 32].includes(code)) {\n return;\n }\n\n // Because return triggers a click anyway, all we need to do is set focus\n if (code === 13) {\n controls.focusFirstMenuItem.call(player, null, true);\n return;\n }\n\n // Prevent scroll\n event.preventDefault();\n\n // Prevent playing video (Firefox)\n event.stopPropagation();\n\n // Toggle menu\n controls.toggleMenu.call(player, event);\n },\n null,\n false, // Can't be passive as we're preventing default\n );\n\n // Escape closes menu\n this.bind(elements.settings.menu, 'keydown', (event) => {\n if (event.which === 27) {\n controls.toggleMenu.call(player, event);\n }\n });\n\n // Set range input alternative \"value\", which matches the tooltip time (#954)\n this.bind(elements.inputs.seek, 'mousedown mousemove', (event) => {\n const rect = elements.progress.getBoundingClientRect();\n const percent = (100 / rect.width) * (event.pageX - rect.left);\n event.currentTarget.setAttribute('seek-value', percent);\n });\n\n // Pause while seeking\n this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', (event) => {\n const seek = event.currentTarget;\n const code = event.keyCode ? event.keyCode : event.which;\n const attribute = 'play-on-seeked';\n\n if (is.keyboardEvent(event) && code !== 39 && code !== 37) {\n return;\n }\n\n // Record seek time so we can prevent hiding controls for a few seconds after seek\n player.lastSeekTime = Date.now();\n\n // Was playing before?\n const play = seek.hasAttribute(attribute);\n // Done seeking\n const done = ['mouseup', 'touchend', 'keyup'].includes(event.type);\n\n // If we're done seeking and it was playing, resume playback\n if (play && done) {\n seek.removeAttribute(attribute);\n silencePromise(player.play());\n } else if (!done && player.playing) {\n seek.setAttribute(attribute, '');\n player.pause();\n }\n });\n\n // Fix range inputs on iOS\n // Super weird iOS bug where after you interact with an <input type=\"range\">,\n // it takes over further interactions on the page. This is a hack\n if (browser.isIos) {\n const inputs = getElements.call(player, 'input[type=\"range\"]');\n Array.from(inputs).forEach((input) => this.bind(input, inputEvent, (event) => repaint(event.target)));\n }\n\n // Seek\n this.bind(\n elements.inputs.seek,\n inputEvent,\n (event) => {\n const seek = event.currentTarget;\n // If it exists, use seek-value instead of \"value\" for consistency with tooltip time (#954)\n let seekTo = seek.getAttribute('seek-value');\n\n if (is.empty(seekTo)) {\n seekTo = seek.value;\n }\n\n seek.removeAttribute('seek-value');\n\n player.currentTime = (seekTo / seek.max) * player.duration;\n },\n 'seek',\n );\n\n // Seek tooltip\n this.bind(elements.progress, 'mouseenter mouseleave mousemove', (event) =>\n controls.updateSeekTooltip.call(player, event),\n );\n\n // Preview thumbnails plugin\n // TODO: Really need to work on some sort of plug-in wide event bus or pub-sub for this\n this.bind(elements.progress, 'mousemove touchmove', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startMove(event);\n }\n });\n\n // Hide thumbnail preview - on mouse click, mouse leave, and video play/seek. All four are required, e.g., for buffering\n this.bind(elements.progress, 'mouseleave touchend click', () => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endMove(false, true);\n }\n });\n\n // Show scrubbing preview\n this.bind(elements.progress, 'mousedown touchstart', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startScrubbing(event);\n }\n });\n\n this.bind(elements.progress, 'mouseup touchend', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endScrubbing(event);\n }\n });\n\n // Polyfill for lower fill in <input type=\"range\"> for webkit\n if (browser.isWebkit) {\n Array.from(getElements.call(player, 'input[type=\"range\"]')).forEach((element) => {\n this.bind(element, 'input', (event) => controls.updateRangeFill.call(player, event.target));\n });\n }\n\n // Current time invert\n // Only if one time element is used for both currentTime and duration\n if (player.config.toggleInvert && !is.element(elements.display.duration)) {\n this.bind(elements.display.currentTime, 'click', () => {\n // Do nothing if we're at the start\n if (player.currentTime === 0) {\n return;\n }\n\n player.config.invertTime = !player.config.invertTime;\n\n controls.timeUpdate.call(player);\n });\n }\n\n // Volume\n this.bind(\n elements.inputs.volume,\n inputEvent,\n (event) => {\n player.volume = event.target.value;\n },\n 'volume',\n );\n\n // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting)\n this.bind(elements.controls, 'mouseenter mouseleave', (event) => {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n });\n\n // Also update controls.hover state for any non-player children of fullscreen element (as above)\n if (elements.fullscreen) {\n Array.from(elements.fullscreen.children)\n .filter((c) => !c.contains(elements.container))\n .forEach((child) => {\n this.bind(child, 'mouseenter mouseleave', (event) => {\n if (elements.controls) {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }\n });\n });\n }\n\n // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting)\n this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', (event) => {\n elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type);\n });\n\n // Show controls when they receive focus (e.g., when using keyboard tab key)\n this.bind(elements.controls, 'focusin', () => {\n const { config, timers } = player;\n\n // Skip transition to prevent focus from scrolling the parent element\n toggleClass(elements.controls, config.classNames.noTransition, true);\n\n // Toggle\n ui.toggleControls.call(player, true);\n\n // Restore transition\n setTimeout(() => {\n toggleClass(elements.controls, config.classNames.noTransition, false);\n }, 0);\n\n // Delay a little more for mouse users\n const delay = this.touch ? 3000 : 4000;\n\n // Clear timer\n clearTimeout(timers.controls);\n\n // Hide again after delay\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n });\n\n // Mouse wheel for volume\n this.bind(\n elements.inputs.volume,\n 'wheel',\n (event) => {\n // Detect \"natural\" scroll - suppored on OS X Safari only\n // Other browsers on OS X will be inverted until support improves\n const inverted = event.webkitDirectionInvertedFromDevice;\n // Get delta from event. Invert if `inverted` is true\n const [x, y] = [event.deltaX, -event.deltaY].map((value) => (inverted ? -value : value));\n // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta)\n const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y);\n\n // Change the volume by 2%\n player.increaseVolume(direction / 50);\n\n // Don't break page scrolling at max and min\n const { volume } = player.media;\n if ((direction === 1 && volume < 1) || (direction === -1 && volume > 0)) {\n event.preventDefault();\n }\n },\n 'volume',\n false,\n );\n };\n}\n\nexport default Listeners;\n","(function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n define([], factory);\n } else if (typeof exports === 'object') {\n module.exports = factory();\n } else {\n root.loadjs = factory();\n }\n}(this, function() {\n/**\n * Global dependencies.\n * @global {Object} document - DOM\n */\n\nvar devnull = function() {},\n bundleIdCache = {},\n bundleResultCache = {},\n bundleCallbackQueue = {};\n\n\n/**\n * Subscribe to bundle load event.\n * @param {string[]} bundleIds - Bundle ids\n * @param {Function} callbackFn - The callback function\n */\nfunction subscribe(bundleIds, callbackFn) {\n // listify\n bundleIds = bundleIds.push ? bundleIds : [bundleIds];\n\n var depsNotFound = [],\n i = bundleIds.length,\n numWaiting = i,\n fn,\n bundleId,\n r,\n q;\n\n // define callback function\n fn = function (bundleId, pathsNotFound) {\n if (pathsNotFound.length) depsNotFound.push(bundleId);\n\n numWaiting--;\n if (!numWaiting) callbackFn(depsNotFound);\n };\n\n // register callback\n while (i--) {\n bundleId = bundleIds[i];\n\n // execute callback if in result cache\n r = bundleResultCache[bundleId];\n if (r) {\n fn(bundleId, r);\n continue;\n }\n\n // add to callback queue\n q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];\n q.push(fn);\n }\n}\n\n\n/**\n * Publish bundle load event.\n * @param {string} bundleId - Bundle id\n * @param {string[]} pathsNotFound - List of files not found\n */\nfunction publish(bundleId, pathsNotFound) {\n // exit if id isn't defined\n if (!bundleId) return;\n\n var q = bundleCallbackQueue[bundleId];\n\n // cache result\n bundleResultCache[bundleId] = pathsNotFound;\n\n // exit if queue is empty\n if (!q) return;\n\n // empty callback queue\n while (q.length) {\n q[0](bundleId, pathsNotFound);\n q.splice(0, 1);\n }\n}\n\n\n/**\n * Execute callbacks.\n * @param {Object or Function} args - The callback args\n * @param {string[]} depsNotFound - List of dependencies not found\n */\nfunction executeCallbacks(args, depsNotFound) {\n // accept function as argument\n if (args.call) args = {success: args};\n\n // success and error callbacks\n if (depsNotFound.length) (args.error || devnull)(depsNotFound);\n else (args.success || devnull)(args);\n}\n\n\n/**\n * Load individual file.\n * @param {string} path - The file path\n * @param {Function} callbackFn - The callback function\n */\nfunction loadFile(path, callbackFn, args, numTries) {\n var doc = document,\n async = args.async,\n maxTries = (args.numRetries || 0) + 1,\n beforeCallbackFn = args.before || devnull,\n pathname = path.replace(/[\\?|#].*$/, ''),\n pathStripped = path.replace(/^(css|img)!/, ''),\n isLegacyIECss,\n e;\n\n numTries = numTries || 0;\n\n if (/(^css!|\\.css$)/.test(pathname)) {\n // css\n e = doc.createElement('link');\n e.rel = 'stylesheet';\n e.href = pathStripped;\n\n // tag IE9+\n isLegacyIECss = 'hideFocus' in e;\n\n // use preload in IE Edge (to detect load errors)\n if (isLegacyIECss && e.relList) {\n isLegacyIECss = 0;\n e.rel = 'preload';\n e.as = 'style';\n }\n } else if (/(^img!|\\.(png|gif|jpg|svg|webp)$)/.test(pathname)) {\n // image\n e = doc.createElement('img');\n e.src = pathStripped; \n } else {\n // javascript\n e = doc.createElement('script');\n e.src = path;\n e.async = async === undefined ? true : async;\n }\n\n e.onload = e.onerror = e.onbeforeload = function (ev) {\n var result = ev.type[0];\n\n // treat empty stylesheets as failures to get around lack of onerror\n // support in IE9-11\n if (isLegacyIECss) {\n try {\n if (!e.sheet.cssText.length) result = 'e';\n } catch (x) {\n // sheets objects created from load errors don't allow access to\n // `cssText` (unless error is Code:18 SecurityError)\n if (x.code != 18) result = 'e';\n }\n }\n\n // handle retries in case of load failure\n if (result == 'e') {\n // increment counter\n numTries += 1;\n\n // exit function and try again\n if (numTries < maxTries) {\n return loadFile(path, callbackFn, args, numTries);\n }\n } else if (e.rel == 'preload' && e.as == 'style') {\n // activate preloaded stylesheets\n return e.rel = 'stylesheet'; // jshint ignore:line\n }\n \n // execute callback\n callbackFn(path, result, ev.defaultPrevented);\n };\n\n // add to document (unless callback returns `false`)\n if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);\n}\n\n\n/**\n * Load multiple files.\n * @param {string[]} paths - The file paths\n * @param {Function} callbackFn - The callback function\n */\nfunction loadFiles(paths, callbackFn, args) {\n // listify paths\n paths = paths.push ? paths : [paths];\n\n var numWaiting = paths.length,\n x = numWaiting,\n pathsNotFound = [],\n fn,\n i;\n\n // define callback function\n fn = function(path, result, defaultPrevented) {\n // handle error\n if (result == 'e') pathsNotFound.push(path);\n\n // handle beforeload event. If defaultPrevented then that means the load\n // will be blocked (ex. Ghostery/ABP on Safari)\n if (result == 'b') {\n if (defaultPrevented) pathsNotFound.push(path);\n else return;\n }\n\n numWaiting--;\n if (!numWaiting) callbackFn(pathsNotFound);\n };\n\n // load scripts\n for (i=0; i < x; i++) loadFile(paths[i], fn, args);\n}\n\n\n/**\n * Initiate script load and register bundle.\n * @param {(string|string[])} paths - The file paths\n * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success\n * callback or (3) object literal with success/error arguments, numRetries,\n * etc.\n * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object\n * literal with success/error arguments, numRetries, etc.\n */\nfunction loadjs(paths, arg1, arg2) {\n var bundleId,\n args;\n\n // bundleId (if string)\n if (arg1 && arg1.trim) bundleId = arg1;\n\n // args (default is {})\n args = (bundleId ? arg2 : arg1) || {};\n\n // throw error if bundle is already defined\n if (bundleId) {\n if (bundleId in bundleIdCache) {\n throw \"LoadJS\";\n } else {\n bundleIdCache[bundleId] = true;\n }\n }\n\n function loadFn(resolve, reject) {\n loadFiles(paths, function (pathsNotFound) {\n // execute callbacks\n executeCallbacks(args, pathsNotFound);\n \n // resolve Promise\n if (resolve) {\n executeCallbacks({success: resolve, error: reject}, pathsNotFound);\n }\n\n // publish bundle load event\n publish(bundleId, pathsNotFound);\n }, args);\n }\n \n if (args.returnPromise) return new Promise(loadFn);\n else loadFn();\n}\n\n\n/**\n * Execute callbacks when dependencies have been satisfied.\n * @param {(string|string[])} deps - List of bundle ids\n * @param {Object} args - success/error arguments\n */\nloadjs.ready = function ready(deps, args) {\n // subscribe to bundle load event\n subscribe(deps, function (depsNotFound) {\n // execute callbacks\n executeCallbacks(args, depsNotFound);\n });\n\n return loadjs;\n};\n\n\n/**\n * Manually satisfy bundle dependencies.\n * @param {string} bundleId - The bundle id\n */\nloadjs.done = function done(bundleId) {\n publish(bundleId, []);\n};\n\n\n/**\n * Reset loadjs dependencies statuses\n */\nloadjs.reset = function reset() {\n bundleIdCache = {};\n bundleResultCache = {};\n bundleCallbackQueue = {};\n};\n\n\n/**\n * Determine if bundle has already been defined\n * @param String} bundleId - The bundle id\n */\nloadjs.isDefined = function isDefined(bundleId) {\n return bundleId in bundleIdCache;\n};\n\n\n// export\nreturn loadjs;\n\n}));\n","// ==========================================================================\n// Load an external script\n// ==========================================================================\n\nimport loadjs from 'loadjs';\n\nexport default function loadScript(url) {\n return new Promise((resolve, reject) => {\n loadjs(url, {\n success: resolve,\n error: reject,\n });\n });\n}\n","// ==========================================================================\n// Vimeo plugin\n// ==========================================================================\n\nimport captions from '../captions';\nimport controls from '../controls';\nimport ui from '../ui';\nimport { createElement, replaceElement, toggleClass } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport loadScript from '../utils/load-script';\nimport { format, stripHTML } from '../utils/strings';\nimport { roundAspectRatio, setAspectRatio } from '../utils/style';\nimport { buildUrlParams } from '../utils/urls';\n\n// Parse Vimeo ID from URL\nfunction parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n if (is.number(Number(url))) {\n return url;\n }\n\n const regex = /^.*(vimeo.com\\/|video\\/)(\\d+).*/;\n return url.match(regex) ? RegExp.$2 : url;\n}\n\n// Try to extract a hash for private videos from the URL\nfunction parseHash(url) {\n /* This regex matches a hexadecimal hash if given in any of these forms:\n * - [https://player.]vimeo.com/video/{id}/{hash}[?params]\n * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms]\n * - [https://player.]vimeo.com/video/{id}?[params]&h={hash}\n * - video/{id}/{hash}\n * If matched, the hash is available in the named group `hash`\n */\n const regex = /^.*(?:vimeo.com\\/|video\\/)(?:\\d+)(?:\\?.*&*h=|\\/)+(?<hash>[\\d,a-f]+)/;\n const found = url.match(regex);\n\n return found ? found.groups.hash : null;\n}\n\n// Set playback state and trigger change (only on actual change)\nfunction assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nconst vimeo = {\n setup() {\n const player = this;\n\n // Add embed class for responsive\n toggleClass(player.elements.wrapper, player.config.classNames.embed, true);\n\n // Set speed options from config\n player.options.speed = player.config.speed.options;\n\n // Set intial ratio\n setAspectRatio.call(player);\n\n // Load the SDK if not already\n if (!is.object(window.Vimeo)) {\n loadScript(player.config.urls.vimeo.sdk)\n .then(() => {\n vimeo.ready.call(player);\n })\n .catch((error) => {\n player.debug.warn('Vimeo SDK (player.js) failed to load', error);\n });\n } else {\n vimeo.ready.call(player);\n }\n },\n\n // API Ready\n ready() {\n const player = this;\n const config = player.config.vimeo;\n const { premium, referrerPolicy, ...frameParams } = config;\n // Get the source URL or ID\n let source = player.media.getAttribute('src');\n let hash = '';\n // Get from <div> if needed\n if (is.empty(source)) {\n source = player.media.getAttribute(player.config.attributes.embed.id);\n // hash can also be set as attribute on the <div>\n hash = player.media.getAttribute(player.config.attributes.embed.hash);\n } else {\n hash = parseHash(source);\n }\n const hashParam = hash ? { h: hash } : {};\n\n // If the owner has a pro or premium account then we can hide controls etc\n if (premium) {\n Object.assign(frameParams, {\n controls: false,\n sidedock: false,\n });\n }\n\n // Get Vimeo params for the iframe\n const params = buildUrlParams({\n loop: player.config.loop.active,\n autoplay: player.autoplay,\n muted: player.muted,\n gesture: 'media',\n playsinline: !this.config.fullscreen.iosNative,\n // hash has to be added to iframe-URL\n ...hashParam,\n ...frameParams,\n });\n\n const id = parseId(source);\n // Build an iframe\n const iframe = createElement('iframe');\n const src = format(player.config.urls.vimeo.iframe, id, params);\n iframe.setAttribute('src', src);\n iframe.setAttribute('allowfullscreen', '');\n iframe.setAttribute(\n 'allow',\n ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; '),\n );\n\n // Set the referrer policy if required\n if (!is.empty(referrerPolicy)) {\n iframe.setAttribute('referrerPolicy', referrerPolicy);\n }\n\n // Inject the package\n if (premium || !config.customControls) {\n iframe.setAttribute('data-poster', player.poster);\n player.media = replaceElement(iframe, player.media);\n } else {\n const wrapper = createElement('div', {\n class: player.config.classNames.embedContainer,\n 'data-poster': player.poster,\n });\n wrapper.appendChild(iframe);\n player.media = replaceElement(wrapper, player.media);\n }\n\n // Get poster image\n if (!config.customControls) {\n fetch(format(player.config.urls.vimeo.api, src)).then((response) => {\n if (is.empty(response) || !response.thumbnail_url) {\n return;\n }\n\n // Set and show poster\n ui.setPoster.call(player, response.thumbnail_url).catch(() => {});\n });\n }\n\n // Setup instance\n // https://github.com/vimeo/player.js\n player.embed = new window.Vimeo.Player(iframe, {\n autopause: player.config.autopause,\n muted: player.muted,\n });\n\n player.media.paused = true;\n player.media.currentTime = 0;\n\n // Disable native text track rendering\n if (player.supported.ui) {\n player.embed.disableTextTrack();\n }\n\n // Create a faux HTML5 API using the Vimeo API\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n return player.embed.play();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n return player.embed.pause();\n };\n\n player.media.stop = () => {\n player.pause();\n player.currentTime = 0;\n };\n\n // Seeking\n let { currentTime } = player.media;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return currentTime;\n },\n set(time) {\n // Vimeo will automatically play on seek if the video hasn't been played before\n\n // Get current paused state and volume etc\n const { embed, media, paused, volume } = player;\n const restorePause = paused && !embed.hasPlayed;\n\n // Set seeking state and trigger event\n media.seeking = true;\n triggerEvent.call(player, media, 'seeking');\n\n // If paused, mute until seek is complete\n Promise.resolve(restorePause && embed.setVolume(0))\n // Seek\n .then(() => embed.setCurrentTime(time))\n // Restore paused\n .then(() => restorePause && embed.pause())\n // Restore volume\n .then(() => restorePause && embed.setVolume(volume))\n .catch(() => {\n // Do nothing\n });\n },\n });\n\n // Playback speed\n let speed = player.config.speed.selected;\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return speed;\n },\n set(input) {\n player.embed\n .setPlaybackRate(input)\n .then(() => {\n speed = input;\n triggerEvent.call(player, player.media, 'ratechange');\n })\n .catch(() => {\n // Cannot set Playback Rate, Video is probably not on Pro account\n player.options.speed = [1];\n });\n },\n });\n\n // Volume\n let { volume } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n set(input) {\n player.embed.setVolume(input).then(() => {\n volume = input;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n },\n });\n\n // Muted\n let { muted } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : false;\n\n player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => {\n muted = toggle;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n },\n });\n\n // Loop\n let { loop } = player.config;\n Object.defineProperty(player.media, 'loop', {\n get() {\n return loop;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : player.config.loop.active;\n\n player.embed.setLoop(toggle).then(() => {\n loop = toggle;\n });\n },\n });\n\n // Source\n let currentSrc;\n player.embed\n .getVideoUrl()\n .then((value) => {\n currentSrc = value;\n controls.setDownloadUrl.call(player);\n })\n .catch((error) => {\n this.debug.warn(error);\n });\n\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return currentSrc;\n },\n });\n\n // Ended\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n },\n });\n\n // Set aspect ratio based on video size\n Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then((dimensions) => {\n const [width, height] = dimensions;\n player.embed.ratio = roundAspectRatio(width, height);\n setAspectRatio.call(this);\n });\n\n // Set autopause\n player.embed.setAutopause(player.config.autopause).then((state) => {\n player.config.autopause = state;\n });\n\n // Get title\n player.embed.getVideoTitle().then((title) => {\n player.config.title = title;\n ui.setTitle.call(this);\n });\n\n // Get current time\n player.embed.getCurrentTime().then((value) => {\n currentTime = value;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n\n // Get duration\n player.embed.getDuration().then((value) => {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n });\n\n // Get captions\n player.embed.getTextTracks().then((tracks) => {\n player.media.textTracks = tracks;\n captions.setup.call(player);\n });\n\n player.embed.on('cuechange', ({ cues = [] }) => {\n const strippedCues = cues.map((cue) => stripHTML(cue.text));\n captions.updateCues.call(player, strippedCues);\n });\n\n player.embed.on('loaded', () => {\n // Assure state and events are updated on autoplay\n player.embed.getPaused().then((paused) => {\n assurePlaybackState.call(player, !paused);\n if (!paused) {\n triggerEvent.call(player, player.media, 'playing');\n }\n });\n\n if (is.element(player.embed.element) && player.supported.ui) {\n const frame = player.embed.element;\n\n // Fix keyboard focus issues\n // https://github.com/sampotts/plyr/issues/317\n frame.setAttribute('tabindex', -1);\n }\n });\n\n player.embed.on('bufferstart', () => {\n triggerEvent.call(player, player.media, 'waiting');\n });\n\n player.embed.on('bufferend', () => {\n triggerEvent.call(player, player.media, 'playing');\n });\n\n player.embed.on('play', () => {\n assurePlaybackState.call(player, true);\n triggerEvent.call(player, player.media, 'playing');\n });\n\n player.embed.on('pause', () => {\n assurePlaybackState.call(player, false);\n });\n\n player.embed.on('timeupdate', (data) => {\n player.media.seeking = false;\n currentTime = data.seconds;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n\n player.embed.on('progress', (data) => {\n player.media.buffered = data.percent;\n triggerEvent.call(player, player.media, 'progress');\n\n // Check all loaded\n if (parseInt(data.percent, 10) === 1) {\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n\n // Get duration as if we do it before load, it gives an incorrect value\n // https://github.com/sampotts/plyr/issues/891\n player.embed.getDuration().then((value) => {\n if (value !== player.media.duration) {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }\n });\n });\n\n player.embed.on('seeked', () => {\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n });\n\n player.embed.on('ended', () => {\n player.media.paused = true;\n triggerEvent.call(player, player.media, 'ended');\n });\n\n player.embed.on('error', (detail) => {\n player.media.error = detail;\n triggerEvent.call(player, player.media, 'error');\n });\n\n // Rebuild UI\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 0);\n }\n },\n};\n\nexport default vimeo;\n","// ==========================================================================\n// YouTube plugin\n// ==========================================================================\n\nimport ui from '../ui';\nimport { createElement, replaceElement, toggleClass } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport loadImage from '../utils/load-image';\nimport loadScript from '../utils/load-script';\nimport { extend } from '../utils/objects';\nimport { format, generateId } from '../utils/strings';\nimport { roundAspectRatio, setAspectRatio } from '../utils/style';\n\n// Parse YouTube ID from URL\nfunction parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n const regex = /^.*(youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=|&v=)([^#&?]*).*/;\n return url.match(regex) ? RegExp.$2 : url;\n}\n\n// Set playback state and trigger change (only on actual change)\nfunction assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nfunction getHost(config) {\n if (config.noCookie) {\n return 'https://www.youtube-nocookie.com';\n }\n\n if (window.location.protocol === 'http:') {\n return 'http://www.youtube.com';\n }\n\n // Use YouTube's default\n return undefined;\n}\n\nconst youtube = {\n setup() {\n // Add embed class for responsive\n toggleClass(this.elements.wrapper, this.config.classNames.embed, true);\n\n // Setup API\n if (is.object(window.YT) && is.function(window.YT.Player)) {\n youtube.ready.call(this);\n } else {\n // Reference current global callback\n const callback = window.onYouTubeIframeAPIReady;\n\n // Set callback to process queue\n window.onYouTubeIframeAPIReady = () => {\n // Call global callback if set\n if (is.function(callback)) {\n callback();\n }\n\n youtube.ready.call(this);\n };\n\n // Load the SDK\n loadScript(this.config.urls.youtube.sdk).catch((error) => {\n this.debug.warn('YouTube API failed to load', error);\n });\n }\n },\n\n // Get the media title\n getTitle(videoId) {\n const url = format(this.config.urls.youtube.api, videoId);\n\n fetch(url)\n .then((data) => {\n if (is.object(data)) {\n const { title, height, width } = data;\n\n // Set title\n this.config.title = title;\n ui.setTitle.call(this);\n\n // Set aspect ratio\n this.embed.ratio = roundAspectRatio(width, height);\n }\n\n setAspectRatio.call(this);\n })\n .catch(() => {\n // Set aspect ratio\n setAspectRatio.call(this);\n });\n },\n\n // API ready\n ready() {\n const player = this;\n const config = player.config.youtube;\n // Ignore already setup (race condition)\n const currentId = player.media && player.media.getAttribute('id');\n if (!is.empty(currentId) && currentId.startsWith('youtube-')) {\n return;\n }\n\n // Get the source URL or ID\n let source = player.media.getAttribute('src');\n\n // Get from <div> if needed\n if (is.empty(source)) {\n source = player.media.getAttribute(this.config.attributes.embed.id);\n }\n\n // Replace the <iframe> with a <div> due to YouTube API issues\n const videoId = parseId(source);\n const id = generateId(player.provider);\n // Replace media element\n const container = createElement('div', { id, 'data-poster': config.customControls ? player.poster : undefined });\n player.media = replaceElement(container, player.media);\n\n // Only load the poster when using custom controls\n if (config.customControls) {\n const posterSrc = (s) => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`;\n\n // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide)\n loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded\n .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3\n .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists\n .then((image) => ui.setPoster.call(player, image.src))\n .then((src) => {\n // If the image is padded, use background-size \"cover\" instead (like youtube does too with their posters)\n if (!src.includes('maxres')) {\n player.elements.poster.style.backgroundSize = 'cover';\n }\n })\n .catch(() => {});\n }\n\n // Setup instance\n // https://developers.google.com/youtube/iframe_api_reference\n player.embed = new window.YT.Player(player.media, {\n videoId,\n host: getHost(config),\n playerVars: extend(\n {},\n {\n // Autoplay\n autoplay: player.config.autoplay ? 1 : 0,\n // iframe interface language\n hl: player.config.hl,\n // Only show controls if not fully supported or opted out\n controls: player.supported.ui && config.customControls ? 0 : 1,\n // Disable keyboard as we handle it\n disablekb: 1,\n // Allow iOS inline playback\n playsinline: !player.config.fullscreen.iosNative ? 1 : 0,\n // Captions are flaky on YouTube\n cc_load_policy: player.captions.active ? 1 : 0,\n cc_lang_pref: player.config.captions.language,\n // Tracking for stats\n widget_referrer: window ? window.location.href : null,\n },\n config,\n ),\n events: {\n onError(event) {\n // YouTube may fire onError twice, so only handle it once\n if (!player.media.error) {\n const code = event.data;\n // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError\n const message =\n {\n 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.',\n 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.',\n 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.',\n 101: 'The owner of the requested video does not allow it to be played in embedded players.',\n 150: 'The owner of the requested video does not allow it to be played in embedded players.',\n }[code] || 'An unknown error occured';\n\n player.media.error = { code, message };\n\n triggerEvent.call(player, player.media, 'error');\n }\n },\n onPlaybackRateChange(event) {\n // Get the instance\n const instance = event.target;\n\n // Get current speed\n player.media.playbackRate = instance.getPlaybackRate();\n\n triggerEvent.call(player, player.media, 'ratechange');\n },\n onReady(event) {\n // Bail if onReady has already been called. See issue #1108\n if (is.function(player.media.play)) {\n return;\n }\n // Get the instance\n const instance = event.target;\n\n // Get the title\n youtube.getTitle.call(player, videoId);\n\n // Create a faux HTML5 API using the YouTube API\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n instance.playVideo();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n instance.pauseVideo();\n };\n\n player.media.stop = () => {\n instance.stopVideo();\n };\n\n player.media.duration = instance.getDuration();\n player.media.paused = true;\n\n // Seeking\n player.media.currentTime = 0;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return Number(instance.getCurrentTime());\n },\n set(time) {\n // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet).\n if (player.paused && !player.embed.hasPlayed) {\n player.embed.mute();\n }\n\n // Set seeking state and trigger event\n player.media.seeking = true;\n triggerEvent.call(player, player.media, 'seeking');\n\n // Seek after events sent\n instance.seekTo(time);\n },\n });\n\n // Playback speed\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return instance.getPlaybackRate();\n },\n set(input) {\n instance.setPlaybackRate(input);\n },\n });\n\n // Volume\n let { volume } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n set(input) {\n volume = input;\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n },\n });\n\n // Muted\n let { muted } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : muted;\n muted = toggle;\n instance[toggle ? 'mute' : 'unMute']();\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n },\n });\n\n // Source\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return instance.getVideoUrl();\n },\n });\n\n // Ended\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n },\n });\n\n // Get available speeds\n const speeds = instance.getAvailablePlaybackRates();\n // Filter based on config\n player.options.speed = speeds.filter((s) => player.config.speed.options.includes(s));\n\n // Set the tabindex to avoid focus entering iframe\n if (player.supported.ui && config.customControls) {\n player.media.setAttribute('tabindex', -1);\n }\n\n triggerEvent.call(player, player.media, 'timeupdate');\n triggerEvent.call(player, player.media, 'durationchange');\n\n // Reset timer\n clearInterval(player.timers.buffering);\n\n // Setup buffering\n player.timers.buffering = setInterval(() => {\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction();\n\n // Trigger progress only when we actually buffer something\n if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) {\n triggerEvent.call(player, player.media, 'progress');\n }\n\n // Set last buffer point\n player.media.lastBuffered = player.media.buffered;\n\n // Bail if we're at 100%\n if (player.media.buffered === 1) {\n clearInterval(player.timers.buffering);\n\n // Trigger event\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n }, 200);\n\n // Rebuild UI\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 50);\n }\n },\n onStateChange(event) {\n // Get the instance\n const instance = event.target;\n\n // Reset timer\n clearInterval(player.timers.playing);\n\n const seeked = player.media.seeking && [1, 2].includes(event.data);\n\n if (seeked) {\n // Unset seeking and fire seeked event\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n }\n\n // Handle events\n // -1 Unstarted\n // 0 Ended\n // 1 Playing\n // 2 Paused\n // 3 Buffering\n // 5 Video cued\n switch (event.data) {\n case -1:\n // Update scrubber\n triggerEvent.call(player, player.media, 'timeupdate');\n\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction();\n triggerEvent.call(player, player.media, 'progress');\n\n break;\n\n case 0:\n assurePlaybackState.call(player, false);\n\n // YouTube doesn't support loop for a single video, so mimick it.\n if (player.media.loop) {\n // YouTube needs a call to `stopVideo` before playing again\n instance.stopVideo();\n instance.playVideo();\n } else {\n triggerEvent.call(player, player.media, 'ended');\n }\n\n break;\n\n case 1:\n // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet)\n if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) {\n player.media.pause();\n } else {\n assurePlaybackState.call(player, true);\n\n triggerEvent.call(player, player.media, 'playing');\n\n // Poll to get playback progress\n player.timers.playing = setInterval(() => {\n triggerEvent.call(player, player.media, 'timeupdate');\n }, 50);\n\n // Check duration again due to YouTube bug\n // https://github.com/sampotts/plyr/issues/374\n // https://code.google.com/p/gdata-issues/issues/detail?id=8690\n if (player.media.duration !== instance.getDuration()) {\n player.media.duration = instance.getDuration();\n triggerEvent.call(player, player.media, 'durationchange');\n }\n }\n\n break;\n\n case 2:\n // Restore audio (YouTube starts playing on seek if the video hasn't been played yet)\n if (!player.muted) {\n player.embed.unMute();\n }\n assurePlaybackState.call(player, false);\n\n break;\n\n case 3:\n // Trigger waiting event to add loading classes to container as the video buffers.\n triggerEvent.call(player, player.media, 'waiting');\n\n break;\n\n default:\n break;\n }\n\n triggerEvent.call(player, player.elements.container, 'statechange', false, {\n code: event.data,\n });\n },\n },\n });\n },\n};\n\nexport default youtube;\n","// ==========================================================================\n// Plyr Media\n// ==========================================================================\n\nimport html5 from './html5';\nimport vimeo from './plugins/vimeo';\nimport youtube from './plugins/youtube';\nimport { createElement, toggleClass, wrap } from './utils/elements';\n\nconst media = {\n // Setup media\n setup() {\n // If there's no media, bail\n if (!this.media) {\n this.debug.warn('No media element found!');\n return;\n }\n\n // Add type class\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true);\n\n // Add provider class\n toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true);\n\n // Add video class for embeds\n // This will require changes if audio embeds are added\n if (this.isEmbed) {\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true);\n }\n\n // Inject the player wrapper\n if (this.isVideo) {\n // Create the wrapper div\n this.elements.wrapper = createElement('div', {\n class: this.config.classNames.video,\n });\n\n // Wrap the video in a container\n wrap(this.media, this.elements.wrapper);\n\n // Poster image container\n this.elements.poster = createElement('div', {\n class: this.config.classNames.poster,\n });\n\n this.elements.wrapper.appendChild(this.elements.poster);\n }\n\n if (this.isHTML5) {\n html5.setup.call(this);\n } else if (this.isYouTube) {\n youtube.setup.call(this);\n } else if (this.isVimeo) {\n vimeo.setup.call(this);\n }\n },\n};\n\nexport default media;\n","// ==========================================================================\n// Advertisement plugin using Google IMA HTML5 SDK\n// Create an account with our ad partner, vi here:\n// https://www.vi.ai/publisher-video-monetization/\n// ==========================================================================\n\n/* global google */\n\nimport { createElement } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport i18n from '../utils/i18n';\nimport is from '../utils/is';\nimport loadScript from '../utils/load-script';\nimport { silencePromise } from '../utils/promise';\nimport { formatTime } from '../utils/time';\nimport { buildUrlParams } from '../utils/urls';\n\nconst destroy = (instance) => {\n // Destroy our adsManager\n if (instance.manager) {\n instance.manager.destroy();\n }\n\n // Destroy our adsManager\n if (instance.elements.displayContainer) {\n instance.elements.displayContainer.destroy();\n }\n\n instance.elements.container.remove();\n};\n\nclass Ads {\n /**\n * Ads constructor.\n * @param {Object} player\n * @return {Ads}\n */\n constructor(player) {\n this.player = player;\n this.config = player.config.ads;\n this.playing = false;\n this.initialized = false;\n this.elements = {\n container: null,\n displayContainer: null,\n };\n this.manager = null;\n this.loader = null;\n this.cuePoints = null;\n this.events = {};\n this.safetyTimer = null;\n this.countdownTimer = null;\n\n // Setup a promise to resolve when the IMA manager is ready\n this.managerPromise = new Promise((resolve, reject) => {\n // The ad is loaded and ready\n this.on('loaded', resolve);\n\n // Ads failed\n this.on('error', reject);\n });\n\n this.load();\n }\n\n get enabled() {\n const { config } = this;\n\n return (\n this.player.isHTML5 &&\n this.player.isVideo &&\n config.enabled &&\n (!is.empty(config.publisherId) || is.url(config.tagUrl))\n );\n }\n\n /**\n * Load the IMA SDK\n */\n load = () => {\n if (!this.enabled) {\n return;\n }\n\n // Check if the Google IMA3 SDK is loaded or load it ourselves\n if (!is.object(window.google) || !is.object(window.google.ima)) {\n loadScript(this.player.config.urls.googleIMA.sdk)\n .then(() => {\n this.ready();\n })\n .catch(() => {\n // Script failed to load or is blocked\n this.trigger('error', new Error('Google IMA SDK failed to load'));\n });\n } else {\n this.ready();\n }\n };\n\n /**\n * Get the ads instance ready\n */\n ready = () => {\n // Double check we're enabled\n if (!this.enabled) {\n destroy(this);\n }\n\n // Start ticking our safety timer. If the whole advertisement\n // thing doesn't resolve within our set time; we bail\n this.startSafetyTimer(12000, 'ready()');\n\n // Clear the safety timer\n this.managerPromise.then(() => {\n this.clearSafetyTimer('onAdsManagerLoaded()');\n });\n\n // Set listeners on the Plyr instance\n this.listeners();\n\n // Setup the IMA SDK\n this.setupIMA();\n };\n\n // Build the tag URL\n get tagUrl() {\n const { config } = this;\n\n if (is.url(config.tagUrl)) {\n return config.tagUrl;\n }\n\n const params = {\n AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',\n AV_CHANNELID: '5a0458dc28a06145e4519d21',\n AV_URL: window.location.hostname,\n cb: Date.now(),\n AV_WIDTH: 640,\n AV_HEIGHT: 480,\n AV_CDIM2: config.publisherId,\n };\n\n const base = 'https://go.aniview.com/api/adserver6/vast/';\n\n return `${base}?${buildUrlParams(params)}`;\n }\n\n /**\n * In order for the SDK to display ads for our video, we need to tell it where to put them,\n * so here we define our ad container. This div is set up to render on top of the video player.\n * Using the code below, we tell the SDK to render ads within that div. We also provide a\n * handle to the content video player - the SDK will poll the current time of our player to\n * properly place mid-rolls. After we create the ad display container, we initialize it. On\n * mobile devices, this initialization is done as the result of a user action.\n */\n setupIMA = () => {\n // Create the container for our advertisements\n this.elements.container = createElement('div', {\n class: this.player.config.classNames.ads,\n });\n\n this.player.elements.container.appendChild(this.elements.container);\n\n // So we can run VPAID2\n google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);\n\n // Set language\n google.ima.settings.setLocale(this.player.config.ads.language);\n\n // Set playback for iOS10+\n google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline);\n\n // We assume the adContainer is the video container of the plyr element that will house the ads\n this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container, this.player.media);\n\n // Create ads loader\n this.loader = new google.ima.AdsLoader(this.elements.displayContainer);\n\n // Listen and respond to ads loaded and error events\n this.loader.addEventListener(\n google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,\n (event) => this.onAdsManagerLoaded(event),\n false,\n );\n this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, (error) => this.onAdError(error), false);\n\n // Request video ads to be pre-loaded\n this.requestAds();\n };\n\n /**\n * Request advertisements\n */\n requestAds = () => {\n const { container } = this.player.elements;\n\n try {\n // Request video ads\n const request = new google.ima.AdsRequest();\n request.adTagUrl = this.tagUrl;\n\n // Specify the linear and nonlinear slot sizes. This helps the SDK\n // to select the correct creative if multiple are returned\n request.linearAdSlotWidth = container.offsetWidth;\n request.linearAdSlotHeight = container.offsetHeight;\n request.nonLinearAdSlotWidth = container.offsetWidth;\n request.nonLinearAdSlotHeight = container.offsetHeight;\n\n // We only overlay ads as we only support video.\n request.forceNonLinearFullSlot = false;\n\n // Mute based on current state\n request.setAdWillPlayMuted(!this.player.muted);\n\n this.loader.requestAds(request);\n } catch (error) {\n this.onAdError(error);\n }\n };\n\n /**\n * Update the ad countdown\n * @param {Boolean} start\n */\n pollCountdown = (start = false) => {\n if (!start) {\n clearInterval(this.countdownTimer);\n this.elements.container.removeAttribute('data-badge-text');\n return;\n }\n\n const update = () => {\n const time = formatTime(Math.max(this.manager.getRemainingTime(), 0));\n const label = `${i18n.get('advertisement', this.player.config)} - ${time}`;\n this.elements.container.setAttribute('data-badge-text', label);\n };\n\n this.countdownTimer = setInterval(update, 100);\n };\n\n /**\n * This method is called whenever the ads are ready inside the AdDisplayContainer\n * @param {Event} adsManagerLoadedEvent\n */\n onAdsManagerLoaded = (event) => {\n // Load could occur after a source change (race condition)\n if (!this.enabled) {\n return;\n }\n\n // Get the ads manager\n const settings = new google.ima.AdsRenderingSettings();\n\n // Tell the SDK to save and restore content video state on our behalf\n settings.restoreCustomPlaybackStateOnAdBreakComplete = true;\n settings.enablePreloading = true;\n\n // The SDK is polling currentTime on the contentPlayback. And needs a duration\n // so it can determine when to start the mid- and post-roll\n this.manager = event.getAdsManager(this.player, settings);\n\n // Get the cue points for any mid-rolls by filtering out the pre- and post-roll\n this.cuePoints = this.manager.getCuePoints();\n\n // Add listeners to the required events\n // Advertisement error events\n this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, (error) => this.onAdError(error));\n\n // Advertisement regular events\n Object.keys(google.ima.AdEvent.Type).forEach((type) => {\n this.manager.addEventListener(google.ima.AdEvent.Type[type], (e) => this.onAdEvent(e));\n });\n\n // Resolve our adsManager\n this.trigger('loaded');\n };\n\n addCuePoints = () => {\n // Add advertisement cue's within the time line if available\n if (!is.empty(this.cuePoints)) {\n this.cuePoints.forEach((cuePoint) => {\n if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {\n const seekElement = this.player.elements.progress;\n\n if (is.element(seekElement)) {\n const cuePercentage = (100 / this.player.duration) * cuePoint;\n const cue = createElement('span', {\n class: this.player.config.classNames.cues,\n });\n\n cue.style.left = `${cuePercentage.toString()}%`;\n seekElement.appendChild(cue);\n }\n }\n });\n }\n };\n\n /**\n * This is where all the event handling takes place. Retrieve the ad from the event. Some\n * events (e.g. ALL_ADS_COMPLETED) don't have the ad object associated\n * https://developers.google.com/interactive-media-ads/docs/sdks/html5/v3/apis#ima.AdEvent.Type\n * @param {Event} event\n */\n onAdEvent = (event) => {\n const { container } = this.player.elements;\n // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)\n // don't have ad object associated\n const ad = event.getAd();\n const adData = event.getAdData();\n\n // Proxy event\n const dispatchEvent = (type) => {\n triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`);\n };\n\n // Bubble the event\n dispatchEvent(event.type);\n\n switch (event.type) {\n case google.ima.AdEvent.Type.LOADED:\n // This is the first event sent for an ad - it is possible to determine whether the\n // ad is a video ad or an overlay\n this.trigger('loaded');\n\n // Start countdown\n this.pollCountdown(true);\n\n if (!ad.isLinear()) {\n // Position AdDisplayContainer correctly for overlay\n ad.width = container.offsetWidth;\n ad.height = container.offsetHeight;\n }\n\n // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex());\n // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset());\n\n break;\n\n case google.ima.AdEvent.Type.STARTED:\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n\n break;\n\n case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:\n // All ads for the current videos are done. We can now request new advertisements\n // in case the video is re-played\n\n // TODO: Example for what happens when a next video in a playlist would be loaded.\n // So here we load a new video when all ads are done.\n // Then we load new ads within a new adsManager. When the video\n // Is started - after - the ads are loaded, then we get ads.\n // You can also easily test cancelling and reloading by running\n // player.ads.cancel() and player.ads.play from the console I guess.\n // this.player.source = {\n // type: 'video',\n // title: 'View From A Blue Moon',\n // sources: [{\n // src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type:\n // 'video/mp4', }], poster:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks:\n // [ { kind: 'captions', label: 'English', srclang: 'en', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',\n // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ],\n // };\n\n // TODO: So there is still this thing where a video should only be allowed to start\n // playing when the IMA SDK is ready or has failed\n\n if (this.player.ended) {\n this.loadAds();\n } else {\n // The SDK won't allow new ads to be called without receiving a contentComplete()\n this.loader.contentComplete();\n }\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:\n // This event indicates the ad has started - the video player can adjust the UI,\n // for example display a pause button and remaining time. Fired when content should\n // be paused. This usually happens right before an ad is about to cover the content\n\n this.pauseContent();\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:\n // This event indicates the ad has finished - the video player can perform\n // appropriate UI actions, such as removing the timer for remaining time detection.\n // Fired when content should be resumed. This usually happens when an ad finishes\n // or collapses\n\n this.pollCountdown();\n\n this.resumeContent();\n\n break;\n\n case google.ima.AdEvent.Type.LOG:\n if (adData.adError) {\n this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);\n }\n\n break;\n\n default:\n break;\n }\n };\n\n /**\n * Any ad error handling comes through here\n * @param {Event} event\n */\n onAdError = (event) => {\n this.cancel();\n this.player.debug.warn('Ads error', event);\n };\n\n /**\n * Setup hooks for Plyr and window events. This ensures\n * the mid- and post-roll launch at the correct time. And\n * resize the advertisement when the player resizes\n */\n listeners = () => {\n const { container } = this.player.elements;\n let time;\n\n this.player.on('canplay', () => {\n this.addCuePoints();\n });\n\n this.player.on('ended', () => {\n this.loader.contentComplete();\n });\n\n this.player.on('timeupdate', () => {\n time = this.player.currentTime;\n });\n\n this.player.on('seeked', () => {\n const seekedTime = this.player.currentTime;\n\n if (is.empty(this.cuePoints)) {\n return;\n }\n\n this.cuePoints.forEach((cuePoint, index) => {\n if (time < cuePoint && cuePoint < seekedTime) {\n this.manager.discardAdBreak();\n this.cuePoints.splice(index, 1);\n }\n });\n });\n\n // Listen to the resizing of the window. And resize ad accordingly\n // TODO: eventually implement ResizeObserver\n window.addEventListener('resize', () => {\n if (this.manager) {\n this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n }\n });\n };\n\n /**\n * Initialize the adsManager and start playing advertisements\n */\n play = () => {\n const { container } = this.player.elements;\n\n if (!this.managerPromise) {\n this.resumeContent();\n }\n\n // Play the requested advertisement whenever the adsManager is ready\n this.managerPromise\n .then(() => {\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n\n // Initialize the container. Must be done via a user action on mobile devices\n this.elements.displayContainer.initialize();\n\n try {\n if (!this.initialized) {\n // Initialize the ads manager. Ad rules playlist will start at this time\n this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n\n // Call play to start showing the ad. Single video and overlay ads will\n // start at this time; the call will be ignored for ad rules\n this.manager.start();\n }\n\n this.initialized = true;\n } catch (adError) {\n // An error may be thrown if there was a problem with the\n // VAST response\n this.onAdError(adError);\n }\n })\n .catch(() => {});\n };\n\n /**\n * Resume our video\n */\n resumeContent = () => {\n // Hide the advertisement container\n this.elements.container.style.zIndex = '';\n\n // Ad is stopped\n this.playing = false;\n\n // Play video\n silencePromise(this.player.media.play());\n };\n\n /**\n * Pause our video\n */\n pauseContent = () => {\n // Show the advertisement container\n this.elements.container.style.zIndex = 3;\n\n // Ad is playing\n this.playing = true;\n\n // Pause our video.\n this.player.media.pause();\n };\n\n /**\n * Destroy the adsManager so we can grab new ads after this. If we don't then we're not\n * allowed to call new ads based on google policies, as they interpret this as an accidental\n * video requests. https://developers.google.com/interactive-\n * media-ads/docs/sdks/android/faq#8\n */\n cancel = () => {\n // Pause our video\n if (this.initialized) {\n this.resumeContent();\n }\n\n // Tell our instance that we're done for now\n this.trigger('error');\n\n // Re-create our adsManager\n this.loadAds();\n };\n\n /**\n * Re-create our adsManager\n */\n loadAds = () => {\n // Tell our adsManager to go bye bye\n this.managerPromise\n .then(() => {\n // Destroy our adsManager\n if (this.manager) {\n this.manager.destroy();\n }\n\n // Re-set our adsManager promises\n this.managerPromise = new Promise((resolve) => {\n this.on('loaded', resolve);\n this.player.debug.log(this.manager);\n });\n // Now that the manager has been destroyed set it to also be un-initialized\n this.initialized = false;\n\n // Now request some new advertisements\n this.requestAds();\n })\n .catch(() => {});\n };\n\n /**\n * Handles callbacks after an ad event was invoked\n * @param {String} event - Event type\n */\n trigger = (event, ...args) => {\n const handlers = this.events[event];\n\n if (is.array(handlers)) {\n handlers.forEach((handler) => {\n if (is.function(handler)) {\n handler.apply(this, args);\n }\n });\n }\n };\n\n /**\n * Add event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n * @return {Ads}\n */\n on = (event, callback) => {\n if (!is.array(this.events[event])) {\n this.events[event] = [];\n }\n\n this.events[event].push(callback);\n\n return this;\n };\n\n /**\n * Setup a safety timer for when the ad network doesn't respond for whatever reason.\n * The advertisement has 12 seconds to get its things together. We stop this timer when the\n * advertisement is playing, or when a user action is required to start, then we clear the\n * timer on ad ready\n * @param {Number} time\n * @param {String} from\n */\n startSafetyTimer = (time, from) => {\n this.player.debug.log(`Safety timer invoked from: ${from}`);\n\n this.safetyTimer = setTimeout(() => {\n this.cancel();\n this.clearSafetyTimer('startSafetyTimer()');\n }, time);\n };\n\n /**\n * Clear our safety timer(s)\n * @param {String} from\n */\n clearSafetyTimer = (from) => {\n if (!is.nullOrUndefined(this.safetyTimer)) {\n this.player.debug.log(`Safety timer cleared from: ${from}`);\n\n clearTimeout(this.safetyTimer);\n this.safetyTimer = null;\n }\n };\n}\n\nexport default Ads;\n","import { createElement } from '../utils/elements';\nimport { once } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport { formatTime } from '../utils/time';\n\n// Arg: vttDataString example: \"WEBVTT\\n\\n1\\n00:00:05.000 --> 00:00:10.000\\n1080p-00001.jpg\"\nconst parseVtt = (vttDataString) => {\n const processedList = [];\n const frames = vttDataString.split(/\\r\\n\\r\\n|\\n\\n|\\r\\r/);\n\n frames.forEach((frame) => {\n const result = {};\n const lines = frame.split(/\\r\\n|\\n|\\r/);\n\n lines.forEach((line) => {\n if (!is.number(result.startTime)) {\n // The line with start and end times on it is the first line of interest\n const matchTimes = line.match(\n /([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})/,\n ); // Note that this currently ignores caption formatting directives that are optionally on the end of this line - fine for non-captions VTT\n\n if (matchTimes) {\n result.startTime =\n Number(matchTimes[1] || 0) * 60 * 60 +\n Number(matchTimes[2]) * 60 +\n Number(matchTimes[3]) +\n Number(`0.${matchTimes[4]}`);\n result.endTime =\n Number(matchTimes[6] || 0) * 60 * 60 +\n Number(matchTimes[7]) * 60 +\n Number(matchTimes[8]) +\n Number(`0.${matchTimes[9]}`);\n }\n } else if (!is.empty(line.trim()) && is.empty(result.text)) {\n // If we already have the startTime, then we're definitely up to the text line(s)\n const lineSplit = line.trim().split('#xywh=');\n [result.text] = lineSplit;\n\n // If there's content in lineSplit[1], then we have sprites. If not, then it's just one frame per image\n if (lineSplit[1]) {\n [result.x, result.y, result.w, result.h] = lineSplit[1].split(',');\n }\n }\n });\n\n if (result.text) {\n processedList.push(result);\n }\n });\n\n return processedList;\n};\n\n/**\n * Preview thumbnails for seek hover and scrubbing\n * Seeking: Hover over the seek bar (desktop only): shows a small preview container above the seek bar\n * 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\n *\n * Notes:\n * - 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\n * - 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\n * - 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\n */\n\nconst fitRatio = (ratio, outer) => {\n const targetRatio = outer.width / outer.height;\n const result = {};\n if (ratio > targetRatio) {\n result.width = outer.width;\n result.height = (1 / ratio) * outer.width;\n } else {\n result.height = outer.height;\n result.width = ratio * outer.height;\n }\n\n return result;\n};\n\nclass PreviewThumbnails {\n /**\n * PreviewThumbnails constructor.\n * @param {Plyr} player\n * @return {PreviewThumbnails}\n */\n constructor(player) {\n this.player = player;\n this.thumbnails = [];\n this.loaded = false;\n this.lastMouseMoveTime = Date.now();\n this.mouseDown = false;\n this.loadedImages = [];\n\n this.elements = {\n thumb: {},\n scrubbing: {},\n };\n\n this.load();\n }\n\n get enabled() {\n return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;\n }\n\n load = () => {\n // Toggle the regular seek tooltip\n if (this.player.elements.display.seekTooltip) {\n this.player.elements.display.seekTooltip.hidden = this.enabled;\n }\n\n if (!this.enabled) {\n return;\n }\n\n this.getThumbnails().then(() => {\n if (!this.enabled) {\n return;\n }\n\n // Render DOM elements\n this.render();\n\n // Check to see if thumb container size was specified manually in CSS\n this.determineContainerAutoSizing();\n\n this.loaded = true;\n });\n };\n\n // Download VTT files and parse them\n getThumbnails = () => {\n return new Promise((resolve) => {\n const { src } = this.player.config.previewThumbnails;\n\n if (is.empty(src)) {\n throw new Error('Missing previewThumbnails.src config attribute');\n }\n\n // Resolve promise\n const sortAndResolve = () => {\n // Sort smallest to biggest (e.g., [120p, 480p, 1080p])\n this.thumbnails.sort((x, y) => x.height - y.height);\n\n this.player.debug.log('Preview thumbnails', this.thumbnails);\n\n resolve();\n };\n\n // Via callback()\n if (is.function(src)) {\n src((thumbnails) => {\n this.thumbnails = thumbnails;\n sortAndResolve();\n });\n }\n // VTT urls\n else {\n // If string, convert into single-element list\n const urls = is.string(src) ? [src] : src;\n // Loop through each src URL. Download and process the VTT file, storing the resulting data in this.thumbnails\n const promises = urls.map((u) => this.getThumbnail(u));\n // Resolve\n Promise.all(promises).then(sortAndResolve);\n }\n });\n };\n\n // Process individual VTT file\n getThumbnail = (url) => {\n return new Promise((resolve) => {\n fetch(url).then((response) => {\n const thumbnail = {\n frames: parseVtt(response),\n height: null,\n urlPrefix: '',\n };\n\n // If the URLs don't start with '/', then we need to set their relative path to be the location of the VTT file\n // If the URLs do start with '/', then they obviously don't need a prefix, so it will remain blank\n // If the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file\n if (\n !thumbnail.frames[0].text.startsWith('/') &&\n !thumbnail.frames[0].text.startsWith('http://') &&\n !thumbnail.frames[0].text.startsWith('https://')\n ) {\n thumbnail.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1);\n }\n\n // Download the first frame, so that we can determine/set the height of this thumbnailsDef\n const tempImage = new Image();\n\n tempImage.onload = () => {\n thumbnail.height = tempImage.naturalHeight;\n thumbnail.width = tempImage.naturalWidth;\n\n this.thumbnails.push(thumbnail);\n\n resolve();\n };\n\n tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;\n });\n });\n };\n\n startMove = (event) => {\n if (!this.loaded) {\n return;\n }\n\n if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {\n return;\n }\n\n // Wait until media has a duration\n if (!this.player.media.duration) {\n return;\n }\n\n if (event.type === 'touchmove') {\n // Calculate seek hover position as approx video seconds\n this.seekTime = this.player.media.duration * (this.player.elements.inputs.seek.value / 100);\n } else {\n // Calculate seek hover position as approx video seconds\n const clientRect = this.player.elements.progress.getBoundingClientRect();\n const percentage = (100 / clientRect.width) * (event.pageX - clientRect.left);\n this.seekTime = this.player.media.duration * (percentage / 100);\n\n if (this.seekTime < 0) {\n // The mousemove fires for 10+px out to the left\n this.seekTime = 0;\n }\n\n if (this.seekTime > this.player.media.duration - 1) {\n // Took 1 second off the duration for safety, because different players can disagree on the real duration of a video\n this.seekTime = this.player.media.duration - 1;\n }\n\n this.mousePosX = event.pageX;\n\n // Set time text inside image container\n this.elements.thumb.time.innerText = formatTime(this.seekTime);\n }\n\n // Download and show image\n this.showImageAtCurrentTime();\n };\n\n endMove = () => {\n this.toggleThumbContainer(false, true);\n };\n\n startScrubbing = (event) => {\n // Only act on left mouse button (0), or touch device (event.button does not exist or is false)\n if (is.nullOrUndefined(event.button) || event.button === false || event.button === 0) {\n this.mouseDown = true;\n\n // Wait until media has a duration\n if (this.player.media.duration) {\n this.toggleScrubbingContainer(true);\n this.toggleThumbContainer(false, true);\n\n // Download and show image\n this.showImageAtCurrentTime();\n }\n }\n };\n\n endScrubbing = () => {\n this.mouseDown = false;\n\n // Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview\n if (Math.ceil(this.lastTime) === Math.ceil(this.player.media.currentTime)) {\n // The video was already seeked/loaded at the chosen time - hide immediately\n this.toggleScrubbingContainer(false);\n } else {\n // The video hasn't seeked yet. Wait for that\n once.call(this.player, this.player.media, 'timeupdate', () => {\n // Re-check mousedown - we might have already started scrubbing again\n if (!this.mouseDown) {\n this.toggleScrubbingContainer(false);\n }\n });\n }\n };\n\n /**\n * Setup hooks for Plyr and window events\n */\n listeners = () => {\n // 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\n this.player.on('play', () => {\n this.toggleThumbContainer(false, true);\n });\n\n this.player.on('seeked', () => {\n this.toggleThumbContainer(false);\n });\n\n this.player.on('timeupdate', () => {\n this.lastTime = this.player.media.currentTime;\n });\n };\n\n /**\n * Create HTML elements for image containers\n */\n render = () => {\n // Create HTML element: plyr__preview-thumbnail-container\n this.elements.thumb.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.thumbContainer,\n });\n\n // Wrapper for the image for styling\n this.elements.thumb.imageContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.imageContainer,\n });\n this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer);\n\n // Create HTML element, parent+span: time text (e.g., 01:32:00)\n const timeContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.timeContainer,\n });\n\n this.elements.thumb.time = createElement('span', {}, '00:00');\n timeContainer.appendChild(this.elements.thumb.time);\n\n this.elements.thumb.container.appendChild(timeContainer);\n\n // Inject the whole thumb\n if (is.element(this.player.elements.progress)) {\n this.player.elements.progress.appendChild(this.elements.thumb.container);\n }\n\n // Create HTML element: plyr__preview-scrubbing-container\n this.elements.scrubbing.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.scrubbingContainer,\n });\n\n this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);\n };\n\n destroy = () => {\n if (this.elements.thumb.container) {\n this.elements.thumb.container.remove();\n }\n if (this.elements.scrubbing.container) {\n this.elements.scrubbing.container.remove();\n }\n };\n\n showImageAtCurrentTime = () => {\n if (this.mouseDown) {\n this.setScrubbingContainerSize();\n } else {\n this.setThumbContainerSizeAndPos();\n }\n\n // Find the desired thumbnail index\n // TODO: Handle a video longer than the thumbs where thumbNum is null\n const thumbNum = this.thumbnails[0].frames.findIndex(\n (frame) => this.seekTime >= frame.startTime && this.seekTime <= frame.endTime,\n );\n const hasThumb = thumbNum >= 0;\n let qualityIndex = 0;\n\n // Show the thumb container if we're not scrubbing\n if (!this.mouseDown) {\n this.toggleThumbContainer(hasThumb);\n }\n\n // No matching thumb found\n if (!hasThumb) {\n return;\n }\n\n // Check to see if we've already downloaded higher quality versions of this image\n this.thumbnails.forEach((thumbnail, index) => {\n if (this.loadedImages.includes(thumbnail.frames[thumbNum].text)) {\n qualityIndex = index;\n }\n });\n\n // Only proceed if either thumbnum or thumbfilename has changed\n if (thumbNum !== this.showingThumb) {\n this.showingThumb = thumbNum;\n this.loadImage(qualityIndex);\n }\n };\n\n // Show the image that's currently specified in this.showingThumb\n loadImage = (qualityIndex = 0) => {\n const thumbNum = this.showingThumb;\n const thumbnail = this.thumbnails[qualityIndex];\n const { urlPrefix } = thumbnail;\n const frame = thumbnail.frames[thumbNum];\n const thumbFilename = thumbnail.frames[thumbNum].text;\n const thumbUrl = urlPrefix + thumbFilename;\n\n if (!this.currentImageElement || this.currentImageElement.dataset.filename !== thumbFilename) {\n // If we're already loading a previous image, remove its onload handler - we don't want it to load after this one\n // Only do this if not using sprites. Without sprites we really want to show as many images as possible, as a best-effort\n if (this.loadingImage && this.usingSprites) {\n this.loadingImage.onload = null;\n }\n\n // We're building and adding a new image. In other implementations of similar functionality (YouTube), background image\n // is instead used. But this causes issues with larger images in Firefox and Safari - switching between background\n // images causes a flicker. Putting a new image over the top does not\n const previewImage = new Image();\n previewImage.src = thumbUrl;\n previewImage.dataset.index = thumbNum;\n previewImage.dataset.filename = thumbFilename;\n this.showingThumbFilename = thumbFilename;\n\n this.player.debug.log(`Loading image: ${thumbUrl}`);\n\n // For some reason, passing the named function directly causes it to execute immediately. So I've wrapped it in an anonymous function...\n previewImage.onload = () => this.showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, true);\n this.loadingImage = previewImage;\n this.removeOldImages(previewImage);\n } else {\n // Update the existing image\n this.showImage(this.currentImageElement, frame, qualityIndex, thumbNum, thumbFilename, false);\n this.currentImageElement.dataset.index = thumbNum;\n this.removeOldImages(this.currentImageElement);\n }\n };\n\n showImage = (previewImage, frame, qualityIndex, thumbNum, thumbFilename, newImage = true) => {\n this.player.debug.log(\n `Showing thumb: ${thumbFilename}. num: ${thumbNum}. qual: ${qualityIndex}. newimg: ${newImage}`,\n );\n this.setImageSizeAndOffset(previewImage, frame);\n\n if (newImage) {\n this.currentImageContainer.appendChild(previewImage);\n this.currentImageElement = previewImage;\n\n if (!this.loadedImages.includes(thumbFilename)) {\n this.loadedImages.push(thumbFilename);\n }\n }\n\n // Preload images before and after the current one\n // Show higher quality of the same frame\n // 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\n this.preloadNearby(thumbNum, true)\n .then(this.preloadNearby(thumbNum, false))\n .then(this.getHigherQuality(qualityIndex, previewImage, frame, thumbFilename));\n };\n\n // Remove all preview images that aren't the designated current image\n removeOldImages = (currentImage) => {\n // Get a list of all images, convert it from a DOM list to an array\n Array.from(this.currentImageContainer.children).forEach((image) => {\n if (image.tagName.toLowerCase() !== 'img') {\n return;\n }\n\n const removeDelay = this.usingSprites ? 500 : 1000;\n\n if (image.dataset.index !== currentImage.dataset.index && !image.dataset.deleting) {\n // 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\n // First set attribute 'deleting' to prevent multi-handling of this on repeat firing of this function\n // eslint-disable-next-line no-param-reassign\n image.dataset.deleting = true;\n\n // This has to be set before the timeout - to prevent issues switching between hover and scrub\n const { currentImageContainer } = this;\n\n setTimeout(() => {\n currentImageContainer.removeChild(image);\n this.player.debug.log(`Removing thumb: ${image.dataset.filename}`);\n }, removeDelay);\n }\n });\n };\n\n // Preload images before and after the current one. Only if the user is still hovering/seeking the same frame\n // This will only preload the lowest quality\n preloadNearby = (thumbNum, forward = true) => {\n return new Promise((resolve) => {\n setTimeout(() => {\n const oldThumbFilename = this.thumbnails[0].frames[thumbNum].text;\n\n if (this.showingThumbFilename === oldThumbFilename) {\n // 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\n let thumbnailsClone;\n if (forward) {\n thumbnailsClone = this.thumbnails[0].frames.slice(thumbNum);\n } else {\n thumbnailsClone = this.thumbnails[0].frames.slice(0, thumbNum).reverse();\n }\n\n let foundOne = false;\n\n thumbnailsClone.forEach((frame) => {\n const newThumbFilename = frame.text;\n\n if (newThumbFilename !== oldThumbFilename) {\n // Found one with a different filename. Make sure it hasn't already been loaded on this page visit\n if (!this.loadedImages.includes(newThumbFilename)) {\n foundOne = true;\n this.player.debug.log(`Preloading thumb filename: ${newThumbFilename}`);\n\n const { urlPrefix } = this.thumbnails[0];\n const thumbURL = urlPrefix + newThumbFilename;\n const previewImage = new Image();\n previewImage.src = thumbURL;\n previewImage.onload = () => {\n this.player.debug.log(`Preloaded thumb filename: ${newThumbFilename}`);\n if (!this.loadedImages.includes(newThumbFilename)) this.loadedImages.push(newThumbFilename);\n\n // We don't resolve until the thumb is loaded\n resolve();\n };\n }\n }\n });\n\n // If there are none to preload then we want to resolve immediately\n if (!foundOne) {\n resolve();\n }\n }\n }, 300);\n });\n };\n\n // If user has been hovering current image for half a second, look for a higher quality one\n getHigherQuality = (currentQualityIndex, previewImage, frame, thumbFilename) => {\n if (currentQualityIndex < this.thumbnails.length - 1) {\n // 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\n let previewImageHeight = previewImage.naturalHeight;\n\n if (this.usingSprites) {\n previewImageHeight = frame.h;\n }\n\n if (previewImageHeight < this.thumbContainerHeight) {\n // Recurse back to the loadImage function - show a higher quality one, but only if the viewer is on this frame for a while\n setTimeout(() => {\n // Make sure the mouse hasn't already moved on and started hovering at another image\n if (this.showingThumbFilename === thumbFilename) {\n this.player.debug.log(`Showing higher quality thumb for: ${thumbFilename}`);\n this.loadImage(currentQualityIndex + 1);\n }\n }, 300);\n }\n }\n };\n\n get currentImageContainer() {\n if (this.mouseDown) {\n return this.elements.scrubbing.container;\n }\n\n return this.elements.thumb.imageContainer;\n }\n\n get usingSprites() {\n return Object.keys(this.thumbnails[0].frames[0]).includes('w');\n }\n\n get thumbAspectRatio() {\n if (this.usingSprites) {\n return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;\n }\n\n return this.thumbnails[0].width / this.thumbnails[0].height;\n }\n\n get thumbContainerHeight() {\n if (this.mouseDown) {\n const { height } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight,\n });\n return height;\n }\n\n // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset)\n if (this.sizeSpecifiedInCSS) {\n return this.elements.thumb.imageContainer.clientHeight;\n }\n\n return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);\n }\n\n get currentImageElement() {\n if (this.mouseDown) {\n return this.currentScrubbingImageElement;\n }\n\n return this.currentThumbnailImageElement;\n }\n\n set currentImageElement(element) {\n if (this.mouseDown) {\n this.currentScrubbingImageElement = element;\n } else {\n this.currentThumbnailImageElement = element;\n }\n }\n\n toggleThumbContainer = (toggle = false, clearShowing = false) => {\n const className = this.player.config.classNames.previewThumbnails.thumbContainerShown;\n this.elements.thumb.container.classList.toggle(className, toggle);\n\n if (!toggle && clearShowing) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n };\n\n toggleScrubbingContainer = (toggle = false) => {\n const className = this.player.config.classNames.previewThumbnails.scrubbingContainerShown;\n this.elements.scrubbing.container.classList.toggle(className, toggle);\n\n if (!toggle) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n };\n\n determineContainerAutoSizing = () => {\n if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) {\n // This will prevent auto sizing in this.setThumbContainerSizeAndPos()\n this.sizeSpecifiedInCSS = true;\n }\n };\n\n // 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\n setThumbContainerSizeAndPos = () => {\n if (!this.sizeSpecifiedInCSS) {\n const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${this.thumbContainerHeight}px`;\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (\n this.elements.thumb.imageContainer.clientHeight > 20 &&\n this.elements.thumb.imageContainer.clientWidth < 20\n ) {\n const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (\n this.elements.thumb.imageContainer.clientHeight < 20 &&\n this.elements.thumb.imageContainer.clientWidth > 20\n ) {\n const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`;\n }\n\n this.setThumbContainerPos();\n };\n\n setThumbContainerPos = () => {\n const seekbarRect = this.player.elements.progress.getBoundingClientRect();\n const plyrRect = this.player.elements.container.getBoundingClientRect();\n const { container } = this.elements.thumb;\n // Find the lowest and highest desired left-position, so we don't slide out the side of the video container\n const minVal = plyrRect.left - seekbarRect.left + 10;\n const maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10;\n // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth\n let previewPos = this.mousePosX - seekbarRect.left - container.clientWidth / 2;\n\n if (previewPos < minVal) {\n previewPos = minVal;\n }\n\n if (previewPos > maxVal) {\n previewPos = maxVal;\n }\n\n container.style.left = `${previewPos}px`;\n };\n\n // Can't use 100% width, in case the video is a different aspect ratio to the video container\n setScrubbingContainerSize = () => {\n const { width, height } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight,\n });\n this.elements.scrubbing.container.style.width = `${width}px`;\n this.elements.scrubbing.container.style.height = `${height}px`;\n };\n\n // Sprites need to be offset to the correct location\n setImageSizeAndOffset = (previewImage, frame) => {\n if (!this.usingSprites) {\n return;\n }\n\n // Find difference between height and preview container height\n const multiplier = this.thumbContainerHeight / frame.h;\n\n // eslint-disable-next-line no-param-reassign\n previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.left = `-${frame.x * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.top = `-${frame.y * multiplier}px`;\n };\n}\n\nexport default PreviewThumbnails;\n","// ==========================================================================\n// Plyr source update\n// ==========================================================================\n\nimport { providers } from './config/types';\nimport html5 from './html5';\nimport media from './media';\nimport PreviewThumbnails from './plugins/preview-thumbnails';\nimport support from './support';\nimport ui from './ui';\nimport { createElement, insertElement, removeElement } from './utils/elements';\nimport is from './utils/is';\nimport { getDeep } from './utils/objects';\n\nconst source = {\n // Add elements to HTML5 media (source, tracks, etc)\n insertElements(type, attributes) {\n if (is.string(attributes)) {\n insertElement(type, this.media, {\n src: attributes,\n });\n } else if (is.array(attributes)) {\n attributes.forEach((attribute) => {\n insertElement(type, this.media, attribute);\n });\n }\n },\n\n // Update source\n // Sources are not checked for support so be careful\n change(input) {\n if (!getDeep(input, 'sources.length')) {\n this.debug.warn('Invalid source format');\n return;\n }\n\n // Cancel current network requests\n html5.cancelRequests.call(this);\n\n // Destroy instance and re-setup\n this.destroy.call(\n this,\n () => {\n // Reset quality options\n this.options.quality = [];\n\n // Remove elements\n removeElement(this.media);\n this.media = null;\n\n // Reset class name\n if (is.element(this.elements.container)) {\n this.elements.container.removeAttribute('class');\n }\n\n // Set the type and provider\n const { sources, type } = input;\n const [{ provider = providers.html5, src }] = sources;\n const tagName = provider === 'html5' ? type : 'div';\n const attributes = provider === 'html5' ? {} : { src };\n\n Object.assign(this, {\n provider,\n type,\n // Check for support\n supported: support.check(type, provider, this.config.playsinline),\n // Create new element\n media: createElement(tagName, attributes),\n });\n\n // Inject the new element\n this.elements.container.appendChild(this.media);\n\n // Autoplay the new source?\n if (is.boolean(input.autoplay)) {\n this.config.autoplay = input.autoplay;\n }\n\n // Set attributes for audio and video\n if (this.isHTML5) {\n if (this.config.crossorigin) {\n this.media.setAttribute('crossorigin', '');\n }\n if (this.config.autoplay) {\n this.media.setAttribute('autoplay', '');\n }\n if (!is.empty(input.poster)) {\n this.poster = input.poster;\n }\n if (this.config.loop.active) {\n this.media.setAttribute('loop', '');\n }\n if (this.config.muted) {\n this.media.setAttribute('muted', '');\n }\n if (this.config.playsinline) {\n this.media.setAttribute('playsinline', '');\n }\n }\n\n // Restore class hook\n ui.addStyleHook.call(this);\n\n // Set new sources for html5\n if (this.isHTML5) {\n source.insertElements.call(this, 'source', sources);\n }\n\n // Set video title\n this.config.title = input.title;\n\n // Set up from scratch\n media.setup.call(this);\n\n // HTML5 stuff\n if (this.isHTML5) {\n // Setup captions\n if (Object.keys(input).includes('tracks')) {\n source.insertElements.call(this, 'track', input.tracks);\n }\n }\n\n // If HTML5 or embed but not fully supported, setupInterface and call ready now\n if (this.isHTML5 || (this.isEmbed && !this.supported.ui)) {\n // Setup interface\n ui.build.call(this);\n }\n\n // Load HTML5 sources\n if (this.isHTML5) {\n this.media.load();\n }\n\n // Update previewThumbnails config & reload plugin\n if (!is.empty(input.previewThumbnails)) {\n Object.assign(this.config.previewThumbnails, input.previewThumbnails);\n\n // Cleanup previewThumbnails plugin if it was loaded\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n // Create new instance if it is still enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n // Update the fullscreen support\n this.fullscreen.update();\n },\n true,\n );\n },\n};\n\nexport default source;\n","/**\n * Returns a number whose value is limited to the given range.\n *\n * Example: limit the output of this computation to between 0 and 255\n * (x * 255).clamp(0, 255)\n *\n * @param {Number} input\n * @param {Number} min The lower boundary of the output range\n * @param {Number} max The upper boundary of the output range\n * @returns A number in the range [min, max]\n * @type Number\n */\nexport function clamp(input = 0, min = 0, max = 255) {\n return Math.min(Math.max(input, min), max);\n}\n\nexport default { clamp };\n","// ==========================================================================\n// Plyr\n// plyr.js v3.6.12\n// https://github.com/sampotts/plyr\n// License: The MIT License (MIT)\n// ==========================================================================\n\nimport captions from './captions';\nimport defaults from './config/defaults';\nimport { pip } from './config/states';\nimport { getProviderByUrl, providers, types } from './config/types';\nimport Console from './console';\nimport controls from './controls';\nimport Fullscreen from './fullscreen';\nimport html5 from './html5';\nimport Listeners from './listeners';\nimport media from './media';\nimport Ads from './plugins/ads';\nimport PreviewThumbnails from './plugins/preview-thumbnails';\nimport source from './source';\nimport Storage from './storage';\nimport support from './support';\nimport ui from './ui';\nimport { closest } from './utils/arrays';\nimport { createElement, hasClass, removeElement, replaceElement, toggleClass, wrap } from './utils/elements';\nimport { off, on, once, triggerEvent, unbindListeners } from './utils/events';\nimport is from './utils/is';\nimport loadSprite from './utils/load-sprite';\nimport { clamp } from './utils/numbers';\nimport { cloneDeep, extend } from './utils/objects';\nimport { silencePromise } from './utils/promise';\nimport { getAspectRatio, reduceAspectRatio, setAspectRatio, validateAspectRatio } from './utils/style';\nimport { parseUrl } from './utils/urls';\n\n// Private properties\n// TODO: Use a WeakMap for private globals\n// const globals = new WeakMap();\n\n// Plyr instance\nclass Plyr {\n constructor(target, options) {\n this.timers = {};\n\n // State\n this.ready = false;\n this.loading = false;\n this.failed = false;\n\n // Touch device\n this.touch = support.touch;\n\n // Set the media element\n this.media = target;\n\n // String selector passed\n if (is.string(this.media)) {\n this.media = document.querySelectorAll(this.media);\n }\n\n // jQuery, NodeList or Array passed, use first element\n if ((window.jQuery && this.media instanceof jQuery) || is.nodeList(this.media) || is.array(this.media)) {\n // eslint-disable-next-line\n this.media = this.media[0];\n }\n\n // Set config\n this.config = extend(\n {},\n defaults,\n Plyr.defaults,\n options || {},\n (() => {\n try {\n return JSON.parse(this.media.getAttribute('data-plyr-config'));\n } catch (_) {\n return {};\n }\n })(),\n );\n\n // Elements cache\n this.elements = {\n container: null,\n fullscreen: null,\n captions: null,\n buttons: {},\n display: {},\n progress: {},\n inputs: {},\n settings: {\n popup: null,\n menu: null,\n panels: {},\n buttons: {},\n },\n };\n\n // Captions\n this.captions = {\n active: null,\n currentTrack: -1,\n meta: new WeakMap(),\n };\n\n // Fullscreen\n this.fullscreen = {\n active: false,\n };\n\n // Options\n this.options = {\n speed: [],\n quality: [],\n };\n\n // Debugging\n // TODO: move to globals\n this.debug = new Console(this.config.debug);\n\n // Log config options and support\n this.debug.log('Config', this.config);\n this.debug.log('Support', support);\n\n // We need an element to setup\n if (is.nullOrUndefined(this.media) || !is.element(this.media)) {\n this.debug.error('Setup failed: no suitable element passed');\n return;\n }\n\n // Bail if the element is initialized\n if (this.media.plyr) {\n this.debug.warn('Target already setup');\n return;\n }\n\n // Bail if not enabled\n if (!this.config.enabled) {\n this.debug.error('Setup failed: disabled by config');\n return;\n }\n\n // Bail if disabled or no basic support\n // You may want to disable certain UAs etc\n if (!support.check().api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n // Cache original element state for .destroy()\n const clone = this.media.cloneNode(true);\n clone.autoplay = false;\n this.elements.original = clone;\n\n // Set media type based on tag or data attribute\n // Supported: video, audio, vimeo, youtube\n const type = this.media.tagName.toLowerCase();\n // Embed properties\n let iframe = null;\n let url = null;\n\n // Different setup based on type\n switch (type) {\n case 'div':\n // Find the frame\n iframe = this.media.querySelector('iframe');\n\n // <iframe> type\n if (is.element(iframe)) {\n // Detect provider\n url = parseUrl(iframe.getAttribute('src'));\n this.provider = getProviderByUrl(url.toString());\n\n // Rework elements\n this.elements.container = this.media;\n this.media = iframe;\n\n // Reset classname\n this.elements.container.className = '';\n\n // Get attributes from URL and set config\n if (url.search.length) {\n const truthy = ['1', 'true'];\n\n if (truthy.includes(url.searchParams.get('autoplay'))) {\n this.config.autoplay = true;\n }\n if (truthy.includes(url.searchParams.get('loop'))) {\n this.config.loop.active = true;\n }\n\n // TODO: replace fullscreen.iosNative with this playsinline config option\n // YouTube requires the playsinline in the URL\n if (this.isYouTube) {\n this.config.playsinline = truthy.includes(url.searchParams.get('playsinline'));\n this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language?\n } else {\n this.config.playsinline = true;\n }\n }\n } else {\n // <div> with attributes\n this.provider = this.media.getAttribute(this.config.attributes.embed.provider);\n\n // Remove attribute\n this.media.removeAttribute(this.config.attributes.embed.provider);\n }\n\n // Unsupported or missing provider\n if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) {\n this.debug.error('Setup failed: Invalid provider');\n return;\n }\n\n // Audio will come later for external providers\n this.type = types.video;\n\n break;\n\n case 'video':\n case 'audio':\n this.type = type;\n this.provider = providers.html5;\n\n // Get config from attributes\n if (this.media.hasAttribute('crossorigin')) {\n this.config.crossorigin = true;\n }\n if (this.media.hasAttribute('autoplay')) {\n this.config.autoplay = true;\n }\n if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) {\n this.config.playsinline = true;\n }\n if (this.media.hasAttribute('muted')) {\n this.config.muted = true;\n }\n if (this.media.hasAttribute('loop')) {\n this.config.loop.active = true;\n }\n\n break;\n\n default:\n this.debug.error('Setup failed: unsupported type');\n return;\n }\n\n // Check for support again but with type\n this.supported = support.check(this.type, this.provider, this.config.playsinline);\n\n // If no support for even API, bail\n if (!this.supported.api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n this.eventListeners = [];\n\n // Create listeners\n this.listeners = new Listeners(this);\n\n // Setup local storage for user settings\n this.storage = new Storage(this);\n\n // Store reference\n this.media.plyr = this;\n\n // Wrap media\n if (!is.element(this.elements.container)) {\n this.elements.container = createElement('div', { tabindex: 0 });\n wrap(this.media, this.elements.container);\n }\n\n // Migrate custom properties from media to container (so they work 😉)\n ui.migrateStyles.call(this);\n\n // Add style hook\n ui.addStyleHook.call(this);\n\n // Setup media\n media.setup.call(this);\n\n // Listen for events if debugging\n if (this.config.debug) {\n on.call(this, this.elements.container, this.config.events.join(' '), (event) => {\n this.debug.log(`event: ${event.type}`);\n });\n }\n\n // Setup fullscreen\n this.fullscreen = new Fullscreen(this);\n\n // Setup interface\n // If embed but not fully supported, build interface now to avoid flash of controls\n if (this.isHTML5 || (this.isEmbed && !this.supported.ui)) {\n ui.build.call(this);\n }\n\n // Container listeners\n this.listeners.container();\n\n // Global listeners\n this.listeners.global();\n\n // Setup ads if provided\n if (this.config.ads.enabled) {\n this.ads = new Ads(this);\n }\n\n // Autoplay if required\n if (this.isHTML5 && this.config.autoplay) {\n this.once('canplay', () => silencePromise(this.play()));\n }\n\n // Seek time will be recorded (in listeners.js) so we can prevent hiding controls for a few seconds after seek\n this.lastSeekTime = 0;\n\n // Setup preview thumbnails if enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n // ---------------------------------------\n // API\n // ---------------------------------------\n\n /**\n * Types and provider helpers\n */\n get isHTML5() {\n return this.provider === providers.html5;\n }\n\n get isEmbed() {\n return this.isYouTube || this.isVimeo;\n }\n\n get isYouTube() {\n return this.provider === providers.youtube;\n }\n\n get isVimeo() {\n return this.provider === providers.vimeo;\n }\n\n get isVideo() {\n return this.type === types.video;\n }\n\n get isAudio() {\n return this.type === types.audio;\n }\n\n /**\n * Play the media, or play the advertisement (if they are not blocked)\n */\n play = () => {\n if (!is.function(this.media.play)) {\n return null;\n }\n\n // Intecept play with ads\n if (this.ads && this.ads.enabled) {\n this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play()));\n }\n\n // Return the promise (for HTML5)\n return this.media.play();\n };\n\n /**\n * Pause the media\n */\n pause = () => {\n if (!this.playing || !is.function(this.media.pause)) {\n return null;\n }\n\n return this.media.pause();\n };\n\n /**\n * Get playing state\n */\n get playing() {\n return Boolean(this.ready && !this.paused && !this.ended);\n }\n\n /**\n * Get paused state\n */\n get paused() {\n return Boolean(this.media.paused);\n }\n\n /**\n * Get stopped state\n */\n get stopped() {\n return Boolean(this.paused && this.currentTime === 0);\n }\n\n /**\n * Get ended state\n */\n get ended() {\n return Boolean(this.media.ended);\n }\n\n /**\n * Toggle playback based on current status\n * @param {Boolean} input\n */\n togglePlay = (input) => {\n // Toggle based on current state if nothing passed\n const toggle = is.boolean(input) ? input : !this.playing;\n\n if (toggle) {\n return this.play();\n }\n\n return this.pause();\n };\n\n /**\n * Stop playback\n */\n stop = () => {\n if (this.isHTML5) {\n this.pause();\n this.restart();\n } else if (is.function(this.media.stop)) {\n this.media.stop();\n }\n };\n\n /**\n * Restart playback\n */\n restart = () => {\n this.currentTime = 0;\n };\n\n /**\n * Rewind\n * @param {Number} seekTime - how far to rewind in seconds. Defaults to the config.seekTime\n */\n rewind = (seekTime) => {\n this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime;\n };\n\n /**\n * Fast forward\n * @param {Number} seekTime - how far to fast forward in seconds. Defaults to the config.seekTime\n */\n forward = (seekTime) => {\n this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime;\n };\n\n /**\n * Seek to a time\n * @param {Number} input - where to seek to in seconds. Defaults to 0 (the start)\n */\n set currentTime(input) {\n // Bail if media duration isn't available yet\n if (!this.duration) {\n return;\n }\n\n // Validate input\n const inputIsValid = is.number(input) && input > 0;\n\n // Set\n this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0;\n\n // Logging\n this.debug.log(`Seeking to ${this.currentTime} seconds`);\n }\n\n /**\n * Get current time\n */\n get currentTime() {\n return Number(this.media.currentTime);\n }\n\n /**\n * Get buffered\n */\n get buffered() {\n const { buffered } = this.media;\n\n // YouTube / Vimeo return a float between 0-1\n if (is.number(buffered)) {\n return buffered;\n }\n\n // HTML5\n // TODO: Handle buffered chunks of the media\n // (i.e. seek to another section buffers only that section)\n if (buffered && buffered.length && this.duration > 0) {\n return buffered.end(0) / this.duration;\n }\n\n return 0;\n }\n\n /**\n * Get seeking status\n */\n get seeking() {\n return Boolean(this.media.seeking);\n }\n\n /**\n * Get the duration of the current media\n */\n get duration() {\n // Faux duration set via config\n const fauxDuration = parseFloat(this.config.duration);\n // Media duration can be NaN or Infinity before the media has loaded\n const realDuration = (this.media || {}).duration;\n const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration;\n\n // If config duration is funky, use regular duration\n return fauxDuration || duration;\n }\n\n /**\n * Set the player volume\n * @param {Number} value - must be between 0 and 1. Defaults to the value from local storage and config.volume if not set in storage\n */\n set volume(value) {\n let volume = value;\n const max = 1;\n const min = 0;\n\n if (is.string(volume)) {\n volume = Number(volume);\n }\n\n // Load volume from storage if no value specified\n if (!is.number(volume)) {\n volume = this.storage.get('volume');\n }\n\n // Use config if all else fails\n if (!is.number(volume)) {\n ({ volume } = this.config);\n }\n\n // Maximum is volumeMax\n if (volume > max) {\n volume = max;\n }\n // Minimum is volumeMin\n if (volume < min) {\n volume = min;\n }\n\n // Update config\n this.config.volume = volume;\n\n // Set the player volume\n this.media.volume = volume;\n\n // If muted, and we're increasing volume manually, reset muted state\n if (!is.empty(value) && this.muted && volume > 0) {\n this.muted = false;\n }\n }\n\n /**\n * Get the current player volume\n */\n get volume() {\n return Number(this.media.volume);\n }\n\n /**\n * Increase volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n increaseVolume = (step) => {\n const volume = this.media.muted ? 0 : this.volume;\n this.volume = volume + (is.number(step) ? step : 0);\n };\n\n /**\n * Decrease volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n decreaseVolume = (step) => {\n this.increaseVolume(-step);\n };\n\n /**\n * Set muted state\n * @param {Boolean} mute\n */\n set muted(mute) {\n let toggle = mute;\n\n // Load muted state from storage\n if (!is.boolean(toggle)) {\n toggle = this.storage.get('muted');\n }\n\n // Use config if all else fails\n if (!is.boolean(toggle)) {\n toggle = this.config.muted;\n }\n\n // Update config\n this.config.muted = toggle;\n\n // Set mute on the player\n this.media.muted = toggle;\n }\n\n /**\n * Get current muted state\n */\n get muted() {\n return Boolean(this.media.muted);\n }\n\n /**\n * Check if the media has audio\n */\n get hasAudio() {\n // Assume yes for all non HTML5 (as we can't tell...)\n if (!this.isHTML5) {\n return true;\n }\n\n if (this.isAudio) {\n return true;\n }\n\n // Get audio tracks\n return (\n Boolean(this.media.mozHasAudio) ||\n Boolean(this.media.webkitAudioDecodedByteCount) ||\n Boolean(this.media.audioTracks && this.media.audioTracks.length)\n );\n }\n\n /**\n * Set playback speed\n * @param {Number} speed - the speed of playback (0.5-2.0)\n */\n set speed(input) {\n let speed = null;\n\n if (is.number(input)) {\n speed = input;\n }\n\n if (!is.number(speed)) {\n speed = this.storage.get('speed');\n }\n\n if (!is.number(speed)) {\n speed = this.config.speed.selected;\n }\n\n // Clamp to min/max\n const { minimumSpeed: min, maximumSpeed: max } = this;\n speed = clamp(speed, min, max);\n\n // Update config\n this.config.speed.selected = speed;\n\n // Set media speed\n setTimeout(() => {\n if (this.media) {\n this.media.playbackRate = speed;\n }\n }, 0);\n }\n\n /**\n * Get current playback speed\n */\n get speed() {\n return Number(this.media.playbackRate);\n }\n\n /**\n * Get the minimum allowed speed\n */\n get minimumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.min(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 0.5;\n }\n\n // https://stackoverflow.com/a/32320020/1191319\n return 0.0625;\n }\n\n /**\n * Get the maximum allowed speed\n */\n get maximumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.max(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 2;\n }\n\n // https://stackoverflow.com/a/32320020/1191319\n return 16;\n }\n\n /**\n * Set playback quality\n * Currently HTML5 & YouTube only\n * @param {Number} input - Quality level\n */\n set quality(input) {\n const config = this.config.quality;\n const options = this.options.quality;\n\n if (!options.length) {\n return;\n }\n\n let quality = [\n !is.empty(input) && Number(input),\n this.storage.get('quality'),\n config.selected,\n config.default,\n ].find(is.number);\n\n let updateStorage = true;\n\n if (!options.includes(quality)) {\n const value = closest(options, quality);\n this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`);\n quality = value;\n\n // Don't update storage if quality is not supported\n updateStorage = false;\n }\n\n // Update config\n config.selected = quality;\n\n // Set quality\n this.media.quality = quality;\n\n // Save to storage\n if (updateStorage) {\n this.storage.set({ quality });\n }\n }\n\n /**\n * Get current quality level\n */\n get quality() {\n return this.media.quality;\n }\n\n /**\n * Toggle loop\n * TODO: Finish fancy new logic. Set the indicator on load as user may pass loop as config\n * @param {Boolean} input - Whether to loop or not\n */\n set loop(input) {\n const toggle = is.boolean(input) ? input : this.config.loop.active;\n this.config.loop.active = toggle;\n this.media.loop = toggle;\n\n // Set default to be a true toggle\n /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle';\n\n switch (type) {\n case 'start':\n if (this.config.loop.end && this.config.loop.end <= this.currentTime) {\n this.config.loop.end = null;\n }\n this.config.loop.start = this.currentTime;\n // this.config.loop.indicator.start = this.elements.display.played.value;\n break;\n\n case 'end':\n if (this.config.loop.start >= this.currentTime) {\n return this;\n }\n this.config.loop.end = this.currentTime;\n // this.config.loop.indicator.end = this.elements.display.played.value;\n break;\n\n case 'all':\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n this.config.loop.indicator.start = 0;\n this.config.loop.indicator.end = 100;\n break;\n\n case 'toggle':\n if (this.config.loop.active) {\n this.config.loop.start = 0;\n this.config.loop.end = null;\n } else {\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n }\n break;\n\n default:\n this.config.loop.start = 0;\n this.config.loop.end = null;\n break;\n } */\n }\n\n /**\n * Get current loop state\n */\n get loop() {\n return Boolean(this.media.loop);\n }\n\n /**\n * Set new media source\n * @param {Object} input - The new source object (see docs)\n */\n set source(input) {\n source.change.call(this, input);\n }\n\n /**\n * Get current source\n */\n get source() {\n return this.media.currentSrc;\n }\n\n /**\n * Get a download URL (either source or custom)\n */\n get download() {\n const { download } = this.config.urls;\n\n return is.url(download) ? download : this.source;\n }\n\n /**\n * Set the download URL\n */\n set download(input) {\n if (!is.url(input)) {\n return;\n }\n\n this.config.urls.download = input;\n\n controls.setDownloadUrl.call(this);\n }\n\n /**\n * Set the poster image for a video\n * @param {String} input - the URL for the new poster image\n */\n set poster(input) {\n if (!this.isVideo) {\n this.debug.warn('Poster can only be set for video');\n return;\n }\n\n ui.setPoster.call(this, input, false).catch(() => {});\n }\n\n /**\n * Get the current poster image\n */\n get poster() {\n if (!this.isVideo) {\n return null;\n }\n\n return this.media.getAttribute('poster') || this.media.getAttribute('data-poster');\n }\n\n /**\n * Get the current aspect ratio in use\n */\n get ratio() {\n if (!this.isVideo) {\n return null;\n }\n\n const ratio = reduceAspectRatio(getAspectRatio.call(this));\n\n return is.array(ratio) ? ratio.join(':') : ratio;\n }\n\n /**\n * Set video aspect ratio\n */\n set ratio(input) {\n if (!this.isVideo) {\n this.debug.warn('Aspect ratio can only be set for video');\n return;\n }\n\n if (!is.string(input) || !validateAspectRatio(input)) {\n this.debug.error(`Invalid aspect ratio specified (${input})`);\n return;\n }\n\n this.config.ratio = reduceAspectRatio(input);\n\n setAspectRatio.call(this);\n }\n\n /**\n * Set the autoplay state\n * @param {Boolean} input - Whether to autoplay or not\n */\n set autoplay(input) {\n const toggle = is.boolean(input) ? input : this.config.autoplay;\n this.config.autoplay = toggle;\n }\n\n /**\n * Get the current autoplay state\n */\n get autoplay() {\n return Boolean(this.config.autoplay);\n }\n\n /**\n * Toggle captions\n * @param {Boolean} input - Whether to enable captions\n */\n toggleCaptions(input) {\n captions.toggle.call(this, input, false);\n }\n\n /**\n * Set the caption track by index\n * @param {Number} - Caption index\n */\n set currentTrack(input) {\n captions.set.call(this, input, false);\n captions.setup();\n }\n\n /**\n * Get the current caption track index (-1 if disabled)\n */\n get currentTrack() {\n const { toggled, currentTrack } = this.captions;\n return toggled ? currentTrack : -1;\n }\n\n /**\n * Set the wanted language for captions\n * Since tracks can be added later it won't update the actual caption track until there is a matching track\n * @param {String} - Two character ISO language code (e.g. EN, FR, PT, etc)\n */\n set language(input) {\n captions.setLanguage.call(this, input, false);\n }\n\n /**\n * Get the current track's language\n */\n get language() {\n return (captions.getCurrentTrack.call(this) || {}).language;\n }\n\n /**\n * Toggle picture-in-picture playback on WebKit/MacOS\n * TODO: update player with state, support, enabled\n * TODO: detect outside changes\n */\n set pip(input) {\n // Bail if no support\n if (!support.pip) {\n return;\n }\n\n // Toggle based on current state if not passed\n const toggle = is.boolean(input) ? input : !this.pip;\n\n // Toggle based on current state\n // Safari\n if (is.function(this.media.webkitSetPresentationMode)) {\n this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive);\n }\n\n // Chrome\n if (is.function(this.media.requestPictureInPicture)) {\n if (!this.pip && toggle) {\n this.media.requestPictureInPicture();\n } else if (this.pip && !toggle) {\n document.exitPictureInPicture();\n }\n }\n }\n\n /**\n * Get the current picture-in-picture state\n */\n get pip() {\n if (!support.pip) {\n return null;\n }\n\n // Safari\n if (!is.empty(this.media.webkitPresentationMode)) {\n return this.media.webkitPresentationMode === pip.active;\n }\n\n // Chrome\n return this.media === document.pictureInPictureElement;\n }\n\n /**\n * Sets the preview thubmnails for the current source\n */\n setPreviewThumbnails(thumbnailSource) {\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n Object.assign(this.config.previewThumbnails, thumbnailSource);\n\n // Create new instance if it is still enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n /**\n * Trigger the airplay dialog\n * TODO: update player with state, support, enabled\n */\n airplay = () => {\n // Show dialog if supported\n if (support.airplay) {\n this.media.webkitShowPlaybackTargetPicker();\n }\n };\n\n /**\n * Toggle the player controls\n * @param {Boolean} [toggle] - Whether to show the controls\n */\n toggleControls = (toggle) => {\n // Don't toggle if missing UI support or if it's audio\n if (this.supported.ui && !this.isAudio) {\n // Get state before change\n const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls);\n // Negate the argument if not undefined since adding the class to hides the controls\n const force = typeof toggle === 'undefined' ? undefined : !toggle;\n // Apply and get updated state\n const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force);\n\n // Close menu\n if (\n hiding &&\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n !is.empty(this.config.settings)\n ) {\n controls.toggleMenu.call(this, false);\n }\n\n // Trigger event on change\n if (hiding !== isHidden) {\n const eventName = hiding ? 'controlshidden' : 'controlsshown';\n triggerEvent.call(this, this.media, eventName);\n }\n\n return !hiding;\n }\n\n return false;\n };\n\n /**\n * Add event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n on = (event, callback) => {\n on.call(this, this.elements.container, event, callback);\n };\n\n /**\n * Add event listeners once\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n once = (event, callback) => {\n once.call(this, this.elements.container, event, callback);\n };\n\n /**\n * Remove event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n off = (event, callback) => {\n off(this.elements.container, event, callback);\n };\n\n /**\n * Destroy an instance\n * Event listeners are removed when elements are removed\n * http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory\n * @param {Function} callback - Callback for when destroy is complete\n * @param {Boolean} soft - Whether it's a soft destroy (for source changes etc)\n */\n destroy = (callback, soft = false) => {\n if (!this.ready) {\n return;\n }\n\n const done = () => {\n // Reset overflow (incase destroyed while in fullscreen)\n document.body.style.overflow = '';\n\n // GC for embed\n this.embed = null;\n\n // If it's a soft destroy, make minimal changes\n if (soft) {\n if (Object.keys(this.elements).length) {\n // Remove elements\n removeElement(this.elements.buttons.play);\n removeElement(this.elements.captions);\n removeElement(this.elements.controls);\n removeElement(this.elements.wrapper);\n\n // Clear for GC\n this.elements.buttons.play = null;\n this.elements.captions = null;\n this.elements.controls = null;\n this.elements.wrapper = null;\n }\n\n // Callback\n if (is.function(callback)) {\n callback();\n }\n } else {\n // Unbind listeners\n unbindListeners.call(this);\n\n // Cancel current network requests\n html5.cancelRequests.call(this);\n\n // Replace the container with the original element provided\n replaceElement(this.elements.original, this.elements.container);\n\n // Event\n triggerEvent.call(this, this.elements.original, 'destroyed', true);\n\n // Callback\n if (is.function(callback)) {\n callback.call(this.elements.original);\n }\n\n // Reset state\n this.ready = false;\n\n // Clear for garbage collection\n setTimeout(() => {\n this.elements = null;\n this.media = null;\n }, 200);\n }\n };\n\n // Stop playback\n this.stop();\n\n // Clear timeouts\n clearTimeout(this.timers.loading);\n clearTimeout(this.timers.controls);\n clearTimeout(this.timers.resized);\n\n // Provider specific stuff\n if (this.isHTML5) {\n // Restore native video controls\n ui.toggleNativeControls.call(this, true);\n\n // Clean up\n done();\n } else if (this.isYouTube) {\n // Clear timers\n clearInterval(this.timers.buffering);\n clearInterval(this.timers.playing);\n\n // Destroy YouTube API\n if (this.embed !== null && is.function(this.embed.destroy)) {\n this.embed.destroy();\n }\n\n // Clean up\n done();\n } else if (this.isVimeo) {\n // Destroy Vimeo API\n // then clean up (wait, to prevent postmessage errors)\n if (this.embed !== null) {\n this.embed.unload().then(done);\n }\n\n // Vimeo does not always return\n setTimeout(done, 200);\n }\n };\n\n /**\n * Check for support for a mime type (HTML5 only)\n * @param {String} type - Mime type\n */\n supports = (type) => support.mime.call(this, type);\n\n /**\n * Check for support\n * @param {String} type - Player type (audio/video)\n * @param {String} provider - Provider (html5/youtube/vimeo)\n * @param {Boolean} inline - Where player has `playsinline` sttribute\n */\n static supported(type, provider, inline) {\n return support.check(type, provider, inline);\n }\n\n /**\n * Load an SVG sprite into the page\n * @param {String} url - URL for the SVG sprite\n * @param {String} [id] - Unique ID\n */\n static loadSprite(url, id) {\n return loadSprite(url, id);\n }\n\n /**\n * Setup multiple instances\n * @param {*} selector\n * @param {Object} options\n */\n static setup(selector, options = {}) {\n let targets = null;\n\n if (is.string(selector)) {\n targets = Array.from(document.querySelectorAll(selector));\n } else if (is.nodeList(selector)) {\n targets = Array.from(selector);\n } else if (is.array(selector)) {\n targets = selector.filter(is.element);\n }\n\n if (is.empty(targets)) {\n return null;\n }\n\n return targets.map((t) => new Plyr(t, options));\n }\n}\n\nPlyr.defaults = cloneDeep(defaults);\n\nexport default Plyr;\n"]}
\ No newline at end of file diff --git a/extlib/plyr/plyr.mjs b/extlib/plyr/plyr.mjs new file mode 100644 index 00000000..2fd40af5 --- /dev/null +++ b/extlib/plyr/plyr.mjs @@ -0,0 +1,8670 @@ +function _defineProperty$1(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +function _classCallCheck(e, t) { + if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function"); +} + +function _defineProperties(e, t) { + for (var n = 0; n < t.length; n++) { + var r = t[n]; + r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r); + } +} + +function _createClass(e, t, n) { + return t && _defineProperties(e.prototype, t), n && _defineProperties(e, n), e; +} + +function _defineProperty(e, t, n) { + return t in e ? Object.defineProperty(e, t, { + value: n, + enumerable: !0, + configurable: !0, + writable: !0 + }) : e[t] = n, e; +} + +function ownKeys(e, t) { + var n = Object.keys(e); + + if (Object.getOwnPropertySymbols) { + var r = Object.getOwnPropertySymbols(e); + t && (r = r.filter(function (t) { + return Object.getOwnPropertyDescriptor(e, t).enumerable; + })), n.push.apply(n, r); + } + + return n; +} + +function _objectSpread2(e) { + for (var t = 1; t < arguments.length; t++) { + var n = null != arguments[t] ? arguments[t] : {}; + t % 2 ? ownKeys(Object(n), !0).forEach(function (t) { + _defineProperty(e, t, n[t]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : ownKeys(Object(n)).forEach(function (t) { + Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)); + }); + } + + return e; +} + +var defaults$1 = { + addCSS: !0, + thumbWidth: 15, + watch: !0 +}; + +function matches$1(e, t) { + return function () { + return Array.from(document.querySelectorAll(t)).includes(this); + }.call(e, t); +} + +function trigger(e, t) { + if (e && t) { + var n = new Event(t, { + bubbles: !0 + }); + e.dispatchEvent(n); + } +} + +var getConstructor$1 = function (e) { + return null != e ? e.constructor : null; +}, + instanceOf$1 = function (e, t) { + return !!(e && t && e instanceof t); +}, + isNullOrUndefined$1 = function (e) { + return null == e; +}, + isObject$1 = function (e) { + return getConstructor$1(e) === Object; +}, + isNumber$1 = function (e) { + return getConstructor$1(e) === Number && !Number.isNaN(e); +}, + isString$1 = function (e) { + return getConstructor$1(e) === String; +}, + isBoolean$1 = function (e) { + return getConstructor$1(e) === Boolean; +}, + isFunction$1 = function (e) { + return getConstructor$1(e) === Function; +}, + isArray$1 = function (e) { + return Array.isArray(e); +}, + isNodeList$1 = function (e) { + return instanceOf$1(e, NodeList); +}, + isElement$1 = function (e) { + return instanceOf$1(e, Element); +}, + isEvent$1 = function (e) { + return instanceOf$1(e, Event); +}, + isEmpty$1 = function (e) { + return isNullOrUndefined$1(e) || (isString$1(e) || isArray$1(e) || isNodeList$1(e)) && !e.length || isObject$1(e) && !Object.keys(e).length; +}, + is$1 = { + nullOrUndefined: isNullOrUndefined$1, + object: isObject$1, + number: isNumber$1, + string: isString$1, + boolean: isBoolean$1, + function: isFunction$1, + array: isArray$1, + nodeList: isNodeList$1, + element: isElement$1, + event: isEvent$1, + empty: isEmpty$1 +}; + +function getDecimalPlaces(e) { + var t = "".concat(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); + return t ? Math.max(0, (t[1] ? t[1].length : 0) - (t[2] ? +t[2] : 0)) : 0; +} + +function round(e, t) { + if (1 > t) { + var n = getDecimalPlaces(t); + return parseFloat(e.toFixed(n)); + } + + return Math.round(e / t) * t; +} + +var RangeTouch = function () { + function e(t, n) { + _classCallCheck(this, e), is$1.element(t) ? this.element = t : is$1.string(t) && (this.element = document.querySelector(t)), is$1.element(this.element) && is$1.empty(this.element.rangeTouch) && (this.config = _objectSpread2({}, defaults$1, {}, n), this.init()); + } + + return _createClass(e, [{ + key: "init", + value: function () { + e.enabled && (this.config.addCSS && (this.element.style.userSelect = "none", this.element.style.webKitUserSelect = "none", this.element.style.touchAction = "manipulation"), this.listeners(!0), this.element.rangeTouch = this); + } + }, { + key: "destroy", + value: function () { + e.enabled && (this.config.addCSS && (this.element.style.userSelect = "", this.element.style.webKitUserSelect = "", this.element.style.touchAction = ""), this.listeners(!1), this.element.rangeTouch = null); + } + }, { + key: "listeners", + value: function (e) { + var t = this, + n = e ? "addEventListener" : "removeEventListener"; + ["touchstart", "touchmove", "touchend"].forEach(function (e) { + t.element[n](e, function (e) { + return t.set(e); + }, !1); + }); + } + }, { + key: "get", + value: function (t) { + if (!e.enabled || !is$1.event(t)) return null; + var n, + r = t.target, + i = t.changedTouches[0], + o = parseFloat(r.getAttribute("min")) || 0, + s = parseFloat(r.getAttribute("max")) || 100, + u = parseFloat(r.getAttribute("step")) || 1, + c = r.getBoundingClientRect(), + a = 100 / c.width * (this.config.thumbWidth / 2) / 100; + return 0 > (n = 100 / c.width * (i.clientX - c.left)) ? n = 0 : 100 < n && (n = 100), 50 > n ? n -= (100 - 2 * n) * a : 50 < n && (n += 2 * (n - 50) * a), o + round(n / 100 * (s - o), u); + } + }, { + key: "set", + value: function (t) { + e.enabled && is$1.event(t) && !t.target.disabled && (t.preventDefault(), t.target.value = this.get(t), trigger(t.target, "touchend" === t.type ? "change" : "input")); + } + }], [{ + key: "setup", + value: function (t) { + var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}, + r = null; + if (is$1.empty(t) || is$1.string(t) ? r = Array.from(document.querySelectorAll(is$1.string(t) ? t : 'input[type="range"]')) : is$1.element(t) ? r = [t] : is$1.nodeList(t) ? r = Array.from(t) : is$1.array(t) && (r = t.filter(is$1.element)), is$1.empty(r)) return null; + + var i = _objectSpread2({}, defaults$1, {}, n); + + if (is$1.string(t) && i.watch) { + var o = new MutationObserver(function (n) { + Array.from(n).forEach(function (n) { + Array.from(n.addedNodes).forEach(function (n) { + is$1.element(n) && matches$1(n, t) && new e(n, i); + }); + }); + }); + o.observe(document.body, { + childList: !0, + subtree: !0 + }); + } + + return r.map(function (t) { + return new e(t, n); + }); + } + }, { + key: "enabled", + get: function () { + return "ontouchstart" in document.documentElement; + } + }]), e; +}(); + +// ========================================================================== +// Type checking utils +// ========================================================================== +const getConstructor = input => input !== null && typeof input !== 'undefined' ? input.constructor : null; + +const instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor); + +const isNullOrUndefined = input => input === null || typeof input === 'undefined'; + +const isObject = input => getConstructor(input) === Object; + +const isNumber = input => getConstructor(input) === Number && !Number.isNaN(input); + +const isString = input => getConstructor(input) === String; + +const isBoolean = input => getConstructor(input) === Boolean; + +const isFunction = input => getConstructor(input) === Function; + +const isArray = input => Array.isArray(input); + +const isWeakMap = input => instanceOf(input, WeakMap); + +const isNodeList = input => instanceOf(input, NodeList); + +const isTextNode = input => getConstructor(input) === Text; + +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) && isFunction(input.then); + +const isElement = input => input !== null && typeof input === 'object' && input.nodeType === 1 && typeof input.style === 'object' && typeof input.ownerDocument === 'object'; + +const isEmpty = input => isNullOrUndefined(input) || (isString(input) || isArray(input) || isNodeList(input)) && !input.length || isObject(input) && !Object.keys(input).length; + +const isUrl = input => { + // Accept a URL object + if (instanceOf(input, window.URL)) { + return true; + } // Must be string from here + + + if (!isString(input)) { + return false; + } // Add the protocol if required + + + let string = input; + + if (!input.startsWith('http://') || !input.startsWith('https://')) { + string = `http://${input}`; + } + + try { + return !isEmpty(new URL(string).hostname); + } catch (_) { + return false; + } +}; + +var is = { + nullOrUndefined: isNullOrUndefined, + object: isObject, + number: isNumber, + string: isString, + boolean: isBoolean, + function: isFunction, + array: isArray, + weakMap: isWeakMap, + nodeList: isNodeList, + element: isElement, + textNode: isTextNode, + event: isEvent, + keyboardEvent: isKeyboardEvent, + cue: isCue, + track: isTrack, + promise: isPromise, + url: isUrl, + empty: isEmpty +}; + +// ========================================================================== +const transitionEndEvent = (() => { + const element = document.createElement('span'); + const events = { + WebkitTransition: 'webkitTransitionEnd', + MozTransition: 'transitionend', + OTransition: 'oTransitionEnd otransitionend', + transition: 'transitionend' + }; + const type = Object.keys(events).find(event => element.style[event] !== undefined); + return is.string(type) ? events[type] : false; +})(); // Force repaint of element + +function repaint(element, delay) { + setTimeout(() => { + try { + // eslint-disable-next-line no-param-reassign + element.hidden = true; // eslint-disable-next-line no-unused-expressions + + element.offsetHeight; // eslint-disable-next-line no-param-reassign + + element.hidden = false; + } catch (_) {// Do nothing + } + }, delay); +} + +// ========================================================================== +// Browser sniffing +// Unfortunately, due to mixed support, UA sniffing is required +// ========================================================================== +const browser = { + isIE: Boolean(window.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: navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 || /(iPad|iPhone|iPod)/gi.test(navigator.platform) +}; + +// ========================================================================== + +function cloneDeep(object) { + return JSON.parse(JSON.stringify(object)); +} // Get a nested value in an object + +function getDeep(object, path) { + return path.split('.').reduce((obj, key) => obj && obj[key], object); +} // Deep extend destination object with N more objects + +function extend(target = {}, ...sources) { + if (!sources.length) { + return target; + } + + const source = sources.shift(); + + if (!is.object(source)) { + return target; + } + + Object.keys(source).forEach(key => { + if (is.object(source[key])) { + if (!Object.keys(target).includes(key)) { + Object.assign(target, { + [key]: {} + }); + } + + extend(target[key], source[key]); + } else { + Object.assign(target, { + [key]: source[key] + }); + } + }); + return extend(target, ...sources); +} + +// ========================================================================== + +function wrap(elements, wrapper) { + // Convert `elements` to an array, if necessary. + const targets = elements.length ? elements : [elements]; // Loops backwards to prevent having to clone the wrapper on the + // first element (see `child` below). + + Array.from(targets).reverse().forEach((element, index) => { + const child = index > 0 ? wrapper.cloneNode(true) : wrapper; // Cache the current parent and sibling. + + const parent = element.parentNode; + const sibling = element.nextSibling; // Wrap the element (is automatically removed from its current + // parent). + + child.appendChild(element); // If the element had a sibling, insert the wrapper before + // the sibling to maintain the HTML structure; otherwise, just + // append it to the parent. + + if (sibling) { + parent.insertBefore(child, sibling); + } else { + parent.appendChild(child); + } + }); +} // Set attributes + +function setAttributes(element, attributes) { + if (!is.element(element) || is.empty(attributes)) { + return; + } // Assume null and undefined attributes should be left out, + // Setting them would otherwise convert them to "null" and "undefined" + + + Object.entries(attributes).filter(([, value]) => !is.nullOrUndefined(value)).forEach(([key, value]) => element.setAttribute(key, value)); +} // Create a DocumentFragment + +function createElement(type, attributes, text) { + // Create a new <element> + const element = document.createElement(type); // Set all passed attributes + + if (is.object(attributes)) { + setAttributes(element, attributes); + } // Add text node + + + if (is.string(text)) { + element.innerText = text; + } // Return built element + + + return element; +} // Inaert an element after another + +function insertAfter(element, target) { + if (!is.element(element) || !is.element(target)) { + return; + } + + target.parentNode.insertBefore(element, target.nextSibling); +} // Insert a DocumentFragment + +function insertElement(type, parent, attributes, text) { + if (!is.element(parent)) { + return; + } + + parent.appendChild(createElement(type, attributes, text)); +} // Remove element(s) + +function removeElement(element) { + if (is.nodeList(element) || is.array(element)) { + Array.from(element).forEach(removeElement); + return; + } + + if (!is.element(element) || !is.element(element.parentNode)) { + return; + } + + element.parentNode.removeChild(element); +} // Remove all child elements + +function emptyElement(element) { + if (!is.element(element)) { + return; + } + + let { + length + } = element.childNodes; + + while (length > 0) { + element.removeChild(element.lastChild); + length -= 1; + } +} // Replace element + +function replaceElement(newChild, oldChild) { + if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) { + return null; + } + + oldChild.parentNode.replaceChild(newChild, oldChild); + return newChild; +} // Get an attribute object from a string selector + +function getAttributesFromSelector(sel, existingAttributes) { + // For example: + // '.test' to { class: 'test' } + // '#test' to { id: 'test' } + // '[data-test="test"]' to { 'data-test': 'test' } + if (!is.string(sel) || is.empty(sel)) { + return {}; + } + + const attributes = {}; + const existing = extend({}, existingAttributes); + sel.split(',').forEach(s => { + // Remove whitespace + const selector = s.trim(); + const className = selector.replace('.', ''); + const stripped = selector.replace(/[[\]]/g, ''); // Get the parts and value + + const parts = stripped.split('='); + const [key] = parts; + const value = parts.length > 1 ? parts[1].replace(/["']/g, '') : ''; // Get the first character + + const start = selector.charAt(0); + + switch (start) { + case '.': + // Add to existing classname + if (is.string(existing.class)) { + attributes.class = `${existing.class} ${className}`; + } else { + attributes.class = className; + } + + break; + + case '#': + // ID selector + attributes.id = selector.replace('#', ''); + break; + + case '[': + // Attribute selector + attributes[key] = value; + break; + } + }); + return extend(existing, attributes); +} // Toggle hidden + +function toggleHidden(element, hidden) { + if (!is.element(element)) { + return; + } + + let hide = hidden; + + if (!is.boolean(hide)) { + hide = !element.hidden; + } // eslint-disable-next-line no-param-reassign + + + element.hidden = hide; +} // Mirror Element.classList.toggle, with IE compatibility for "force" argument + +function toggleClass(element, className, force) { + if (is.nodeList(element)) { + return Array.from(element).map(e => toggleClass(e, className, force)); + } + + if (is.element(element)) { + let method = 'toggle'; + + if (typeof force !== 'undefined') { + method = force ? 'add' : 'remove'; + } + + element.classList[method](className); + return element.classList.contains(className); + } + + return false; +} // Has class name + +function hasClass(element, className) { + return is.element(element) && element.classList.contains(className); +} // Element matches selector + +function matches(element, selector) { + const { + prototype + } = Element; + + function match() { + return Array.from(document.querySelectorAll(selector)).includes(this); + } + + const method = prototype.matches || prototype.webkitMatchesSelector || prototype.mozMatchesSelector || prototype.msMatchesSelector || match; + return method.call(element, selector); +} // Closest ancestor element matching selector (also tests element itself) + +function closest$1(element, selector) { + const { + prototype + } = Element; // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill + + function closestElement() { + let el = this; + + do { + if (matches.matches(el, selector)) return el; + el = el.parentElement || el.parentNode; + } while (el !== null && el.nodeType === 1); + + return null; + } + + const method = prototype.closest || closestElement; + return method.call(element, selector); +} // Find all elements + +function getElements(selector) { + return this.elements.container.querySelectorAll(selector); +} // Find a single element + +function getElement(selector) { + return this.elements.container.querySelector(selector); +} // Set focus and tab focus class + +function setFocus(element = null, tabFocus = false) { + if (!is.element(element)) { + return; + } // Set regular focus + + + element.focus({ + preventScroll: true + }); // If we want to mimic keyboard focus via tab + + if (tabFocus) { + toggleClass(element, this.config.classNames.tabFocus); + } +} + +// ========================================================================== + +const defaultCodecs = { + 'audio/ogg': 'vorbis', + 'audio/wav': '1', + 'video/webm': 'vp8, vorbis', + 'video/mp4': 'avc1.42E01E, mp4a.40.2', + 'video/ogg': 'theora' +}; // Check for feature support + +const support = { + // Basic support + audio: 'canPlayType' in document.createElement('audio'), + video: 'canPlayType' in document.createElement('video'), + + // Check for support + // Basic functionality vs full UI + check(type, provider, playsinline) { + const canPlayInline = browser.isIPhone && playsinline && support.playsinline; + const api = support[type] || provider !== 'html5'; + const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline); + return { + api, + ui + }; + }, + + // Picture-in-picture support + // Safari & Chrome only currently + pip: (() => { + if (browser.isIPhone) { + return false; + } // Safari + // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls + + + if (is.function(createElement('video').webkitSetPresentationMode)) { + return true; + } // Chrome + // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture + + + if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) { + return true; + } + + return false; + })(), + // Airplay support + // Safari only currently + airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent), + // Inline playback support + // https://webkit.org/blog/6784/new-video-policies-for-ios/ + playsinline: 'playsInline' in document.createElement('video'), + + // Check for mime type support against a player instance + // Credits: http://diveintohtml5.info/everything.html + // Related: http://www.leanbackplayer.com/test/h5mt.html + 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) { + return false; + } // Add codec if required + + + if (Object.keys(defaultCodecs).includes(type)) { + type += `; codecs="${defaultCodecs[input]}"`; + } + + try { + return Boolean(type && this.media.canPlayType(type).replace(/no/, '')); + } catch (_) { + return false; + } + }, + + // Check for textTracks support + textTracks: 'textTracks' in document.createElement('video'), + // <input type="range"> Sliders + rangeInput: (() => { + const range = document.createElement('input'); + range.type = 'range'; + return range.type === 'range'; + })(), + // Touch + // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event + touch: 'ontouchstart' in document.documentElement, + // Detect transitions support + transitions: transitionEndEvent !== false, + // Reduced motion iOS & MacOS setting + // https://webkit.org/blog/7551/responsive-design-for-motion/ + reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches +}; + +// ========================================================================== +// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md +// https://www.youtube.com/watch?v=NPM6172J22g + +const supportsPassiveListeners = (() => { + // Test via a getter in the options object to see if the passive property is accessed + let supported = false; + + try { + const options = Object.defineProperty({}, 'passive', { + get() { + supported = true; + return null; + } + + }); + window.addEventListener('test', null, options); + window.removeEventListener('test', null, options); + } catch (_) {// Do nothing + } + + return supported; +})(); // Toggle event listener + + +function toggleListener(element, event, callback, toggle = false, passive = true, capture = false) { + // Bail if no element, event, or callback + if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) { + return; + } // Allow multiple events + + + const events = event.split(' '); // Build options + // Default to just the capture boolean for browsers with no passive listener support + + let options = capture; // If passive events listeners are supported + + if (supportsPassiveListeners) { + options = { + // Whether the listener can be passive (i.e. default never prevented) + passive, + // Whether the listener is a capturing listener or not + capture + }; + } // If a single node is passed, bind the event listener + + + events.forEach(type => { + if (this && this.eventListeners && toggle) { + // Cache event listener + this.eventListeners.push({ + element, + type, + callback, + options + }); + } + + element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options); + }); +} // Bind event handler + +function on(element, events = '', callback, passive = true, capture = false) { + toggleListener.call(this, element, events, callback, true, passive, capture); +} // Unbind event handler + +function off(element, events = '', callback, passive = true, capture = false) { + toggleListener.call(this, element, events, callback, false, passive, capture); +} // Bind once-only event handler + +function once(element, events = '', callback, passive = true, capture = false) { + const onceCallback = (...args) => { + off(element, events, onceCallback, passive, capture); + callback.apply(this, args); + }; + + toggleListener.call(this, element, events, onceCallback, true, passive, capture); +} // Trigger event + +function triggerEvent(element, type = '', bubbles = false, detail = {}) { + // Bail if no element + if (!is.element(element) || is.empty(type)) { + return; + } // Create and dispatch the event + + + const event = new CustomEvent(type, { + bubbles, + detail: { ...detail, + plyr: this + } + }); // Dispatch the event + + element.dispatchEvent(event); +} // Unbind all cached event listeners + +function unbindListeners() { + if (this && this.eventListeners) { + this.eventListeners.forEach(item => { + const { + element, + type, + callback, + options + } = item; + element.removeEventListener(type, callback, options); + }); + this.eventListeners = []; + } +} // Run method when / if player is ready + +function ready() { + return new Promise(resolve => this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve)).then(() => {}); +} + +/** + * Silence a Promise-like object. + * This is useful for avoiding non-harmful, but potentially confusing "uncaught + * play promise" rejection error messages. + * @param {Object} value An object that may or may not be `Promise`-like. + */ + +function silencePromise(value) { + if (is.promise(value)) { + value.then(null, () => {}); + } +} + +// ========================================================================== + +function dedupe(array) { + if (!is.array(array)) { + return array; + } + + return array.filter((item, index) => array.indexOf(item) === index); +} // Get the closest value in an array + +function closest(array, value) { + if (!is.array(array) || !array.length) { + return null; + } + + return array.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev); +} + +// ========================================================================== + +function supportsCSS(declaration) { + if (!window || !window.CSS) { + return false; + } + + return window.CSS.supports(declaration); +} // Standard/common aspect ratios + +const standardRatios = [[1, 1], [4, 3], [3, 4], [5, 4], [4, 5], [3, 2], [2, 3], [16, 10], [10, 16], [16, 9], [9, 16], [21, 9], [9, 21], [32, 9], [9, 32]].reduce((out, [x, y]) => ({ ...out, + [x / y]: [x, y] +}), {}); // Validate an aspect ratio + +function validateAspectRatio(input) { + if (!is.array(input) && (!is.string(input) || !input.includes(':'))) { + return false; + } + + const ratio = is.array(input) ? input : input.split(':'); + return ratio.map(Number).every(is.number); +} // Reduce an aspect ratio to it's lowest form + +function reduceAspectRatio(ratio) { + if (!is.array(ratio) || !ratio.every(is.number)) { + return null; + } + + const [width, height] = ratio; + + const getDivider = (w, h) => h === 0 ? w : getDivider(h, w % h); + + const divider = getDivider(width, height); + return [width / divider, height / divider]; +} // Calculate an aspect ratio + +function getAspectRatio(input) { + const parse = ratio => validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null; // Try provided ratio + + + let ratio = parse(input); // Get from config + + if (ratio === null) { + ratio = parse(this.config.ratio); + } // Get from embed + + + if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) { + ({ + ratio + } = this.embed); + } // Get from HTML5 video + + + if (ratio === null && this.isHTML5) { + const { + videoWidth, + videoHeight + } = this.media; + ratio = [videoWidth, videoHeight]; + } + + return reduceAspectRatio(ratio); +} // Set aspect ratio for responsive container + +function setAspectRatio(input) { + if (!this.isVideo) { + return {}; + } + + const { + wrapper + } = this.elements; + const ratio = getAspectRatio.call(this, input); + + if (!is.array(ratio)) { + return {}; + } + + const [x, y] = reduceAspectRatio(ratio); + const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`); + const padding = 100 / x * y; + + if (useNative) { + wrapper.style.aspectRatio = `${x}/${y}`; + } else { + wrapper.style.paddingBottom = `${padding}%`; + } // For Vimeo we have an extra <div> to hide the standard controls and UI + + + if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) { + const height = 100 / this.media.offsetWidth * parseInt(window.getComputedStyle(this.media).paddingBottom, 10); + const offset = (height - padding) / (height / 50); + + if (this.fullscreen.active) { + wrapper.style.paddingBottom = null; + } else { + this.media.style.transform = `translateY(-${offset}%)`; + } + } else if (this.isHTML5) { + wrapper.classList.add(this.config.classNames.videoFixedRatio); + } + + return { + padding, + ratio + }; +} // Round an aspect ratio to closest standard ratio + +function roundAspectRatio(x, y, tolerance = 0.05) { + const ratio = x / y; + const closestRatio = closest(Object.keys(standardRatios), ratio); // Check match is within tolerance + + if (Math.abs(closestRatio - ratio) <= tolerance) { + return standardRatios[closestRatio]; + } // No match + + + return [x, y]; +} // Get the size of the viewport +// https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions + +function getViewportSize() { + const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0); + const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0); + return [width, height]; +} + +// ========================================================================== +const html5 = { + getSources() { + if (!this.isHTML5) { + return []; + } + + const sources = Array.from(this.media.querySelectorAll('source')); // 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 + getQualityOptions() { + // Whether we're forcing all options (e.g. for streaming) + if (this.config.quality.forced) { + return this.config.quality.options; + } // Get sizes from <source> elements + + + return html5.getSources.call(this).map(source => Number(source.getAttribute('data-res'))).filter(Boolean); + }, + + setup() { + if (!this.isHTML5) { + return; + } + + const player = this; // Set speed options from config + + player.options.speed = player.config.speed.options; // Set aspect ratio if fixed + + if (!is.empty(this.config.ratio)) { + setAspectRatio.call(player); + } // Quality + + + Object.defineProperty(player.media, 'quality', { + get() { + // Get sources + const sources = html5.getSources.call(player); + const source = sources.find(s => s.getAttribute('src') === player.source); // Return size, if match is found + + return source && Number(source.getAttribute('data-res')); + }, + + set(input) { + if (player.quality === input) { + return; + } // If we're using an external handler... + + + if (player.config.quality.forced && is.function(player.config.quality.onChange)) { + player.config.quality.onChange(input); + } else { + // Get sources + const sources = html5.getSources.call(player); // Get first match for requested size + + const source = sources.find(s => Number(s.getAttribute('data-res')) === input); // No matching source found + + if (!source) { + return; + } // Get current state + + + const { + currentTime, + paused, + preload, + readyState, + playbackRate + } = player.media; // Set new source + + player.media.src = source.getAttribute('src'); // Prevent loading if preload="none" and the current source isn't loaded (#1044) + + if (preload !== 'none' || readyState) { + // Restore time + player.once('loadedmetadata', () => { + player.speed = playbackRate; + player.currentTime = currentTime; // Resume playing + + if (!paused) { + silencePromise(player.play()); + } + }); // Load new source + + player.media.load(); + } + } // Trigger change event + + + triggerEvent.call(player, player.media, 'qualitychange', false, { + quality: input + }); + } + + }); + }, + + // Cancel current network requests + // See https://github.com/sampotts/plyr/issues/174 + cancelRequests() { + if (!this.isHTML5) { + return; + } // Remove child sources + + + removeElement(html5.getSources.call(this)); // Set blank video src attribute + // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error + // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection + + this.media.setAttribute('src', this.config.blankVideo); // Load the new empty source + // This will cancel existing requests + // See https://github.com/sampotts/plyr/issues/174 + + this.media.load(); // Debugging + + this.debug.log('Cancelled network requests'); + } + +}; + +// ========================================================================== + +function generateId(prefix) { + return `${prefix}-${Math.floor(Math.random() * 10000)}`; +} // Format string + +function format(input, ...args) { + if (is.empty(input)) { + return input; + } + + return input.toString().replace(/{(\d+)}/g, (match, i) => args[i].toString()); +} // Get percentage + +function getPercentage(current, max) { + if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) { + return 0; + } + + return (current / max * 100).toFixed(2); +} // Replace all occurances of a string in a string + +const replaceAll = (input = '', find = '', replace = '') => input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\]/\\])/g, '\\$1'), 'g'), replace.toString()); // Convert to title case + +const toTitleCase = (input = '') => input.toString().replace(/\w\S*/g, text => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()); // Convert string to pascalCase + +function toPascalCase(input = '') { + let string = input.toString(); // Convert kebab case + + string = replaceAll(string, '-', ' '); // Convert snake case + + string = replaceAll(string, '_', ' '); // Convert to title case + + string = toTitleCase(string); // Convert to pascal case + + return replaceAll(string, ' ', ''); +} // Convert string to pascalCase + +function toCamelCase(input = '') { + let string = input.toString(); // Convert to pascal case + + string = toPascalCase(string); // Convert first character to lowercase + + return string.charAt(0).toLowerCase() + string.slice(1); +} // Remove HTML from a string + +function stripHTML(source) { + const fragment = document.createDocumentFragment(); + const element = document.createElement('div'); + fragment.appendChild(element); + element.innerHTML = source; + return fragment.firstChild.innerText; +} // Like outerHTML, but also works for DocumentFragment + +function getHTML(element) { + const wrapper = document.createElement('div'); + wrapper.appendChild(element); + return wrapper.innerHTML; +} + +// ========================================================================== + +const resources = { + pip: 'PIP', + airplay: 'AirPlay', + html5: 'HTML5', + vimeo: 'Vimeo', + youtube: 'YouTube' +}; +const i18n = { + get(key = '', config = {}) { + if (is.empty(key) || is.empty(config)) { + return ''; + } + + let string = getDeep(config.i18n, key); + + if (is.empty(string)) { + if (Object.keys(resources).includes(key)) { + return resources[key]; + } + + return ''; + } + + const replace = { + '{seektime}': config.seekTime, + '{title}': config.title + }; + Object.entries(replace).forEach(([k, v]) => { + string = replaceAll(string, k, v); + }); + return string; + } + +}; + +class Storage { + constructor(player) { + _defineProperty$1(this, "get", key => { + if (!Storage.supported || !this.enabled) { + return null; + } + + const store = window.localStorage.getItem(this.key); + + if (is.empty(store)) { + return null; + } + + const json = JSON.parse(store); + return is.string(key) && key.length ? json[key] : json; + }); + + _defineProperty$1(this, "set", object => { + // Bail if we don't have localStorage support or it's disabled + if (!Storage.supported || !this.enabled) { + return; + } // Can only store objectst + + + if (!is.object(object)) { + return; + } // Get current storage + + + let storage = this.get(); // Default to empty object + + if (is.empty(storage)) { + storage = {}; + } // Update the working copy of the values + + + extend(storage, object); // Update storage + + try { + window.localStorage.setItem(this.key, JSON.stringify(storage)); + } catch (_) {// Do nothing + } + }); + + this.enabled = player.config.storage.enabled; + this.key = player.config.storage.key; + } // Check for actual support (see if we can use it) + + + static get supported() { + try { + if (!('localStorage' in window)) { + return false; + } + + const test = '___test'; // Try to use it (it might be disabled, e.g. user is in private mode) + // see: https://github.com/sampotts/plyr/issues/131 + + window.localStorage.setItem(test, test); + window.localStorage.removeItem(test); + return true; + } catch (_) { + return false; + } + } + +} + +// ========================================================================== +// Fetch wrapper +// Using XHR to avoid issues with older browsers +// ========================================================================== +function fetch(url, responseType = 'text') { + return new Promise((resolve, reject) => { + try { + const request = new XMLHttpRequest(); // Check for CORS support + + if (!('withCredentials' in request)) { + return; + } + + request.addEventListener('load', () => { + if (responseType === 'text') { + try { + resolve(JSON.parse(request.responseText)); + } catch (_) { + resolve(request.responseText); + } + } else { + resolve(request.response); + } + }); + request.addEventListener('error', () => { + throw new Error(request.status); + }); + request.open('GET', url, true); // Set the required response type + + request.responseType = responseType; + request.send(); + } catch (error) { + reject(error); + } + }); +} + +// ========================================================================== + +function loadSprite(url, id) { + if (!is.string(url)) { + return; + } + + const prefix = 'cache'; + const hasId = is.string(id); + let isCached = false; + + const exists = () => document.getElementById(id) !== null; + + const update = (container, data) => { + // eslint-disable-next-line no-param-reassign + container.innerHTML = data; // Check again incase of race condition + + if (hasId && exists()) { + return; + } // Inject the SVG to the body + + + document.body.insertAdjacentElement('afterbegin', container); + }; // Only load once if ID set + + + if (!hasId || !exists()) { + const useStorage = Storage.supported; // Create container + + const container = document.createElement('div'); + container.setAttribute('hidden', ''); + + if (hasId) { + container.setAttribute('id', id); + } // Check in cache + + + if (useStorage) { + const cached = window.localStorage.getItem(`${prefix}-${id}`); + isCached = cached !== null; + + if (isCached) { + const data = JSON.parse(cached); + update(container, data.content); + } + } // Get the sprite + + + fetch(url).then(result => { + if (is.empty(result)) { + return; + } + + if (useStorage) { + try { + window.localStorage.setItem(`${prefix}-${id}`, JSON.stringify({ + content: result + })); + } catch (_) {// Do nothing + } + } + + update(container, result); + }).catch(() => {}); + } +} + +// ========================================================================== + +const getHours = value => Math.trunc(value / 60 / 60 % 60, 10); +const getMinutes = value => Math.trunc(value / 60 % 60, 10); +const getSeconds = value => Math.trunc(value % 60, 10); // Format time to UI friendly string + +function formatTime(time = 0, displayHours = false, inverted = false) { + // Bail if the value isn't a number + if (!is.number(time)) { + return formatTime(undefined, displayHours, inverted); + } // Format time component to add leading zero + + + const format = value => `0${value}`.slice(-2); // Breakdown to hours, mins, secs + + + let hours = getHours(time); + const mins = getMinutes(time); + const secs = getSeconds(time); // Do we need to display hours? + + if (displayHours || hours > 0) { + hours = `${hours}:`; + } else { + hours = ''; + } // Render + + + return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`; +} + +// ========================================================================== + +const controls = { + // Get icon URL + getIconUrl() { + const url = new URL(this.config.iconUrl, window.location); + const host = window.location.host ? window.location.host : window.top.location.host; + const cors = url.host !== host || browser.isIE && !window.svg4everybody; + return { + url: this.config.iconUrl, + cors + }; + }, + + // Find the UI controls + findElements() { + try { + this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper); // Buttons + + this.elements.buttons = { + play: getElements.call(this, this.config.selectors.buttons.play), + pause: getElement.call(this, this.config.selectors.buttons.pause), + restart: getElement.call(this, this.config.selectors.buttons.restart), + rewind: getElement.call(this, this.config.selectors.buttons.rewind), + fastForward: getElement.call(this, this.config.selectors.buttons.fastForward), + mute: getElement.call(this, this.config.selectors.buttons.mute), + pip: getElement.call(this, this.config.selectors.buttons.pip), + airplay: getElement.call(this, this.config.selectors.buttons.airplay), + settings: getElement.call(this, this.config.selectors.buttons.settings), + captions: getElement.call(this, this.config.selectors.buttons.captions), + fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen) + }; // Progress + + this.elements.progress = getElement.call(this, this.config.selectors.progress); // Inputs + + this.elements.inputs = { + seek: getElement.call(this, this.config.selectors.inputs.seek), + volume: getElement.call(this, this.config.selectors.inputs.volume) + }; // Display + + this.elements.display = { + buffer: getElement.call(this, this.config.selectors.display.buffer), + currentTime: getElement.call(this, this.config.selectors.display.currentTime), + duration: getElement.call(this, this.config.selectors.display.duration) + }; // Seek tooltip + + if (is.element(this.elements.progress)) { + this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`); + } + + return true; + } catch (error) { + // Log it + this.debug.warn('It looks like there is a problem with your custom controls HTML', error); // Restore native video controls + + this.toggleNativeControls(true); + return false; + } + }, + + // Create <svg> icon + createIcon(type, attributes) { + const namespace = 'http://www.w3.org/2000/svg'; + const iconUrl = controls.getIconUrl.call(this); + const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`; // Create <svg> + + const icon = document.createElementNS(namespace, 'svg'); + setAttributes(icon, extend(attributes, { + 'aria-hidden': 'true', + focusable: 'false' + })); // Create the <use> to reference sprite + + const use = document.createElementNS(namespace, 'use'); + const path = `${iconPath}-${type}`; // Set `href` attributes + // https://github.com/sampotts/plyr/issues/460 + // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href + + if ('href' in use) { + use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path); + } // Always set the older attribute even though it's "deprecated" (it'll be around for ages) + + + use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path); // Add <use> to <svg> + + icon.appendChild(use); + return icon; + }, + + // Create hidden text label + createLabel(key, attr = {}) { + const text = i18n.get(key, this.config); + const attributes = { ...attr, + class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ') + }; + return createElement('span', attributes, text); + }, + + // Create a badge + createBadge(text) { + if (is.empty(text)) { + return null; + } + + const badge = createElement('span', { + class: this.config.classNames.menu.value + }); + badge.appendChild(createElement('span', { + class: this.config.classNames.menu.badge + }, text)); + return badge; + }, + + // Create a <button> + createButton(buttonType, attr) { + const attributes = extend({}, attr); + let type = toCamelCase(buttonType); + const props = { + element: 'button', + toggle: false, + label: null, + icon: null, + labelPressed: null, + iconPressed: null + }; + ['element', 'icon', 'label'].forEach(key => { + if (Object.keys(attributes).includes(key)) { + props[key] = attributes[key]; + delete attributes[key]; + } + }); // Default to 'button' type to prevent form submission + + if (props.element === 'button' && !Object.keys(attributes).includes('type')) { + attributes.type = 'button'; + } // Set class name + + + if (Object.keys(attributes).includes('class')) { + if (!attributes.class.split(' ').some(c => c === this.config.classNames.control)) { + extend(attributes, { + class: `${attributes.class} ${this.config.classNames.control}` + }); + } + } else { + attributes.class = this.config.classNames.control; + } // Large play button + + + switch (buttonType) { + case 'play': + props.toggle = true; + props.label = 'play'; + props.labelPressed = 'pause'; + props.icon = 'play'; + props.iconPressed = 'pause'; + break; + + case 'mute': + props.toggle = true; + props.label = 'mute'; + props.labelPressed = 'unmute'; + props.icon = 'volume'; + props.iconPressed = 'muted'; + break; + + case 'captions': + props.toggle = true; + props.label = 'enableCaptions'; + props.labelPressed = 'disableCaptions'; + props.icon = 'captions-off'; + props.iconPressed = 'captions-on'; + break; + + case 'fullscreen': + props.toggle = true; + props.label = 'enterFullscreen'; + props.labelPressed = 'exitFullscreen'; + props.icon = 'enter-fullscreen'; + props.iconPressed = 'exit-fullscreen'; + break; + + case 'play-large': + attributes.class += ` ${this.config.classNames.control}--overlaid`; + type = 'play'; + props.label = 'play'; + props.icon = 'play'; + break; + + default: + if (is.empty(props.label)) { + props.label = type; + } + + if (is.empty(props.icon)) { + props.icon = buttonType; + } + + } + + const button = createElement(props.element); // Setup toggle icon and labels + + if (props.toggle) { + // Icon + button.appendChild(controls.createIcon.call(this, props.iconPressed, { + class: 'icon--pressed' + })); + button.appendChild(controls.createIcon.call(this, props.icon, { + class: 'icon--not-pressed' + })); // Label/Tooltip + + button.appendChild(controls.createLabel.call(this, props.labelPressed, { + class: 'label--pressed' + })); + button.appendChild(controls.createLabel.call(this, props.label, { + class: 'label--not-pressed' + })); + } else { + button.appendChild(controls.createIcon.call(this, props.icon)); + button.appendChild(controls.createLabel.call(this, props.label)); + } // Merge and set attributes + + + extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes)); + setAttributes(button, attributes); // We have multiple play buttons + + if (type === 'play') { + if (!is.array(this.elements.buttons[type])) { + this.elements.buttons[type] = []; + } + + this.elements.buttons[type].push(button); + } else { + this.elements.buttons[type] = button; + } + + return button; + }, + + // Create an <input type='range'> + createRange(type, attributes) { + // Seek input + const input = createElement('input', extend(getAttributesFromSelector(this.config.selectors.inputs[type]), { + type: 'range', + min: 0, + max: 100, + step: 0.01, + value: 0, + autocomplete: 'off', + // A11y fixes for https://github.com/sampotts/plyr/issues/905 + role: 'slider', + 'aria-label': i18n.get(type, this.config), + 'aria-valuemin': 0, + 'aria-valuemax': 100, + 'aria-valuenow': 0 + }, attributes)); + this.elements.inputs[type] = input; // Set the fill for webkit now + + controls.updateRangeFill.call(this, input); // Improve support on touch devices + + RangeTouch.setup(input); + return input; + }, + + // Create a <progress> + createProgress(type, attributes) { + const progress = createElement('progress', extend(getAttributesFromSelector(this.config.selectors.display[type]), { + min: 0, + max: 100, + value: 0, + role: 'progressbar', + 'aria-hidden': true + }, attributes)); // Create the label inside + + if (type !== 'volume') { + progress.appendChild(createElement('span', null, '0')); + const suffixKey = { + played: 'played', + buffer: 'buffered' + }[type]; + const suffix = suffixKey ? i18n.get(suffixKey, this.config) : ''; + progress.innerText = `% ${suffix.toLowerCase()}`; + } + + this.elements.display[type] = progress; + return progress; + }, + + // Create time display + createTime(type, attrs) { + const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs); + const container = createElement('div', extend(attributes, { + class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(), + 'aria-label': i18n.get(type, this.config) + }), '00:00'); // Reference for updates + + this.elements.display[type] = container; + return container; + }, + + // Bind keyboard shortcuts for a menu item + // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus + // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143 + bindMenuItemShortcuts(menuItem, type) { + // Navigate through menus via arrow keys and space + on.call(this, menuItem, 'keydown keyup', event => { + // We only care about space and ⬆️ ⬇️️ ➡️ + if (![32, 38, 39, 40].includes(event.which)) { + return; + } // Prevent play / seek + + + event.preventDefault(); + event.stopPropagation(); // We're just here to prevent the keydown bubbling + + if (event.type === 'keydown') { + return; + } + + const isRadioButton = matches(menuItem, '[role="menuitemradio"]'); // Show the respective menu + + if (!isRadioButton && [32, 39].includes(event.which)) { + controls.showMenuPanel.call(this, type, true); + } else { + let target; + + if (event.which !== 32) { + if (event.which === 40 || isRadioButton && event.which === 39) { + target = menuItem.nextElementSibling; + + if (!is.element(target)) { + target = menuItem.parentNode.firstElementChild; + } + } else { + target = menuItem.previousElementSibling; + + if (!is.element(target)) { + target = menuItem.parentNode.lastElementChild; + } + } + + setFocus.call(this, target, true); + } + } + }, false); // Enter will fire a `click` event but we still need to manage focus + // So we bind to keyup which fires after and set focus here + + on.call(this, menuItem, 'keyup', event => { + if (event.which !== 13) { + return; + } + + controls.focusFirstMenuItem.call(this, null, true); + }); + }, + + // Create a settings menu item + createMenuItem({ + value, + list, + type, + title, + badge = null, + checked = false + }) { + const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]); + const menuItem = createElement('button', extend(attributes, { + type: 'button', + role: 'menuitemradio', + class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(), + 'aria-checked': checked, + value + })); + const flex = createElement('span'); // We have to set as HTML incase of special characters + + flex.innerHTML = title; + + if (is.element(badge)) { + flex.appendChild(badge); + } + + menuItem.appendChild(flex); // Replicate radio button behaviour + + Object.defineProperty(menuItem, 'checked', { + enumerable: true, + + get() { + return menuItem.getAttribute('aria-checked') === 'true'; + }, + + set(check) { + // Ensure exclusivity + if (check) { + Array.from(menuItem.parentNode.children).filter(node => matches(node, '[role="menuitemradio"]')).forEach(node => node.setAttribute('aria-checked', 'false')); + } + + menuItem.setAttribute('aria-checked', check ? 'true' : 'false'); + } + + }); + this.listeners.bind(menuItem, 'click keyup', event => { + if (is.keyboardEvent(event) && event.which !== 32) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + menuItem.checked = true; + + switch (type) { + case 'language': + this.currentTrack = Number(value); + break; + + case 'quality': + this.quality = value; + break; + + case 'speed': + this.speed = parseFloat(value); + break; + } + + controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event)); + }, type, false); + controls.bindMenuItemShortcuts.call(this, menuItem, type); + list.appendChild(menuItem); + }, + + // Format a time for display + formatTime(time = 0, inverted = false) { + // Bail if the value isn't a number + if (!is.number(time)) { + return time; + } // Always display hours if duration is over an hour + + + const forceHours = getHours(this.duration) > 0; + return formatTime(time, forceHours, inverted); + }, + + // Update the displayed time + updateTimeDisplay(target = null, time = 0, inverted = false) { + // Bail if there's no element to display or the value isn't a number + if (!is.element(target) || !is.number(time)) { + return; + } // eslint-disable-next-line no-param-reassign + + + target.innerText = controls.formatTime(time, inverted); + }, + + // Update volume UI and storage + updateVolume() { + if (!this.supported.ui) { + return; + } // Update range + + + if (is.element(this.elements.inputs.volume)) { + controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume); + } // Update mute state + + + if (is.element(this.elements.buttons.mute)) { + this.elements.buttons.mute.pressed = this.muted || this.volume === 0; + } + }, + + // Update seek value and lower fill + setRange(target, value = 0) { + if (!is.element(target)) { + return; + } // eslint-disable-next-line + + + target.value = value; // Webkit range fill + + controls.updateRangeFill.call(this, target); + }, + + // Update <progress> elements + updateProgress(event) { + if (!this.supported.ui || !is.event(event)) { + return; + } + + let value = 0; + + const setProgress = (target, input) => { + const val = is.number(input) ? input : 0; + const progress = is.element(target) ? target : this.elements.display.buffer; // Update value and label + + if (is.element(progress)) { + progress.value = val; // Update text label inside + + const label = progress.getElementsByTagName('span')[0]; + + if (is.element(label)) { + label.childNodes[0].nodeValue = val; + } + } + }; + + if (event) { + switch (event.type) { + // Video playing + case 'timeupdate': + case 'seeking': + case 'seeked': + value = getPercentage(this.currentTime, this.duration); // Set seek range value only if it's a 'natural' time event + + if (event.type === 'timeupdate') { + controls.setRange.call(this, this.elements.inputs.seek, value); + } + + break; + // Check buffer status + + case 'playing': + case 'progress': + setProgress(this.elements.display.buffer, this.buffered * 100); + break; + } + } + }, + + // Webkit polyfill for lower fill range + updateRangeFill(target) { + // Get range from event if event passed + const range = is.event(target) ? target.target : target; // Needs to be a valid <input type='range'> + + if (!is.element(range) || range.getAttribute('type') !== 'range') { + return; + } // Set aria values for https://github.com/sampotts/plyr/issues/905 + + + if (matches(range, this.config.selectors.inputs.seek)) { + range.setAttribute('aria-valuenow', this.currentTime); + const currentTime = controls.formatTime(this.currentTime); + const duration = controls.formatTime(this.duration); + const format = i18n.get('seekLabel', this.config); + range.setAttribute('aria-valuetext', format.replace('{currentTime}', currentTime).replace('{duration}', duration)); + } else if (matches(range, this.config.selectors.inputs.volume)) { + const percent = range.value * 100; + range.setAttribute('aria-valuenow', percent); + range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`); + } else { + range.setAttribute('aria-valuenow', range.value); + } // WebKit only + + + if (!browser.isWebkit) { + return; + } // Set CSS custom property + + + range.style.setProperty('--value', `${range.value / range.max * 100}%`); + }, + + // Update hover tooltip for seeking + updateSeekTooltip(event) { + // Bail if setting not true + if (!this.config.tooltips.seek || !is.element(this.elements.inputs.seek) || !is.element(this.elements.display.seekTooltip) || this.duration === 0) { + return; + } + + const visible = `${this.config.classNames.tooltip}--visible`; + + const toggle = show => toggleClass(this.elements.display.seekTooltip, visible, show); // Hide on touch + + + if (this.touch) { + toggle(false); + return; + } // Determine percentage, if already visible + + + let percent = 0; + const clientRect = this.elements.progress.getBoundingClientRect(); + + if (is.event(event)) { + percent = 100 / clientRect.width * (event.pageX - clientRect.left); + } else if (hasClass(this.elements.display.seekTooltip, visible)) { + percent = parseFloat(this.elements.display.seekTooltip.style.left, 10); + } else { + return; + } // Set bounds + + + if (percent < 0) { + percent = 0; + } else if (percent > 100) { + percent = 100; + } // Display the time a click would seek to + + + controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent); // Set position + + this.elements.display.seekTooltip.style.left = `${percent}%`; // Show/hide the tooltip + // If the event is a moues in/out and percentage is inside bounds + + if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) { + toggle(event.type === 'mouseenter'); + } + }, + + // Handle time change event + timeUpdate(event) { + // Only invert if only one time element is displayed and used for both duration and currentTime + const invert = !is.element(this.elements.display.duration) && this.config.invertTime; // Duration + + controls.updateTimeDisplay.call(this, this.elements.display.currentTime, invert ? this.duration - this.currentTime : this.currentTime, invert); // Ignore updates while seeking + + if (event && event.type === 'timeupdate' && this.media.seeking) { + return; + } // Playing progress + + + controls.updateProgress.call(this, event); + }, + + // Show the duration on metadataloaded or durationchange events + durationUpdate() { + // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false + if (!this.supported.ui || !this.config.invertTime && this.currentTime) { + return; + } // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar. + // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415 + // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062 + // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338 + + + if (this.duration >= 2 ** 32) { + toggleHidden(this.elements.display.currentTime, true); + toggleHidden(this.elements.progress, true); + return; + } // Update ARIA values + + + if (is.element(this.elements.inputs.seek)) { + this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration); + } // If there's a spot to display duration + + + const hasDuration = is.element(this.elements.display.duration); // If there's only one time display, display duration there + + if (!hasDuration && this.config.displayDuration && this.paused) { + controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration); + } // If there's a duration element, update content + + + if (hasDuration) { + controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration); + } // Update the tooltip (if visible) + + + controls.updateSeekTooltip.call(this); + }, + + // Hide/show a tab + toggleMenuButton(setting, toggle) { + toggleHidden(this.elements.settings.buttons[setting], !toggle); + }, + + // Update the selected setting + updateSetting(setting, container, input) { + const pane = this.elements.settings.panels[setting]; + let value = null; + let list = container; + + if (setting === 'captions') { + value = this.currentTrack; + } else { + value = !is.empty(input) ? input : this[setting]; // Get default + + if (is.empty(value)) { + value = this.config[setting].default; + } // Unsupported value + + + if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) { + this.debug.warn(`Unsupported value of '${value}' for ${setting}`); + return; + } // Disabled value + + + if (!this.config[setting].options.includes(value)) { + this.debug.warn(`Disabled value of '${value}' for ${setting}`); + return; + } + } // Get the list if we need to + + + if (!is.element(list)) { + list = pane && pane.querySelector('[role="menu"]'); + } // If there's no list it means it's not been rendered... + + + if (!is.element(list)) { + return; + } // Update the label + + + const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`); + label.innerHTML = controls.getLabel.call(this, setting, value); // Find the radio option and check it + + const target = list && list.querySelector(`[value="${value}"]`); + + if (is.element(target)) { + target.checked = true; + } + }, + + // Translate a value into a nice label + getLabel(setting, value) { + switch (setting) { + case 'speed': + return value === 1 ? i18n.get('normal', this.config) : `${value}×`; + + case 'quality': + if (is.number(value)) { + const label = i18n.get(`qualityLabel.${value}`, this.config); + + if (!label.length) { + return `${value}p`; + } + + return label; + } + + return toTitleCase(value); + + case 'captions': + return captions.getLabel.call(this); + + default: + return null; + } + }, + + // Set the quality menu + setQualityMenu(options) { + // Menu required + if (!is.element(this.elements.settings.panels.quality)) { + return; + } + + const type = 'quality'; + const list = this.elements.settings.panels.quality.querySelector('[role="menu"]'); // Set options if passed and filter based on uniqueness and config + + if (is.array(options)) { + this.options.quality = dedupe(options).filter(quality => this.config.quality.options.includes(quality)); + } // Toggle the pane and tab + + + const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1; + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If we're hiding, nothing more to do + + if (!toggle) { + return; + } // Get the badge HTML for HD, 4K etc + + + const getBadge = quality => { + const label = i18n.get(`qualityBadge.${quality}`, this.config); + + if (!label.length) { + return null; + } + + return controls.createBadge.call(this, label); + }; // Sort options by the config and then render options + + + this.options.quality.sort((a, b) => { + const sorting = this.config.quality.options; + return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1; + }).forEach(quality => { + controls.createMenuItem.call(this, { + value: quality, + list, + type, + title: controls.getLabel.call(this, 'quality', quality), + badge: getBadge(quality) + }); + }); + controls.updateSetting.call(this, type, list); + }, + + // Set the looping options + + /* setLoopMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.loop)) { + return; + } + const options = ['start', 'end', 'all', 'reset']; + const list = this.elements.settings.panels.loop.querySelector('[role="menu"]'); + // Show the pane and tab + toggleHidden(this.elements.settings.buttons.loop, false); + toggleHidden(this.elements.settings.panels.loop, false); + // Toggle the pane and tab + const toggle = !is.empty(this.loop.options); + controls.toggleMenuButton.call(this, 'loop', toggle); + // Empty the menu + emptyElement(list); + options.forEach(option => { + const item = createElement('li'); + const button = createElement( + 'button', + extend(getAttributesFromSelector(this.config.selectors.buttons.loop), { + type: 'button', + class: this.config.classNames.control, + 'data-plyr-loop-action': option, + }), + i18n.get(option, this.config) + ); + if (['start', 'end'].includes(option)) { + const badge = controls.createBadge.call(this, '00:00'); + button.appendChild(badge); + } + item.appendChild(button); + list.appendChild(item); + }); + }, */ + // Get current selected caption language + // TODO: rework this to user the getter in the API? + // Set a list of available captions languages + setCaptionsMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.captions)) { + return; + } // TODO: Captions or language? Currently it's mixed + + + const type = 'captions'; + const list = this.elements.settings.panels.captions.querySelector('[role="menu"]'); + const tracks = captions.getTracks.call(this); + const toggle = Boolean(tracks.length); // Toggle the pane and tab + + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If there's no captions, bail + + if (!toggle) { + return; + } // Generate options data + + + const options = tracks.map((track, value) => ({ + value, + checked: this.captions.toggled && this.currentTrack === value, + title: captions.getLabel.call(this, track), + badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()), + list, + type: 'language' + })); // Add the "Disabled" option to turn off captions + + options.unshift({ + value: -1, + checked: !this.captions.toggled, + title: i18n.get('disabled', this.config), + list, + type: 'language' + }); // Generate options + + options.forEach(controls.createMenuItem.bind(this)); + controls.updateSetting.call(this, type, list); + }, + + // Set a list of available captions languages + setSpeedMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.speed)) { + return; + } + + const type = 'speed'; + const list = this.elements.settings.panels.speed.querySelector('[role="menu"]'); // Filter out invalid speeds + + this.options.speed = this.options.speed.filter(o => o >= this.minimumSpeed && o <= this.maximumSpeed); // Toggle the pane and tab + + const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1; + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If we're hiding, nothing more to do + + if (!toggle) { + return; + } // Create items + + + this.options.speed.forEach(speed => { + controls.createMenuItem.call(this, { + value: speed, + list, + type, + title: controls.getLabel.call(this, 'speed', speed) + }); + }); + controls.updateSetting.call(this, type, list); + }, + + // Check if we need to hide/show the settings menu + checkMenu() { + const { + buttons + } = this.elements.settings; + const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden); + toggleHidden(this.elements.settings.menu, !visible); + }, + + // Focus the first menu item in a given (or visible) menu + focusFirstMenuItem(pane, tabFocus = false) { + if (this.elements.settings.popup.hidden) { + return; + } + + let target = pane; + + if (!is.element(target)) { + target = Object.values(this.elements.settings.panels).find(p => !p.hidden); + } + + const firstItem = target.querySelector('[role^="menuitem"]'); + setFocus.call(this, firstItem, tabFocus); + }, + + // Show/hide menu + toggleMenu(input) { + const { + popup + } = this.elements.settings; + const button = this.elements.buttons.settings; // Menu and button are required + + if (!is.element(popup) || !is.element(button)) { + return; + } // True toggle by default + + + const { + hidden + } = popup; + let show = hidden; + + if (is.boolean(input)) { + show = input; + } else if (is.keyboardEvent(input) && input.which === 27) { + show = false; + } else if (is.event(input)) { + // If Plyr is in a shadowDOM, the event target is set to the component, instead of the + // Element in the shadowDOM. The path, if available, is complete. + const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target; + const isMenuItem = popup.contains(target); // If the click was inside the menu or if the click + // wasn't the button or menu item and we're trying to + // show the menu (a doc click shouldn't show the menu) + + if (isMenuItem || !isMenuItem && input.target !== button && show) { + return; + } + } // Set button attributes + + + button.setAttribute('aria-expanded', show); // Show the actual popup + + toggleHidden(popup, !show); // Add class hook + + toggleClass(this.elements.container, this.config.classNames.menu.open, show); // Focus the first item if key interaction + + if (show && is.keyboardEvent(input)) { + controls.focusFirstMenuItem.call(this, null, true); + } else if (!show && !hidden) { + // If closing, re-focus the button + setFocus.call(this, button, is.keyboardEvent(input)); + } + }, + + // Get the natural size of a menu panel + getMenuSize(tab) { + const clone = tab.cloneNode(true); + clone.style.position = 'absolute'; + clone.style.opacity = 0; + clone.removeAttribute('hidden'); // Append to parent so we get the "real" size + + tab.parentNode.appendChild(clone); // Get the sizes before we remove + + const width = clone.scrollWidth; + const height = clone.scrollHeight; // Remove from the DOM + + removeElement(clone); + return { + width, + height + }; + }, + + // Show a panel in the menu + showMenuPanel(type = '', tabFocus = false) { + const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`); // Nothing to show, bail + + if (!is.element(target)) { + return; + } // Hide all other panels + + + const container = target.parentNode; + const current = Array.from(container.children).find(node => !node.hidden); // If we can do fancy animations, we'll animate the height/width + + if (support.transitions && !support.reducedMotion) { + // Set the current width as a base + container.style.width = `${current.scrollWidth}px`; + container.style.height = `${current.scrollHeight}px`; // Get potential sizes + + const size = controls.getMenuSize.call(this, target); // Restore auto height/width + + const restore = event => { + // We're only bothered about height and width on the container + if (event.target !== container || !['width', 'height'].includes(event.propertyName)) { + return; + } // Revert back to auto + + + container.style.width = ''; + container.style.height = ''; // Only listen once + + off.call(this, container, transitionEndEvent, restore); + }; // Listen for the transition finishing and restore auto height/width + + + on.call(this, container, transitionEndEvent, restore); // Set dimensions to target + + container.style.width = `${size.width}px`; + container.style.height = `${size.height}px`; + } // Set attributes on current tab + + + toggleHidden(current, true); // Set attributes on target + + toggleHidden(target, false); // Focus the first item + + controls.focusFirstMenuItem.call(this, target, tabFocus); + }, + + // Set the download URL + setDownloadUrl() { + const button = this.elements.buttons.download; // Bail if no button + + if (!is.element(button)) { + return; + } // Set attribute + + + button.setAttribute('href', this.download); + }, + + // Build the default HTML + create(data) { + const { + bindMenuItemShortcuts, + createButton, + createProgress, + createRange, + createTime, + setQualityMenu, + setSpeedMenu, + showMenuPanel + } = controls; + this.elements.controls = null; // Larger overlaid play button + + if (is.array(this.config.controls) && this.config.controls.includes('play-large')) { + this.elements.container.appendChild(createButton.call(this, 'play-large')); + } // Create the container + + + const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper)); + this.elements.controls = container; // Default item attributes + + const defaultAttributes = { + class: 'plyr__controls__item' + }; // Loop through controls in order + + dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach(control => { + // Restart button + if (control === 'restart') { + container.appendChild(createButton.call(this, 'restart', defaultAttributes)); + } // Rewind button + + + if (control === 'rewind') { + container.appendChild(createButton.call(this, 'rewind', defaultAttributes)); + } // Play/Pause button + + + if (control === 'play') { + container.appendChild(createButton.call(this, 'play', defaultAttributes)); + } // Fast forward button + + + if (control === 'fast-forward') { + container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes)); + } // Progress + + + if (control === 'progress') { + const progressContainer = createElement('div', { + class: `${defaultAttributes.class} plyr__progress__container` + }); + const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress)); // Seek range slider + + progress.appendChild(createRange.call(this, 'seek', { + id: `plyr-seek-${data.id}` + })); // Buffer progress + + progress.appendChild(createProgress.call(this, 'buffer')); // TODO: Add loop display indicator + // Seek tooltip + + if (this.config.tooltips.seek) { + const tooltip = createElement('span', { + class: this.config.classNames.tooltip + }, '00:00'); + progress.appendChild(tooltip); + this.elements.display.seekTooltip = tooltip; + } + + this.elements.progress = progress; + progressContainer.appendChild(this.elements.progress); + container.appendChild(progressContainer); + } // Media current time display + + + if (control === 'current-time') { + container.appendChild(createTime.call(this, 'currentTime', defaultAttributes)); + } // Media duration display + + + if (control === 'duration') { + container.appendChild(createTime.call(this, 'duration', defaultAttributes)); + } // Volume controls + + + if (control === 'mute' || control === 'volume') { + let { + volume + } = this.elements; // Create the volume container if needed + + if (!is.element(volume) || !container.contains(volume)) { + volume = createElement('div', extend({}, defaultAttributes, { + class: `${defaultAttributes.class} plyr__volume`.trim() + })); + this.elements.volume = volume; + container.appendChild(volume); + } // Toggle mute button + + + if (control === 'mute') { + volume.appendChild(createButton.call(this, 'mute')); + } // Volume range control + // Ignored on iOS as it's handled globally + // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html + + + if (control === 'volume' && !browser.isIos) { + // Set the attributes + const attributes = { + max: 1, + step: 0.05, + value: this.config.volume + }; // Create the volume range slider + + volume.appendChild(createRange.call(this, 'volume', extend(attributes, { + id: `plyr-volume-${data.id}` + }))); + } + } // Toggle captions button + + + if (control === 'captions') { + container.appendChild(createButton.call(this, 'captions', defaultAttributes)); + } // Settings button / menu + + + if (control === 'settings' && !is.empty(this.config.settings)) { + const wrapper = createElement('div', extend({}, defaultAttributes, { + class: `${defaultAttributes.class} plyr__menu`.trim(), + hidden: '' + })); + wrapper.appendChild(createButton.call(this, 'settings', { + 'aria-haspopup': true, + 'aria-controls': `plyr-settings-${data.id}`, + 'aria-expanded': false + })); + const popup = createElement('div', { + class: 'plyr__menu__container', + id: `plyr-settings-${data.id}`, + hidden: '' + }); + const inner = createElement('div'); + const home = createElement('div', { + id: `plyr-settings-${data.id}-home` + }); // Create the menu + + const menu = createElement('div', { + role: 'menu' + }); + home.appendChild(menu); + inner.appendChild(home); + this.elements.settings.panels.home = home; // Build the menu items + + this.config.settings.forEach(type => { + // TODO: bundle this with the createMenuItem helper and bindings + const menuItem = createElement('button', extend(getAttributesFromSelector(this.config.selectors.buttons.settings), { + type: 'button', + class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`, + role: 'menuitem', + 'aria-haspopup': true, + hidden: '' + })); // Bind menu shortcuts for keyboard users + + bindMenuItemShortcuts.call(this, menuItem, type); // Show menu on click + + on.call(this, menuItem, 'click', () => { + showMenuPanel.call(this, type, false); + }); + const flex = createElement('span', null, i18n.get(type, this.config)); + const value = createElement('span', { + class: this.config.classNames.menu.value + }); // Speed contains HTML entities + + value.innerHTML = data[type]; + flex.appendChild(value); + menuItem.appendChild(flex); + menu.appendChild(menuItem); // Build the panes + + const pane = createElement('div', { + id: `plyr-settings-${data.id}-${type}`, + hidden: '' + }); // Back button + + const backButton = createElement('button', { + type: 'button', + class: `${this.config.classNames.control} ${this.config.classNames.control}--back` + }); // Visible label + + backButton.appendChild(createElement('span', { + 'aria-hidden': true + }, i18n.get(type, this.config))); // Screen reader label + + backButton.appendChild(createElement('span', { + class: this.config.classNames.hidden + }, i18n.get('menuBack', this.config))); // Go back via keyboard + + on.call(this, pane, 'keydown', event => { + // We only care about <- + if (event.which !== 37) { + return; + } // Prevent seek + + + event.preventDefault(); + event.stopPropagation(); // Show the respective menu + + showMenuPanel.call(this, 'home', true); + }, false); // Go back via button click + + on.call(this, backButton, 'click', () => { + showMenuPanel.call(this, 'home', false); + }); // Add to pane + + pane.appendChild(backButton); // Menu + + pane.appendChild(createElement('div', { + role: 'menu' + })); + inner.appendChild(pane); + this.elements.settings.buttons[type] = menuItem; + this.elements.settings.panels[type] = pane; + }); + popup.appendChild(inner); + wrapper.appendChild(popup); + container.appendChild(wrapper); + this.elements.settings.popup = popup; + this.elements.settings.menu = wrapper; + } // Picture in picture button + + + if (control === 'pip' && support.pip) { + container.appendChild(createButton.call(this, 'pip', defaultAttributes)); + } // Airplay button + + + if (control === 'airplay' && support.airplay) { + container.appendChild(createButton.call(this, 'airplay', defaultAttributes)); + } // Download button + + + if (control === 'download') { + const attributes = extend({}, defaultAttributes, { + element: 'a', + href: this.download, + target: '_blank' + }); // Set download attribute for HTML5 only + + if (this.isHTML5) { + attributes.download = ''; + } + + const { + download + } = this.config.urls; + + if (!is.url(download) && this.isEmbed) { + extend(attributes, { + icon: `logo-${this.provider}`, + label: this.provider + }); + } + + container.appendChild(createButton.call(this, 'download', attributes)); + } // Toggle fullscreen button + + + if (control === 'fullscreen') { + container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes)); + } + }); // Set available quality levels + + if (this.isHTML5) { + setQualityMenu.call(this, html5.getQualityOptions.call(this)); + } + + setSpeedMenu.call(this); + return container; + }, + + // Insert controls + inject() { + // Sprite + if (this.config.loadSprite) { + const icon = controls.getIconUrl.call(this); // Only load external sprite using AJAX + + if (icon.cors) { + loadSprite(icon.url, 'sprite-plyr'); + } + } // Create a unique ID + + + this.id = Math.floor(Math.random() * 10000); // Null by default + + let container = null; + this.elements.controls = null; // Set template properties + + const props = { + id: this.id, + seektime: this.config.seekTime, + title: this.config.title + }; + let update = true; // If function, run it and use output + + if (is.function(this.config.controls)) { + this.config.controls = this.config.controls.call(this, props); + } // Convert falsy controls to empty array (primarily for empty strings) + + + if (!this.config.controls) { + this.config.controls = []; + } + + if (is.element(this.config.controls) || is.string(this.config.controls)) { + // HTMLElement or Non-empty string passed as the option + container = this.config.controls; + } else { + // Create controls + container = controls.create.call(this, { + id: this.id, + seektime: this.config.seekTime, + speed: this.speed, + quality: this.quality, + captions: captions.getLabel.call(this) // TODO: Looping + // loop: 'None', + + }); + update = false; + } // Replace props with their value + + + const replace = input => { + let result = input; + Object.entries(props).forEach(([key, value]) => { + result = replaceAll(result, `{${key}}`, value); + }); + return result; + }; // Update markup + + + if (update) { + if (is.string(this.config.controls)) { + container = replace(container); + } + } // Controls container + + + let target; // Inject to custom location + + if (is.string(this.config.selectors.controls.container)) { + target = document.querySelector(this.config.selectors.controls.container); + } // Inject into the container by default + + + if (!is.element(target)) { + target = this.elements.container; + } // Inject controls HTML (needs to be before captions, hence "afterbegin") + + + const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML'; + target[insertMethod]('afterbegin', container); // Find the elements if need be + + if (!is.element(this.elements.controls)) { + controls.findElements.call(this); + } // Add pressed property to buttons + + + if (!is.empty(this.elements.buttons)) { + const addProperty = button => { + const className = this.config.classNames.controlPressed; + Object.defineProperty(button, 'pressed', { + enumerable: true, + + get() { + return hasClass(button, className); + }, + + set(pressed = false) { + toggleClass(button, className, pressed); + } + + }); + }; // Toggle classname when pressed property is set + + + Object.values(this.elements.buttons).filter(Boolean).forEach(button => { + if (is.array(button) || is.nodeList(button)) { + Array.from(button).filter(Boolean).forEach(addProperty); + } else { + addProperty(button); + } + }); + } // Edge sometimes doesn't finish the paint so force a repaint + + + if (browser.isEdge) { + repaint(target); + } // Setup tooltips + + + if (this.config.tooltips.controls) { + const { + classNames, + selectors + } = this.config; + const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`; + const labels = getElements.call(this, selector); + Array.from(labels).forEach(label => { + toggleClass(label, this.config.classNames.hidden, false); + toggleClass(label, this.config.classNames.tooltip, true); + }); + } + } + +}; + +// ========================================================================== +/** + * Parse a string to a URL object + * @param {String} input - the URL to be parsed + * @param {Boolean} safe - failsafe parsing + */ + +function parseUrl(input, safe = true) { + let url = input; + + if (safe) { + const parser = document.createElement('a'); + parser.href = url; + url = parser.href; + } + + try { + return new URL(url); + } catch (_) { + return null; + } +} // Convert object to URLSearchParams + +function buildUrlParams(input) { + const params = new URLSearchParams(); + + if (is.object(input)) { + Object.entries(input).forEach(([key, value]) => { + params.set(key, value); + }); + } + + return params; +} + +// ========================================================================== +const captions = { + // Setup captions + setup() { + // Requires UI support + if (!this.supported.ui) { + return; + } // Only Vimeo and HTML5 video supported at this point + + + if (!this.isVideo || this.isYouTube || this.isHTML5 && !support.textTracks) { + // Clear menu and hide + if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) { + controls.setCaptionsMenu.call(this); + } + + return; + } // Inject the container + + + if (!is.element(this.elements.captions)) { + this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions)); + insertAfter(this.elements.captions, this.elements.wrapper); + } // Fix IE captions if CORS is used + // Fetch captions and inject as blobs instead (data URIs not supported!) + + + if (browser.isIE && window.URL) { + const elements = this.media.querySelectorAll('track'); + Array.from(elements).forEach(track => { + const src = track.getAttribute('src'); + const url = parseUrl(src); + + if (url !== null && url.hostname !== window.location.href.hostname && ['http:', 'https:'].includes(url.protocol)) { + fetch(src, 'blob').then(blob => { + track.setAttribute('src', window.URL.createObjectURL(blob)); + }).catch(() => { + removeElement(track); + }); + } + }); + } // Get and set initial data + // The "preferred" options are not realized unless / until the wanted language has a match + // * languages: Array of user's browser languages. + // * language: The language preferred by user settings or config + // * active: The state preferred by user settings or config + // * toggled: The real captions state + + + const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en']; + const languages = dedupe(browserLanguages.map(language => language.split('-')[0])); + let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase(); // Use first browser language when language is 'auto' + + if (language === 'auto') { + [language] = languages; + } + + let active = this.storage.get('captions'); + + if (!is.boolean(active)) { + ({ + active + } = this.config.captions); + } + + Object.assign(this.captions, { + toggled: false, + active, + language, + languages + }); // Watch changes to textTracks and update captions menu + + if (this.isHTML5) { + const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack'; + on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this)); + } // Update available languages in list next tick (the event must not be triggered before the listeners) + + + setTimeout(captions.update.bind(this), 0); + }, + + // Update available language options in settings based on tracks + update() { + const tracks = captions.getTracks.call(this, true); // Get the wanted language + + const { + active, + language, + meta, + currentTrackNode + } = this.captions; + const languageExists = Boolean(tracks.find(track => track.language === language)); // Handle tracks (add event listener and "pseudo"-default) + + if (this.isHTML5 && this.isVideo) { + tracks.filter(track => !meta.get(track)).forEach(track => { + this.debug.log('Track added', track); // Attempt to store if the original dom element was "default" + + meta.set(track, { + default: track.mode === 'showing' + }); // Turn off native caption rendering to avoid double captions + // Note: mode='hidden' forces a track to download. To ensure every track + // isn't downloaded at once, only 'showing' tracks should be reassigned + // eslint-disable-next-line no-param-reassign + + if (track.mode === 'showing') { + // eslint-disable-next-line no-param-reassign + track.mode = 'hidden'; + } // Add event listener for cue changes + + + on.call(this, track, 'cuechange', () => captions.updateCues.call(this)); + }); + } // Update language first time it matches, or if the previous matching track was removed + + + if (languageExists && this.language !== language || !tracks.includes(currentTrackNode)) { + captions.setLanguage.call(this, language); + captions.toggle.call(this, active && languageExists); + } // Enable or disable captions based on track length + + + if (this.elements) { + toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks)); + } // Update available languages in list + + + if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) { + controls.setCaptionsMenu.call(this); + } + }, + + // Toggle captions display + // Used internally for the toggleCaptions method, with the passive option forced to false + toggle(input, passive = true) { + // If there's no full support + if (!this.supported.ui) { + return; + } + + const { + toggled + } = this.captions; // Current state + + const activeClass = this.config.classNames.captions.active; // Get the next state + // If the method is called without parameter, toggle based on current value + + const active = is.nullOrUndefined(input) ? !toggled : input; // Update state and trigger event + + if (active !== toggled) { + // When passive, don't override user preferences + if (!passive) { + this.captions.active = active; + this.storage.set({ + captions: active + }); + } // Force language if the call isn't passive and there is no matching language to toggle to + + + if (!this.language && active && !passive) { + const tracks = captions.getTracks.call(this); + const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true); // Override user preferences to avoid switching languages if a matching track is added + + this.captions.language = track.language; // Set caption, but don't store in localStorage as user preference + + captions.set.call(this, tracks.indexOf(track)); + return; + } // Toggle button if it's enabled + + + if (this.elements.buttons.captions) { + this.elements.buttons.captions.pressed = active; + } // Add class hook + + + toggleClass(this.elements.container, activeClass, active); + this.captions.toggled = active; // Update settings menu + + controls.updateSetting.call(this, 'captions'); // Trigger event (not used internally) + + triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled'); + } // Wait for the call stack to clear before setting mode='hidden' + // on the active track - forcing the browser to download it + + + setTimeout(() => { + if (active && this.captions.toggled) { + this.captions.currentTrackNode.mode = 'hidden'; + } + }); + }, + + // Set captions by track index + // Used internally for the currentTrack setter with the passive option forced to false + set(index, passive = true) { + const tracks = captions.getTracks.call(this); // Disable captions if setting to -1 + + if (index === -1) { + captions.toggle.call(this, false, passive); + return; + } + + if (!is.number(index)) { + this.debug.warn('Invalid caption argument', index); + return; + } + + if (!(index in tracks)) { + this.debug.warn('Track not found', index); + return; + } + + if (this.captions.currentTrack !== index) { + this.captions.currentTrack = index; + const track = tracks[index]; + const { + language + } = track || {}; // Store reference to node for invalidation on remove + + this.captions.currentTrackNode = track; // Update settings menu + + controls.updateSetting.call(this, 'captions'); // When passive, don't override user preferences + + if (!passive) { + this.captions.language = language; + this.storage.set({ + language + }); + } // Handle Vimeo captions + + + if (this.isVimeo) { + this.embed.enableTextTrack(language); + } // Trigger event + + + triggerEvent.call(this, this.media, 'languagechange'); + } // Show captions + + + captions.toggle.call(this, true, passive); + + if (this.isHTML5 && this.isVideo) { + // If we change the active track while a cue is already displayed we need to update it + captions.updateCues.call(this); + } + }, + + // Set captions by language + // Used internally for the language setter with the passive option forced to false + setLanguage(input, passive = true) { + if (!is.string(input)) { + this.debug.warn('Invalid language argument', input); + return; + } // Normalize + + + const language = input.toLowerCase(); + this.captions.language = language; // Set currentTrack + + const tracks = captions.getTracks.call(this); + const track = captions.findTrack.call(this, [language]); + captions.set.call(this, tracks.indexOf(track), passive); + }, + + // Get current valid caption tracks + // If update is false it will also ignore tracks without metadata + // This is used to "freeze" the language options when captions.update is false + getTracks(update = false) { + // Handle media or textTracks missing or null + const tracks = Array.from((this.media || {}).textTracks || []); // For HTML5, use cache instead of current tracks when it exists (if captions.update is false) + // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata) + + return tracks.filter(track => !this.isHTML5 || update || this.captions.meta.has(track)).filter(track => ['captions', 'subtitles'].includes(track.kind)); + }, + + // Match tracks based on languages and get the first + findTrack(languages, force = false) { + const tracks = captions.getTracks.call(this); + + const sortIsDefault = track => Number((this.captions.meta.get(track) || {}).default); + + const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a)); + let track; + languages.every(language => { + track = sorted.find(t => t.language === language); + return !track; // Break iteration if there is a match + }); // If no match is found but is required, get first + + return track || (force ? sorted[0] : undefined); + }, + + // Get the current track + getCurrentTrack() { + return captions.getTracks.call(this)[this.currentTrack]; + }, + + // Get UI label for track + getLabel(track) { + let currentTrack = track; + + if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) { + currentTrack = captions.getCurrentTrack.call(this); + } + + if (is.track(currentTrack)) { + if (!is.empty(currentTrack.label)) { + return currentTrack.label; + } + + if (!is.empty(currentTrack.language)) { + return track.language.toUpperCase(); + } + + return i18n.get('enabled', this.config); + } + + return i18n.get('disabled', this.config); + }, + + // Update captions using current track's active cues + // Also optional array argument in case there isn't any track (ex: vimeo) + updateCues(input) { + // Requires UI + if (!this.supported.ui) { + return; + } + + if (!is.element(this.elements.captions)) { + this.debug.warn('No captions element to render to'); + return; + } // Only accept array or empty input + + + if (!is.nullOrUndefined(input) && !Array.isArray(input)) { + this.debug.warn('updateCues: Invalid input', input); + return; + } + + let cues = input; // Get cues from track + + if (!cues) { + const track = captions.getCurrentTrack.call(this); + cues = Array.from((track || {}).activeCues || []).map(cue => cue.getCueAsHTML()).map(getHTML); + } // Set new caption text + + + const content = cues.map(cueText => cueText.trim()).join('\n'); + const changed = content !== this.elements.captions.innerHTML; + + if (changed) { + // Empty the container and create a new child element + emptyElement(this.elements.captions); + const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption)); + caption.innerHTML = content; + this.elements.captions.appendChild(caption); // Trigger event + + triggerEvent.call(this, this.media, 'cuechange'); + } + } + +}; + +// ========================================================================== +// Plyr default config +// ========================================================================== +const defaults = { + // Disable + enabled: true, + // Custom media title + title: '', + // Logging to console + debug: false, + // Auto play (if supported) + autoplay: false, + // Only allow one media playing at once (vimeo only) + autopause: true, + // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present) + // TODO: Remove iosNative fullscreen option in favour of this (logic needs work) + playsinline: true, + // Default time to skip when rewind/fast forward + seekTime: 10, + // Default volume + volume: 1, + muted: false, + // Pass a custom duration + duration: null, + // Display the media duration on load in the current time position + // If you have opted to display both duration and currentTime, this is ignored + displayDuration: true, + // Invert the current time to be a countdown + invertTime: true, + // Clicking the currentTime inverts it's value to show time left rather than elapsed + toggleInvert: true, + // Force an aspect ratio + // The format must be `'w:h'` (e.g. `'16:9'`) + ratio: null, + // Click video container to play/pause + clickToPlay: true, + // Auto hide the controls + hideControls: true, + // Reset to start when playback ended + resetOnEnd: false, + // Disable the standard context menu + disableContextMenu: true, + // Sprite (for icons) + loadSprite: true, + iconPrefix: 'plyr', + iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg', + // Blank video (used to prevent errors on source change) + blankVideo: 'https://cdn.plyr.io/static/blank.mp4', + // Quality default + quality: { + default: 576, + // The options to display in the UI, if available for the source media + options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240], + forced: false, + onChange: null + }, + // Set loops + loop: { + active: false // start: null, + // end: null, + + }, + // Speed default and options to display + speed: { + selected: 1, + // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x) + options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4] + }, + // Keyboard shortcut settings + keyboard: { + focused: true, + global: false + }, + // Display tooltips + tooltips: { + controls: false, + seek: true + }, + // Captions settings + captions: { + active: false, + language: 'auto', + // Listen to new tracks added after Plyr is initialized. + // This is needed for streaming captions, but may result in unselectable options + update: false + }, + // Fullscreen settings + fullscreen: { + enabled: true, + // Allow fullscreen? + fallback: true, + // Fallback using full viewport/window + iosNative: false // Use the native fullscreen in iOS (disables custom controls) + // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode + // Non-ancestors of the player element will be ignored + // container: null, // defaults to the player element + + }, + // Local storage + storage: { + enabled: true, + key: 'plyr' + }, + // Default controls + controls: ['play-large', // 'restart', + // 'rewind', + 'play', // 'fast-forward', + 'progress', 'current-time', // 'duration', + 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', // 'download', + 'fullscreen'], + settings: ['captions', 'quality', 'speed'], + // Localisation + i18n: { + restart: 'Restart', + rewind: 'Rewind {seektime}s', + play: 'Play', + pause: 'Pause', + fastForward: 'Forward {seektime}s', + seek: 'Seek', + seekLabel: '{currentTime} of {duration}', + played: 'Played', + buffered: 'Buffered', + currentTime: 'Current time', + duration: 'Duration', + volume: 'Volume', + mute: 'Mute', + unmute: 'Unmute', + enableCaptions: 'Enable captions', + disableCaptions: 'Disable captions', + download: 'Download', + enterFullscreen: 'Enter fullscreen', + exitFullscreen: 'Exit fullscreen', + frameTitle: 'Player for {title}', + captions: 'Captions', + settings: 'Settings', + pip: 'PIP', + menuBack: 'Go back to previous menu', + speed: 'Speed', + normal: 'Normal', + quality: 'Quality', + loop: 'Loop', + start: 'Start', + end: 'End', + all: 'All', + reset: 'Reset', + disabled: 'Disabled', + enabled: 'Enabled', + advertisement: 'Ad', + qualityBadge: { + 2160: '4K', + 1440: 'HD', + 1080: 'HD', + 720: 'HD', + 576: 'SD', + 480: 'SD' + } + }, + // URLs + urls: { + download: null, + vimeo: { + sdk: 'https://player.vimeo.com/api/player.js', + iframe: 'https://player.vimeo.com/video/{0}?{1}', + api: 'https://vimeo.com/api/oembed.json?url={0}' + }, + youtube: { + sdk: 'https://www.youtube.com/iframe_api', + api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}' + }, + googleIMA: { + sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js' + } + }, + // Custom control listeners + listeners: { + seek: null, + play: null, + pause: null, + restart: null, + rewind: null, + fastForward: null, + mute: null, + volume: null, + captions: null, + download: null, + fullscreen: null, + pip: null, + airplay: null, + speed: null, + quality: null, + loop: null, + language: null + }, + // Events to watch and bubble + events: [// Events to watch on HTML5 media elements and bubble + // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events + 'ended', 'progress', 'stalled', 'playing', 'waiting', 'canplay', 'canplaythrough', 'loadstart', 'loadeddata', 'loadedmetadata', 'timeupdate', 'volumechange', 'play', 'pause', 'error', 'seeking', 'seeked', 'emptied', 'ratechange', 'cuechange', // Custom events + 'download', 'enterfullscreen', 'exitfullscreen', 'captionsenabled', 'captionsdisabled', 'languagechange', 'controlshidden', 'controlsshown', 'ready', // YouTube + 'statechange', // Quality + 'qualitychange', // Ads + 'adsloaded', 'adscontentpause', 'adscontentresume', 'adstarted', 'adsmidpoint', 'adscomplete', 'adsallcomplete', 'adsimpression', 'adsclick'], + // Selectors + // Change these to match your template if using custom HTML + selectors: { + editable: 'input, textarea, select, [contenteditable]', + container: '.plyr', + controls: { + container: null, + wrapper: '.plyr__controls' + }, + labels: '[data-plyr]', + buttons: { + play: '[data-plyr="play"]', + pause: '[data-plyr="pause"]', + restart: '[data-plyr="restart"]', + rewind: '[data-plyr="rewind"]', + fastForward: '[data-plyr="fast-forward"]', + mute: '[data-plyr="mute"]', + captions: '[data-plyr="captions"]', + download: '[data-plyr="download"]', + fullscreen: '[data-plyr="fullscreen"]', + pip: '[data-plyr="pip"]', + airplay: '[data-plyr="airplay"]', + settings: '[data-plyr="settings"]', + loop: '[data-plyr="loop"]' + }, + inputs: { + seek: '[data-plyr="seek"]', + volume: '[data-plyr="volume"]', + speed: '[data-plyr="speed"]', + language: '[data-plyr="language"]', + quality: '[data-plyr="quality"]' + }, + display: { + currentTime: '.plyr__time--current', + duration: '.plyr__time--duration', + buffer: '.plyr__progress__buffer', + loop: '.plyr__progress__loop', + // Used later + volume: '.plyr__volume--display' + }, + progress: '.plyr__progress', + captions: '.plyr__captions', + caption: '.plyr__caption' + }, + // Class hooks added to the player in different states + classNames: { + type: 'plyr--{0}', + provider: 'plyr--{0}', + video: 'plyr__video-wrapper', + embed: 'plyr__video-embed', + videoFixedRatio: 'plyr__video-wrapper--fixed-ratio', + embedContainer: 'plyr__video-embed__container', + poster: 'plyr__poster', + posterEnabled: 'plyr__poster-enabled', + ads: 'plyr__ads', + control: 'plyr__control', + controlPressed: 'plyr__control--pressed', + playing: 'plyr--playing', + paused: 'plyr--paused', + stopped: 'plyr--stopped', + loading: 'plyr--loading', + hover: 'plyr--hover', + tooltip: 'plyr__tooltip', + cues: 'plyr__cues', + hidden: 'plyr__sr-only', + hideControls: 'plyr--hide-controls', + isIos: 'plyr--is-ios', + isTouch: 'plyr--is-touch', + uiSupported: 'plyr--full-ui', + noTransition: 'plyr--no-transition', + display: { + time: 'plyr__time' + }, + menu: { + value: 'plyr__menu__value', + badge: 'plyr__badge', + open: 'plyr--menu-open' + }, + captions: { + enabled: 'plyr--captions-enabled', + active: 'plyr--captions-active' + }, + fullscreen: { + enabled: 'plyr--fullscreen-enabled', + fallback: 'plyr--fullscreen-fallback' + }, + pip: { + supported: 'plyr--pip-supported', + active: 'plyr--pip-active' + }, + airplay: { + supported: 'plyr--airplay-supported', + 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 + attributes: { + embed: { + provider: 'data-plyr-provider', + id: 'data-plyr-embed-id', + hash: 'data-plyr-embed-hash' + } + }, + // Advertisements plugin + // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio + 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, + // Custom settings from Plyr + customControls: true, + referrerPolicy: null, + // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy + // Whether the owner of the video has a Pro or Business account + // (which allows us to properly hide controls without CSS hacks, etc) + premium: false + }, + // YouTube plugin + youtube: { + 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) + // Custom settings from Plyr + customControls: true, + noCookie: false // Whether to use an alternative version of YouTube without cookies + + } +}; + +// ========================================================================== +// Plyr states +// ========================================================================== +const pip = { + active: 'picture-in-picture', + inactive: 'inline' +}; + +// ========================================================================== +// Plyr supported types and providers +// ========================================================================== +const providers = { + html5: 'html5', + youtube: 'youtube', + vimeo: 'vimeo' +}; +const types = { + audio: 'audio', + video: 'video' +}; +/** + * Get provider by URL + * @param {String} url + */ + +function getProviderByUrl(url) { + // YouTube + if (/^(https?:\/\/)?(www\.)?(youtube\.com|youtube-nocookie\.com|youtu\.?be)\/.+$/.test(url)) { + return providers.youtube; + } // Vimeo + + + if (/^https?:\/\/player.vimeo.com\/video\/\d{0,9}(?=\b|\/)/.test(url)) { + return providers.vimeo; + } + + return null; +} + +// ========================================================================== +// Console wrapper +// ========================================================================== +const noop = () => {}; + +class Console { + constructor(enabled = false) { + this.enabled = window.console && enabled; + + if (this.enabled) { + this.log('Debugging enabled'); + } + } + + get log() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.log, console) : noop; + } + + get warn() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop; + } + + get error() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.error, console) : noop; + } + +} + +class Fullscreen { + constructor(player) { + _defineProperty$1(this, "onChange", () => { + if (!this.enabled) { + return; + } // Update toggle button + + + const button = this.player.elements.buttons.fullscreen; + + if (is.element(button)) { + button.pressed = this.active; + } // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up + + + const target = this.target === this.player.media ? this.target : this.player.elements.container; // Trigger an event + + triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true); + }); + + _defineProperty$1(this, "toggleFallback", (toggle = false) => { + // Store or restore scroll position + if (toggle) { + this.scrollPosition = { + x: window.scrollX || 0, + y: window.scrollY || 0 + }; + } else { + window.scrollTo(this.scrollPosition.x, this.scrollPosition.y); + } // Toggle scroll + + + document.body.style.overflow = toggle ? 'hidden' : ''; // Toggle class hook + + toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle); // Force full viewport on iPhone X+ + + if (browser.isIos) { + let viewport = document.head.querySelector('meta[name="viewport"]'); + const property = 'viewport-fit=cover'; // Inject the viewport meta if required + + if (!viewport) { + viewport = document.createElement('meta'); + viewport.setAttribute('name', 'viewport'); + } // Check if the property already exists + + + const hasProperty = is.string(viewport.content) && viewport.content.includes(property); + + if (toggle) { + this.cleanupViewport = !hasProperty; + + if (!hasProperty) { + viewport.content += `,${property}`; + } + } else if (this.cleanupViewport) { + viewport.content = viewport.content.split(',').filter(part => part.trim() !== property).join(','); + } + } // Toggle button and fire events + + + this.onChange(); + }); + + _defineProperty$1(this, "trapFocus", event => { + // Bail if iOS, not active, not the tab key + if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) { + return; + } // Get the current focused element + + + const focused = document.activeElement; + const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]'); + const [first] = focusable; + const last = focusable[focusable.length - 1]; + + if (focused === last && !event.shiftKey) { + // Move focus to first element that can be tabbed if Shift isn't used + first.focus(); + event.preventDefault(); + } else if (focused === first && event.shiftKey) { + // Move focus to last element that can be tabbed if Shift is used + last.focus(); + event.preventDefault(); + } + }); + + _defineProperty$1(this, "update", () => { + if (this.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'); + } // Add styling hook to show button + + + toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled); + }); + + _defineProperty$1(this, "enter", () => { + if (!this.enabled) { + return; + } // iOS native fullscreen doesn't need the request step + + + if (browser.isIos && this.player.config.fullscreen.iosNative) { + if (this.player.isVimeo) { + this.player.embed.requestFullscreen(); + } else { + this.target.webkitEnterFullscreen(); + } + } else if (!Fullscreen.native || this.forceFallback) { + this.toggleFallback(true); + } else if (!this.prefix) { + this.target.requestFullscreen({ + navigationUI: 'hide' + }); + } else if (!is.empty(this.prefix)) { + this.target[`${this.prefix}Request${this.property}`](); + } + }); + + _defineProperty$1(this, "exit", () => { + if (!this.enabled) { + return; + } // iOS native fullscreen + + + if (browser.isIos && this.player.config.fullscreen.iosNative) { + this.target.webkitExitFullscreen(); + silencePromise(this.player.play()); + } else if (!Fullscreen.native || this.forceFallback) { + this.toggleFallback(false); + } else if (!this.prefix) { + (document.cancelFullScreen || document.exitFullscreen).call(document); + } else if (!is.empty(this.prefix)) { + const action = this.prefix === 'moz' ? 'Cancel' : 'Exit'; + document[`${this.prefix}${action}${this.property}`](); + } + }); + + _defineProperty$1(this, "toggle", () => { + if (!this.active) { + this.enter(); + } else { + this.exit(); + } + }); + + // Keep reference to parent + this.player = player; // Get prefix + + this.prefix = Fullscreen.prefix; + this.property = Fullscreen.property; // 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'; // Get the fullscreen element + // Checks container is an ancestor, defaults to null + + this.player.elements.fullscreen = player.config.fullscreen.container && closest$1(this.player.elements.container, player.config.fullscreen.container); // Register event listeners + // Handle event (incase user presses escape etc) + + on.call(this.player, document, this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`, () => { + // TODO: Filter for target?? + this.onChange(); + }); // Fullscreen toggle on double click + + on.call(this.player, this.player.elements.container, 'dblclick', event => { + // Ignore double click in controls + if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) { + return; + } + + this.player.listeners.proxy(event, this.toggle, 'fullscreen'); + }); // Tap focus when in fullscreen + + on.call(this, this.player.elements.container, 'keydown', event => this.trapFocus(event)); // Update the UI + + this.update(); // this.toggle = this.toggle.bind(this); + } // Determine if native supported + + + static get native() { + return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled); + } // If we're actually using native + + + get usingNative() { + return Fullscreen.native && !this.forceFallback; + } // Get the prefix for handlers + + + static get prefix() { + // No prefix + if (is.function(document.exitFullscreen)) { + return ''; + } // Check for fullscreen support by vendor prefix + + + let value = ''; + const prefixes = ['webkit', 'moz', 'ms']; + prefixes.some(pre => { + if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) { + value = pre; + return true; + } + + return false; + }); + return value; + } + + static get property() { + return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen'; + } // Determine if fullscreen is enabled + + + get enabled() { + return (Fullscreen.native || this.player.config.fullscreen.fallback) && this.player.config.fullscreen.enabled && this.player.supported.ui && this.player.isVideo; + } // Get active state + + + get active() { + if (!this.enabled) { + return false; + } // Fallback using classname + + + if (!Fullscreen.native || this.forceFallback) { + return hasClass(this.target, this.player.config.classNames.fullscreen.fallback); + } + + const element = !this.prefix ? this.target.getRootNode().fullscreenElement : this.target.getRootNode()[`${this.prefix}${this.property}Element`]; + return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target; + } // Get target element + + + get target() { + return browser.isIos && this.player.config.fullscreen.iosNative ? this.player.media : this.player.elements.fullscreen || this.player.elements.container; + } + +} + +// ========================================================================== +// Load image avoiding xhr/fetch CORS issues +// Server status can't be obtained this way unfortunately, so this uses "naturalWidth" to determine if the image has loaded +// By default it checks if it is at least 1px, but you can add a second argument to change this +// ========================================================================== +function loadImage(src, minWidth = 1) { + return new Promise((resolve, reject) => { + const image = new Image(); + + const handler = () => { + delete image.onload; + delete image.onerror; + (image.naturalWidth >= minWidth ? resolve : reject)(image); + }; + + Object.assign(image, { + onload: handler, + onerror: handler, + src + }); + }); +} + +// ========================================================================== +const ui = { + addStyleHook() { + toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true); + toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui); + }, + + // Toggle native HTML5 media controls + toggleNativeControls(toggle = false) { + if (toggle && this.isHTML5) { + this.media.setAttribute('controls', ''); + } else { + this.media.removeAttribute('controls'); + } + }, + + // Setup the UI + build() { + // Re-attach media element listeners + // TODO: Use event bubbling? + this.listeners.media(); // Don't setup interface if no support + + if (!this.supported.ui) { + this.debug.warn(`Basic support only for ${this.provider} ${this.type}`); // Restore native controls + + ui.toggleNativeControls.call(this, true); // Bail + + return; + } // Inject custom controls if not present + + + if (!is.element(this.elements.controls)) { + // Inject custom controls + controls.inject.call(this); // Re-attach control listeners + + this.listeners.controls(); + } // Remove native controls + + + ui.toggleNativeControls.call(this); // Setup captions for HTML5 + + if (this.isHTML5) { + captions.setup.call(this); + } // Reset volume + + + this.volume = null; // Reset mute state + + this.muted = null; // Reset loop state + + this.loop = null; // Reset quality setting + + this.quality = null; // Reset speed + + this.speed = null; // Reset volume display + + controls.updateVolume.call(this); // Reset time display + + controls.timeUpdate.call(this); // Reset duration display + + controls.durationUpdate.call(this); // Update the UI + + ui.checkPlaying.call(this); // Check for picture-in-picture support + + toggleClass(this.elements.container, this.config.classNames.pip.supported, support.pip && this.isHTML5 && this.isVideo); // Check for airplay support + + toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5); // Add iOS class + + toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos); // Add touch class + + toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch); // Ready for API calls + + this.ready = true; // Ready event at end of execution stack + + setTimeout(() => { + triggerEvent.call(this, this.media, 'ready'); + }, 0); // Set the title + + ui.setTitle.call(this); // Assure the poster image is set, if the property was added before the element was created + + if (this.poster) { + ui.setPoster.call(this, this.poster, false).catch(() => {}); + } // Manually set the duration if user has overridden it. + // The event listeners for it doesn't get called if preload is disabled (#701) + + + if (this.config.duration) { + controls.durationUpdate.call(this); + } + }, + + // Setup aria attribute for play and iframe title + setTitle() { + // Find the current text + let label = i18n.get('play', this.config); // If there's a media title set, use that for the label + + if (is.string(this.config.title) && !is.empty(this.config.title)) { + label += `, ${this.config.title}`; + } // If there's a play button, set label + + + Array.from(this.elements.buttons.play || []).forEach(button => { + button.setAttribute('aria-label', label); + }); // Set iframe title + // https://github.com/sampotts/plyr/issues/124 + + if (this.isEmbed) { + const iframe = getElement.call(this, 'iframe'); + + if (!is.element(iframe)) { + return; + } // Default to media type + + + const title = !is.empty(this.config.title) ? this.config.title : 'video'; + const format = i18n.get('frameTitle', this.config); + iframe.setAttribute('title', format.replace('{title}', title)); + } + }, + + // Toggle poster + togglePoster(enable) { + toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable); + }, + + // Set the poster image (async) + // Used internally for the poster setter, with the passive option forced to false + setPoster(poster, passive = true) { + // Don't override if call is passive + if (passive && this.poster) { + return Promise.reject(new Error('Poster already set')); + } // Set property synchronously to respect the call order + + + this.media.setAttribute('data-poster', poster); // Show the poster + + this.elements.poster.removeAttribute('hidden'); // Wait until ui is ready + + return ready.call(this) // Load image + .then(() => loadImage(poster)).catch(error => { + // Hide poster on error unless it's been set by another call + if (poster === this.poster) { + ui.togglePoster.call(this, false); + } // Rethrow + + + throw error; + }).then(() => { + // Prevent race conditions + if (poster !== this.poster) { + throw new Error('setPoster cancelled by later call to setPoster'); + } + }).then(() => { + Object.assign(this.elements.poster.style, { + backgroundImage: `url('${poster}')`, + // Reset backgroundSize as well (since it can be set to "cover" for padded thumbnails for youtube) + backgroundSize: '' + }); + ui.togglePoster.call(this, true); + return poster; + }); + }, + + // Check playing state + checkPlaying(event) { + // Class hooks + toggleClass(this.elements.container, this.config.classNames.playing, this.playing); + toggleClass(this.elements.container, this.config.classNames.paused, this.paused); + toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped); // Set state + + Array.from(this.elements.buttons.play || []).forEach(target => { + Object.assign(target, { + pressed: this.playing + }); + target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config)); + }); // Only update controls on non timeupdate events + + if (is.event(event) && event.type === 'timeupdate') { + return; + } // Toggle controls + + + ui.toggleControls.call(this); + }, + + // Check if media is loading + checkLoading(event) { + this.loading = ['stalled', 'waiting'].includes(event.type); // Clear timer + + clearTimeout(this.timers.loading); // Timer to prevent flicker when seeking + + this.timers.loading = setTimeout(() => { + // Update progress bar loading class state + toggleClass(this.elements.container, this.config.classNames.loading, this.loading); // Update controls visibility + + ui.toggleControls.call(this); + }, this.loading ? 250 : 0); + }, + + // Toggle controls based on state and `force` argument + toggleControls(force) { + const { + controls: controlsElement + } = this.elements; + + if (controlsElement && this.config.hideControls) { + // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.) + const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now(); // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide + + this.toggleControls(Boolean(force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek)); + } + }, + + // Migrate any custom properties from the media to the parent + migrateStyles() { + // Loop through values (as they are the keys when the object is spread 🤔) + Object.values({ ...this.media.style + }) // We're only fussed about Plyr specific properties + .filter(key => !is.empty(key) && is.string(key) && key.startsWith('--plyr')).forEach(key => { + // Set on the container + this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key)); // Clean up from media element + + this.media.style.removeProperty(key); + }); // Remove attribute if empty + + if (is.empty(this.media.style)) { + this.media.removeAttribute('style'); + } + } + +}; + +class Listeners { + constructor(_player) { + _defineProperty$1(this, "firstTouch", () => { + const { + player + } = this; + const { + elements + } = player; + player.touch = true; // Add touch class + + toggleClass(elements.container, player.config.classNames.isTouch, true); + }); + + _defineProperty$1(this, "setTabFocus", event => { + const { + player + } = this; + const { + elements + } = player; + clearTimeout(this.focusTimer); // Ignore any key other than tab + + if (event.type === 'keydown' && event.which !== 9) { + return; + } // Store reference to event timeStamp + + + if (event.type === 'keydown') { + this.lastKeyDown = event.timeStamp; + } // Remove current classes + + + const removeCurrent = () => { + const className = player.config.classNames.tabFocus; + const current = getElements.call(player, `.${className}`); + toggleClass(current, className, false); + }; // Determine if a key was pressed to trigger this event + + + const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20; // Ignore focus events if a key was pressed prior + + if (event.type === 'focus' && !wasKeyDown) { + return; + } // Remove all current + + + removeCurrent(); // Delay the adding of classname until the focus has changed + // This event fires before the focusin event + + if (event.type !== 'focusout') { + this.focusTimer = setTimeout(() => { + const focused = document.activeElement; // Ignore if current focus element isn't inside the player + + if (!elements.container.contains(focused)) { + return; + } + + toggleClass(document.activeElement, player.config.classNames.tabFocus, true); + }, 10); + } + }); + + _defineProperty$1(this, "global", (toggle = true) => { + const { + player + } = this; // Keyboard shortcuts + + if (player.config.keyboard.global) { + toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false); + } // Click anywhere closes menu + + + toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle); // Detect touch by events + + once.call(player, document.body, 'touchstart', this.firstTouch); // Tab focus detection + + toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true); + }); + + _defineProperty$1(this, "container", () => { + const { + player + } = this; + const { + config, + elements, + timers + } = player; // Keyboard shortcuts + + if (!config.keyboard.global && config.keyboard.focused) { + on.call(player, elements.container, 'keydown keyup', this.handleKey, false); + } // Toggle controls on mouse events and entering fullscreen + + + on.call(player, elements.container, 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen', event => { + const { + controls: controlsElement + } = elements; // Remove button states for fullscreen + + if (controlsElement && event.type === 'enterfullscreen') { + controlsElement.pressed = false; + controlsElement.hover = false; + } // Show, then hide after a timeout unless another control event occurs + + + const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type); + let delay = 0; + + if (show) { + ui.toggleControls.call(player, true); // Use longer timeout for touch devices + + delay = player.touch ? 3000 : 2000; + } // Clear timer + + + clearTimeout(timers.controls); // Set new timer to prevent flicker when seeking + + timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay); + }); // Set a gutter for Vimeo + + const setGutter = () => { + if (!player.isVimeo || player.config.vimeo.premium) { + return; + } + + const target = elements.wrapper; + const { + active + } = player.fullscreen; + const [videoWidth, videoHeight] = getAspectRatio.call(player); + const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`); // If not active, remove styles + + if (!active) { + if (useNativeAspectRatio) { + target.style.width = null; + target.style.height = null; + } else { + target.style.maxWidth = null; + target.style.margin = null; + } + + return; + } // Determine which dimension will overflow and constrain view + + + const [viewportWidth, viewportHeight] = getViewportSize(); + const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight; + + if (useNativeAspectRatio) { + target.style.width = overflow ? 'auto' : '100%'; + target.style.height = overflow ? '100%' : 'auto'; + } else { + target.style.maxWidth = overflow ? `${viewportHeight / videoHeight * videoWidth}px` : null; + target.style.margin = overflow ? '0 auto' : null; + } + }; // Handle resizing + + + const resized = () => { + clearTimeout(timers.resized); + timers.resized = setTimeout(setGutter, 50); + }; + + on.call(player, elements.container, 'enterfullscreen exitfullscreen', event => { + const { + target + } = player.fullscreen; // Ignore events not from target + + if (target !== elements.container) { + return; + } // If it's not an embed and no ratio specified + + + if (!player.isEmbed && is.empty(player.config.ratio)) { + return; + } // Set Vimeo gutter + + + setGutter(); // Watch for resizes + + const method = event.type === 'enterfullscreen' ? on : off; + method.call(player, window, 'resize', resized); + }); + }); + + _defineProperty$1(this, "media", () => { + const { + player + } = this; + const { + elements + } = player; // Time change on media + + on.call(player, player.media, 'timeupdate seeking seeked', event => controls.timeUpdate.call(player, event)); // Display duration + + on.call(player, player.media, 'durationchange loadeddata loadedmetadata', event => controls.durationUpdate.call(player, event)); // Handle the media finishing + + on.call(player, player.media, 'ended', () => { + // Show poster on end + if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) { + // Restart + player.restart(); // Call pause otherwise IE11 will start playing the video again + + player.pause(); + } + }); // Check for buffer progress + + on.call(player, player.media, 'progress playing seeking seeked', event => controls.updateProgress.call(player, event)); // Handle volume changes + + on.call(player, player.media, 'volumechange', event => controls.updateVolume.call(player, event)); // Handle play/pause + + on.call(player, player.media, 'playing play pause ended emptied timeupdate', event => ui.checkPlaying.call(player, event)); // Loading state + + on.call(player, player.media, 'waiting canplay seeked playing', event => ui.checkLoading.call(player, event)); // Click video + + if (player.supported.ui && player.config.clickToPlay && !player.isAudio) { + // Re-fetch the wrapper + const wrapper = getElement.call(player, `.${player.config.classNames.video}`); // Bail if there's no wrapper (this should never happen) + + if (!is.element(wrapper)) { + return; + } // On click play, pause or restart + + + on.call(player, elements.container, 'click', event => { + const targets = [elements.container, wrapper]; // Ignore if click if not container or in video wrapper + + if (!targets.includes(event.target) && !wrapper.contains(event.target)) { + return; + } // Touch devices will just show controls (if hidden) + + + if (player.touch && player.config.hideControls) { + return; + } + + if (player.ended) { + this.proxy(event, player.restart, 'restart'); + this.proxy(event, () => { + silencePromise(player.play()); + }, 'play'); + } else { + this.proxy(event, () => { + silencePromise(player.togglePlay()); + }, 'play'); + } + }); + } // Disable right click + + + if (player.supported.ui && player.config.disableContextMenu) { + on.call(player, elements.wrapper, 'contextmenu', event => { + event.preventDefault(); + }, false); + } // Volume change + + + on.call(player, player.media, 'volumechange', () => { + // Save to storage + player.storage.set({ + volume: player.volume, + muted: player.muted + }); + }); // Speed change + + on.call(player, player.media, 'ratechange', () => { + // Update UI + controls.updateSetting.call(player, 'speed'); // Save to storage + + player.storage.set({ + speed: player.speed + }); + }); // Quality change + + on.call(player, player.media, 'qualitychange', event => { + // Update UI + controls.updateSetting.call(player, 'quality', null, event.detail.quality); + }); // Update download link when ready and if quality changes + + on.call(player, player.media, 'ready qualitychange', () => { + controls.setDownloadUrl.call(player); + }); // Proxy events to container + // Bubble up key events for Edge + + const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' '); + on.call(player, player.media, proxyEvents, event => { + let { + detail = {} + } = event; // Get error details from media + + if (event.type === 'error') { + detail = player.media.error; + } + + triggerEvent.call(player, elements.container, event.type, true, detail); + }); + }); + + _defineProperty$1(this, "proxy", (event, defaultHandler, customHandlerKey) => { + const { + player + } = this; + const customHandler = player.config.listeners[customHandlerKey]; + const hasCustomHandler = is.function(customHandler); + let returned = true; // Execute custom handler + + if (hasCustomHandler) { + returned = customHandler.call(player, event); + } // Only call default handler if not prevented in custom handler + + + if (returned !== false && is.function(defaultHandler)) { + defaultHandler.call(player, event); + } + }); + + _defineProperty$1(this, "bind", (element, type, defaultHandler, customHandlerKey, passive = true) => { + const { + player + } = this; + const customHandler = player.config.listeners[customHandlerKey]; + const hasCustomHandler = is.function(customHandler); + on.call(player, element, type, event => this.proxy(event, defaultHandler, customHandlerKey), passive && !hasCustomHandler); + }); + + _defineProperty$1(this, "controls", () => { + const { + player + } = this; + const { + elements + } = player; // IE doesn't support input event, so we fallback to change + + const inputEvent = browser.isIE ? 'change' : 'input'; // Play/pause toggle + + if (elements.buttons.play) { + Array.from(elements.buttons.play).forEach(button => { + this.bind(button, 'click', () => { + silencePromise(player.togglePlay()); + }, 'play'); + }); + } // Pause + + + this.bind(elements.buttons.restart, 'click', player.restart, 'restart'); // Rewind + + this.bind(elements.buttons.rewind, 'click', () => { + // Record seek time so we can prevent hiding controls for a few seconds after rewind + player.lastSeekTime = Date.now(); + player.rewind(); + }, 'rewind'); // Rewind + + this.bind(elements.buttons.fastForward, 'click', () => { + // Record seek time so we can prevent hiding controls for a few seconds after fast forward + player.lastSeekTime = Date.now(); + player.forward(); + }, 'fastForward'); // Mute toggle + + this.bind(elements.buttons.mute, 'click', () => { + player.muted = !player.muted; + }, 'mute'); // Captions toggle + + this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions()); // Download + + this.bind(elements.buttons.download, 'click', () => { + triggerEvent.call(player, player.media, 'download'); + }, 'download'); // Fullscreen toggle + + this.bind(elements.buttons.fullscreen, 'click', () => { + player.fullscreen.toggle(); + }, 'fullscreen'); // Picture-in-Picture + + this.bind(elements.buttons.pip, 'click', () => { + player.pip = 'toggle'; + }, 'pip'); // Airplay + + this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay'); // Settings menu - click toggle + + this.bind(elements.buttons.settings, 'click', event => { + // Prevent the document click listener closing the menu + event.stopPropagation(); + event.preventDefault(); + controls.toggleMenu.call(player, event); + }, null, false); // Can't be passive as we're preventing default + // Settings menu - keyboard toggle + // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus + // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143 + + this.bind(elements.buttons.settings, 'keyup', event => { + const code = event.which; // We only care about space and return + + if (![13, 32].includes(code)) { + return; + } // Because return triggers a click anyway, all we need to do is set focus + + + if (code === 13) { + controls.focusFirstMenuItem.call(player, null, true); + return; + } // Prevent scroll + + + event.preventDefault(); // Prevent playing video (Firefox) + + event.stopPropagation(); // Toggle menu + + controls.toggleMenu.call(player, event); + }, null, false // Can't be passive as we're preventing default + ); // Escape closes menu + + this.bind(elements.settings.menu, 'keydown', event => { + if (event.which === 27) { + controls.toggleMenu.call(player, event); + } + }); // Set range input alternative "value", which matches the tooltip time (#954) + + this.bind(elements.inputs.seek, 'mousedown mousemove', event => { + const rect = elements.progress.getBoundingClientRect(); + const percent = 100 / rect.width * (event.pageX - rect.left); + event.currentTarget.setAttribute('seek-value', percent); + }); // Pause while seeking + + this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', event => { + const seek = event.currentTarget; + const code = event.keyCode ? event.keyCode : event.which; + const attribute = 'play-on-seeked'; + + if (is.keyboardEvent(event) && code !== 39 && code !== 37) { + return; + } // Record seek time so we can prevent hiding controls for a few seconds after seek + + + player.lastSeekTime = Date.now(); // Was playing before? + + const play = seek.hasAttribute(attribute); // Done seeking + + const done = ['mouseup', 'touchend', 'keyup'].includes(event.type); // If we're done seeking and it was playing, resume playback + + if (play && done) { + seek.removeAttribute(attribute); + silencePromise(player.play()); + } else if (!done && player.playing) { + seek.setAttribute(attribute, ''); + player.pause(); + } + }); // Fix range inputs on iOS + // Super weird iOS bug where after you interact with an <input type="range">, + // it takes over further interactions on the page. This is a hack + + if (browser.isIos) { + const inputs = getElements.call(player, 'input[type="range"]'); + Array.from(inputs).forEach(input => this.bind(input, inputEvent, event => repaint(event.target))); + } // Seek + + + this.bind(elements.inputs.seek, inputEvent, event => { + const seek = event.currentTarget; // If it exists, use seek-value instead of "value" for consistency with tooltip time (#954) + + let seekTo = seek.getAttribute('seek-value'); + + if (is.empty(seekTo)) { + seekTo = seek.value; + } + + seek.removeAttribute('seek-value'); + player.currentTime = seekTo / seek.max * player.duration; + }, 'seek'); // Seek tooltip + + this.bind(elements.progress, 'mouseenter mouseleave mousemove', event => 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 touchend 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 => { + this.bind(element, 'input', event => controls.updateRangeFill.call(player, event.target)); + }); + } // Current time invert + // Only if one time element is used for both currentTime and duration + + + if (player.config.toggleInvert && !is.element(elements.display.duration)) { + this.bind(elements.display.currentTime, 'click', () => { + // Do nothing if we're at the start + if (player.currentTime === 0) { + return; + } + + player.config.invertTime = !player.config.invertTime; + controls.timeUpdate.call(player); + }); + } // Volume + + + this.bind(elements.inputs.volume, inputEvent, event => { + player.volume = event.target.value; + }, 'volume'); // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting) + + this.bind(elements.controls, 'mouseenter mouseleave', event => { + elements.controls.hover = !player.touch && event.type === 'mouseenter'; + }); // Also update controls.hover state for any non-player children of fullscreen element (as above) + + if (elements.fullscreen) { + Array.from(elements.fullscreen.children).filter(c => !c.contains(elements.container)).forEach(child => { + this.bind(child, 'mouseenter mouseleave', event => { + if (elements.controls) { + elements.controls.hover = !player.touch && event.type === 'mouseenter'; + } + }); + }); + } // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting) + + + this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', event => { + elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type); + }); // Show controls when they receive focus (e.g., when using keyboard tab key) + + this.bind(elements.controls, 'focusin', () => { + const { + config, + timers + } = player; // Skip transition to prevent focus from scrolling the parent element + + toggleClass(elements.controls, config.classNames.noTransition, true); // Toggle + + ui.toggleControls.call(player, true); // Restore transition + + setTimeout(() => { + toggleClass(elements.controls, config.classNames.noTransition, false); + }, 0); // Delay a little more for mouse users + + const delay = this.touch ? 3000 : 4000; // Clear timer + + clearTimeout(timers.controls); // Hide again after delay + + timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay); + }); // Mouse wheel for volume + + this.bind(elements.inputs.volume, 'wheel', event => { + // Detect "natural" scroll - suppored on OS X Safari only + // Other browsers on OS X will be inverted until support improves + const inverted = event.webkitDirectionInvertedFromDevice; // Get delta from event. Invert if `inverted` is true + + const [x, y] = [event.deltaX, -event.deltaY].map(value => inverted ? -value : value); // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta) + + const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y); // Change the volume by 2% + + player.increaseVolume(direction / 50); // Don't break page scrolling at max and min + + const { + volume + } = player.media; + + if (direction === 1 && volume < 1 || direction === -1 && volume > 0) { + event.preventDefault(); + } + }, 'volume', false); + }); + + this.player = _player; + this.lastKey = null; + this.focusTimer = null; + this.lastKeyDown = null; + this.handleKey = this.handleKey.bind(this); + this.toggleMenu = this.toggleMenu.bind(this); + this.setTabFocus = this.setTabFocus.bind(this); + this.firstTouch = this.firstTouch.bind(this); + } // Handle key presses + + + handleKey(event) { + const { + player + } = this; + const { + elements + } = player; + const code = event.keyCode ? event.keyCode : event.which; + const pressed = event.type === 'keydown'; + const repeat = pressed && code === this.lastKey; // Bail if a modifier key is set + + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { + return; + } // If the event is bubbled from the media element + // Firefox doesn't get the keycode for whatever reason + + + if (!is.number(code)) { + return; + } // Seek by the number keys + + + const seekByKey = () => { + // Divide the max duration into 10th's and times by the number value + player.currentTime = player.duration / 10 * (code - 48); + }; // Handle the key on keydown + // Reset on keyup + + + if (pressed) { + // Check focused element + // and if the focused element is not editable (e.g. text input) + // and any that accept key input http://webaim.org/techniques/keyboard/ + const focused = document.activeElement; + + if (is.element(focused)) { + const { + editable + } = player.config.selectors; + const { + seek + } = elements.inputs; + + if (focused !== seek && matches(focused, editable)) { + return; + } + + if (event.which === 32 && matches(focused, 'button, [role^="menuitem"]')) { + return; + } + } // Which keycodes should we prevent default + + + const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79]; // If the code is found prevent default (e.g. prevent scrolling for arrows) + + if (preventDefault.includes(code)) { + event.preventDefault(); + event.stopPropagation(); + } + + switch (code) { + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + // 0-9 + if (!repeat) { + seekByKey(); + } + + break; + + case 32: + case 75: + // Space and K key + if (!repeat) { + silencePromise(player.togglePlay()); + } + + break; + + case 38: + // Arrow up + player.increaseVolume(0.1); + break; + + case 40: + // Arrow down + player.decreaseVolume(0.1); + break; + + case 77: + // M key + if (!repeat) { + player.muted = !player.muted; + } + + break; + + case 39: + // Arrow forward + player.forward(); + break; + + case 37: + // Arrow back + player.rewind(); + break; + + case 70: + // F key + player.fullscreen.toggle(); + break; + + case 67: + // C key + if (!repeat) { + player.toggleCaptions(); + } + + break; + + case 76: + // L key + player.loop = !player.loop; + break; + } // Escape is handle natively when in full screen + // So we only need to worry about non native + + + if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) { + player.fullscreen.toggle(); + } // Store last code for next cycle + + + this.lastKey = code; + } else { + this.lastKey = null; + } + } // Toggle menu + + + toggleMenu(event) { + controls.toggleMenu.call(this.player, event); + } // Device is touch enabled + + +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var loadjs_umd = createCommonjsModule(function (module, exports) { + (function (root, factory) { + { + module.exports = factory(); + } + })(commonjsGlobal, function () { + /** + * Global dependencies. + * @global {Object} document - DOM + */ + var devnull = function () {}, + bundleIdCache = {}, + bundleResultCache = {}, + bundleCallbackQueue = {}; + /** + * Subscribe to bundle load event. + * @param {string[]} bundleIds - Bundle ids + * @param {Function} callbackFn - The callback function + */ + + + function subscribe(bundleIds, callbackFn) { + // listify + bundleIds = bundleIds.push ? bundleIds : [bundleIds]; + var depsNotFound = [], + i = bundleIds.length, + numWaiting = i, + fn, + bundleId, + r, + q; // define callback function + + fn = function (bundleId, pathsNotFound) { + if (pathsNotFound.length) depsNotFound.push(bundleId); + numWaiting--; + if (!numWaiting) callbackFn(depsNotFound); + }; // register callback + + + while (i--) { + bundleId = bundleIds[i]; // execute callback if in result cache + + r = bundleResultCache[bundleId]; + + if (r) { + fn(bundleId, r); + continue; + } // add to callback queue + + + q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || []; + q.push(fn); + } + } + /** + * Publish bundle load event. + * @param {string} bundleId - Bundle id + * @param {string[]} pathsNotFound - List of files not found + */ + + + function publish(bundleId, pathsNotFound) { + // exit if id isn't defined + if (!bundleId) return; + var q = bundleCallbackQueue[bundleId]; // cache result + + bundleResultCache[bundleId] = pathsNotFound; // exit if queue is empty + + if (!q) return; // empty callback queue + + while (q.length) { + q[0](bundleId, pathsNotFound); + q.splice(0, 1); + } + } + /** + * Execute callbacks. + * @param {Object or Function} args - The callback args + * @param {string[]} depsNotFound - List of dependencies not found + */ + + + function executeCallbacks(args, depsNotFound) { + // accept function as argument + if (args.call) args = { + success: args + }; // success and error callbacks + + if (depsNotFound.length) (args.error || devnull)(depsNotFound);else (args.success || devnull)(args); + } + /** + * Load individual file. + * @param {string} path - The file path + * @param {Function} callbackFn - The callback function + */ + + + function loadFile(path, callbackFn, args, numTries) { + var doc = document, + async = args.async, + maxTries = (args.numRetries || 0) + 1, + beforeCallbackFn = args.before || devnull, + pathname = path.replace(/[\?|#].*$/, ''), + pathStripped = path.replace(/^(css|img)!/, ''), + isLegacyIECss, + e; + numTries = numTries || 0; + + if (/(^css!|\.css$)/.test(pathname)) { + // css + e = doc.createElement('link'); + e.rel = 'stylesheet'; + e.href = pathStripped; // tag IE9+ + + isLegacyIECss = 'hideFocus' in e; // use preload in IE Edge (to detect load errors) + + if (isLegacyIECss && e.relList) { + isLegacyIECss = 0; + e.rel = 'preload'; + e.as = 'style'; + } + } else if (/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(pathname)) { + // image + e = doc.createElement('img'); + e.src = pathStripped; + } else { + // javascript + e = doc.createElement('script'); + e.src = path; + e.async = async === undefined ? true : async; + } + + e.onload = e.onerror = e.onbeforeload = function (ev) { + var result = ev.type[0]; // treat empty stylesheets as failures to get around lack of onerror + // support in IE9-11 + + if (isLegacyIECss) { + try { + if (!e.sheet.cssText.length) result = 'e'; + } catch (x) { + // sheets objects created from load errors don't allow access to + // `cssText` (unless error is Code:18 SecurityError) + if (x.code != 18) result = 'e'; + } + } // handle retries in case of load failure + + + if (result == 'e') { + // increment counter + numTries += 1; // exit function and try again + + if (numTries < maxTries) { + return loadFile(path, callbackFn, args, numTries); + } + } else if (e.rel == 'preload' && e.as == 'style') { + // activate preloaded stylesheets + return e.rel = 'stylesheet'; // jshint ignore:line + } // execute callback + + + callbackFn(path, result, ev.defaultPrevented); + }; // add to document (unless callback returns `false`) + + + if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e); + } + /** + * Load multiple files. + * @param {string[]} paths - The file paths + * @param {Function} callbackFn - The callback function + */ + + + function loadFiles(paths, callbackFn, args) { + // listify paths + paths = paths.push ? paths : [paths]; + var numWaiting = paths.length, + x = numWaiting, + pathsNotFound = [], + fn, + i; // define callback function + + fn = function (path, result, defaultPrevented) { + // handle error + if (result == 'e') pathsNotFound.push(path); // handle beforeload event. If defaultPrevented then that means the load + // will be blocked (ex. Ghostery/ABP on Safari) + + if (result == 'b') { + if (defaultPrevented) pathsNotFound.push(path);else return; + } + + numWaiting--; + if (!numWaiting) callbackFn(pathsNotFound); + }; // load scripts + + + for (i = 0; i < x; i++) loadFile(paths[i], fn, args); + } + /** + * Initiate script load and register bundle. + * @param {(string|string[])} paths - The file paths + * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success + * callback or (3) object literal with success/error arguments, numRetries, + * etc. + * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object + * literal with success/error arguments, numRetries, etc. + */ + + + function loadjs(paths, arg1, arg2) { + var bundleId, args; // bundleId (if string) + + if (arg1 && arg1.trim) bundleId = arg1; // args (default is {}) + + args = (bundleId ? arg2 : arg1) || {}; // throw error if bundle is already defined + + if (bundleId) { + if (bundleId in bundleIdCache) { + throw "LoadJS"; + } else { + bundleIdCache[bundleId] = true; + } + } + + function loadFn(resolve, reject) { + loadFiles(paths, function (pathsNotFound) { + // execute callbacks + executeCallbacks(args, pathsNotFound); // resolve Promise + + if (resolve) { + executeCallbacks({ + success: resolve, + error: reject + }, pathsNotFound); + } // publish bundle load event + + + publish(bundleId, pathsNotFound); + }, args); + } + + if (args.returnPromise) return new Promise(loadFn);else loadFn(); + } + /** + * Execute callbacks when dependencies have been satisfied. + * @param {(string|string[])} deps - List of bundle ids + * @param {Object} args - success/error arguments + */ + + + loadjs.ready = function ready(deps, args) { + // subscribe to bundle load event + subscribe(deps, function (depsNotFound) { + // execute callbacks + executeCallbacks(args, depsNotFound); + }); + return loadjs; + }; + /** + * Manually satisfy bundle dependencies. + * @param {string} bundleId - The bundle id + */ + + + loadjs.done = function done(bundleId) { + publish(bundleId, []); + }; + /** + * Reset loadjs dependencies statuses + */ + + + loadjs.reset = function reset() { + bundleIdCache = {}; + bundleResultCache = {}; + bundleCallbackQueue = {}; + }; + /** + * Determine if bundle has already been defined + * @param String} bundleId - The bundle id + */ + + + loadjs.isDefined = function isDefined(bundleId) { + return bundleId in bundleIdCache; + }; // export + + + return loadjs; + }); +}); + +// ========================================================================== +function loadScript(url) { + return new Promise((resolve, reject) => { + loadjs_umd(url, { + success: resolve, + error: reject + }); + }); +} + +// ========================================================================== + +function parseId$1(url) { + if (is.empty(url)) { + return null; + } + + if (is.number(Number(url))) { + return url; + } + + const regex = /^.*(vimeo.com\/|video\/)(\d+).*/; + return url.match(regex) ? RegExp.$2 : url; +} // Try to extract a hash for private videos from the URL + + +function parseHash(url) { + /* This regex matches a hexadecimal hash if given in any of these forms: + * - [https://player.]vimeo.com/video/{id}/{hash}[?params] + * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms] + * - [https://player.]vimeo.com/video/{id}?[params]&h={hash} + * - video/{id}/{hash} + * If matched, the hash is available in the named group `hash` + */ + const regex = /^.*(?:vimeo.com\/|video\/)(?:\d+)(?:\?.*&*h=|\/)+(?<hash>[\d,a-f]+)/; + const found = url.match(regex); + return found ? found.groups.hash : null; +} // Set playback state and trigger change (only on actual change) + + +function assurePlaybackState$1(play) { + if (play && !this.embed.hasPlayed) { + this.embed.hasPlayed = true; + } + + if (this.media.paused === play) { + this.media.paused = !play; + triggerEvent.call(this, this.media, play ? 'play' : 'pause'); + } +} + +const vimeo = { + setup() { + const player = this; // Add embed class for responsive + + toggleClass(player.elements.wrapper, player.config.classNames.embed, true); // Set speed options from config + + player.options.speed = player.config.speed.options; // Set intial ratio + + setAspectRatio.call(player); // Load the SDK if not already + + if (!is.object(window.Vimeo)) { + loadScript(player.config.urls.vimeo.sdk).then(() => { + vimeo.ready.call(player); + }).catch(error => { + player.debug.warn('Vimeo SDK (player.js) failed to load', error); + }); + } else { + vimeo.ready.call(player); + } + }, + + // API Ready + ready() { + const player = this; + const config = player.config.vimeo; + const { + premium, + referrerPolicy, + ...frameParams + } = config; // Get the source URL or ID + + let source = player.media.getAttribute('src'); + let hash = ''; // Get from <div> if needed + + if (is.empty(source)) { + source = player.media.getAttribute(player.config.attributes.embed.id); // hash can also be set as attribute on the <div> + + hash = player.media.getAttribute(player.config.attributes.embed.hash); + } else { + hash = parseHash(source); + } + + const hashParam = hash ? { + h: hash + } : {}; // If the owner has a pro or premium account then we can hide controls etc + + if (premium) { + Object.assign(frameParams, { + controls: false, + sidedock: false + }); + } // Get Vimeo params for the iframe + + + const params = buildUrlParams({ + loop: player.config.loop.active, + autoplay: player.autoplay, + muted: player.muted, + gesture: 'media', + playsinline: !this.config.fullscreen.iosNative, + // hash has to be added to iframe-URL + ...hashParam, + ...frameParams + }); + const id = parseId$1(source); // Build an iframe + + const iframe = createElement('iframe'); + const src = format(player.config.urls.vimeo.iframe, id, params); + iframe.setAttribute('src', src); + iframe.setAttribute('allowfullscreen', ''); + iframe.setAttribute('allow', ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; ')); // Set the referrer policy if required + + if (!is.empty(referrerPolicy)) { + iframe.setAttribute('referrerPolicy', referrerPolicy); + } // Inject the package + + + if (premium || !config.customControls) { + iframe.setAttribute('data-poster', player.poster); + player.media = replaceElement(iframe, player.media); + } else { + const wrapper = createElement('div', { + class: player.config.classNames.embedContainer, + 'data-poster': player.poster + }); + wrapper.appendChild(iframe); + player.media = replaceElement(wrapper, player.media); + } // Get poster image + + + if (!config.customControls) { + fetch(format(player.config.urls.vimeo.api, src)).then(response => { + if (is.empty(response) || !response.thumbnail_url) { + return; + } // Set and show poster + + + ui.setPoster.call(player, response.thumbnail_url).catch(() => {}); + }); + } // Setup instance + // https://github.com/vimeo/player.js + + + player.embed = new window.Vimeo.Player(iframe, { + autopause: player.config.autopause, + muted: player.muted + }); + player.media.paused = true; + player.media.currentTime = 0; // Disable native text track rendering + + if (player.supported.ui) { + player.embed.disableTextTrack(); + } // Create a faux HTML5 API using the Vimeo API + + + player.media.play = () => { + assurePlaybackState$1.call(player, true); + return player.embed.play(); + }; + + player.media.pause = () => { + assurePlaybackState$1.call(player, false); + return player.embed.pause(); + }; + + player.media.stop = () => { + player.pause(); + player.currentTime = 0; + }; // Seeking + + + let { + currentTime + } = player.media; + Object.defineProperty(player.media, 'currentTime', { + get() { + return currentTime; + }, + + set(time) { + // Vimeo will automatically play on seek if the video hasn't been played before + // Get current paused state and volume etc + const { + embed, + media, + paused, + volume + } = player; + const restorePause = paused && !embed.hasPlayed; // Set seeking state and trigger event + + media.seeking = true; + triggerEvent.call(player, media, 'seeking'); // If paused, mute until seek is complete + + Promise.resolve(restorePause && embed.setVolume(0)) // Seek + .then(() => embed.setCurrentTime(time)) // Restore paused + .then(() => restorePause && embed.pause()) // Restore volume + .then(() => restorePause && embed.setVolume(volume)).catch(() => {// Do nothing + }); + } + + }); // Playback speed + + let speed = player.config.speed.selected; + Object.defineProperty(player.media, 'playbackRate', { + get() { + return speed; + }, + + set(input) { + player.embed.setPlaybackRate(input).then(() => { + speed = input; + triggerEvent.call(player, player.media, 'ratechange'); + }).catch(() => { + // Cannot set Playback Rate, Video is probably not on Pro account + player.options.speed = [1]; + }); + } + + }); // Volume + + let { + volume + } = player.config; + Object.defineProperty(player.media, 'volume', { + get() { + return volume; + }, + + set(input) { + player.embed.setVolume(input).then(() => { + volume = input; + triggerEvent.call(player, player.media, 'volumechange'); + }); + } + + }); // Muted + + let { + muted + } = player.config; + Object.defineProperty(player.media, 'muted', { + get() { + return muted; + }, + + set(input) { + const toggle = is.boolean(input) ? input : false; + player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => { + muted = toggle; + triggerEvent.call(player, player.media, 'volumechange'); + }); + } + + }); // Loop + + let { + loop + } = player.config; + Object.defineProperty(player.media, 'loop', { + get() { + return loop; + }, + + set(input) { + const toggle = is.boolean(input) ? input : player.config.loop.active; + player.embed.setLoop(toggle).then(() => { + loop = toggle; + }); + } + + }); // Source + + let currentSrc; + player.embed.getVideoUrl().then(value => { + currentSrc = value; + controls.setDownloadUrl.call(player); + }).catch(error => { + this.debug.warn(error); + }); + Object.defineProperty(player.media, 'currentSrc', { + get() { + return currentSrc; + } + + }); // Ended + + Object.defineProperty(player.media, 'ended', { + get() { + return player.currentTime === player.duration; + } + + }); // Set aspect ratio based on video size + + Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(dimensions => { + const [width, height] = dimensions; + player.embed.ratio = roundAspectRatio(width, height); + setAspectRatio.call(this); + }); // Set autopause + + player.embed.setAutopause(player.config.autopause).then(state => { + player.config.autopause = state; + }); // Get title + + player.embed.getVideoTitle().then(title => { + player.config.title = title; + ui.setTitle.call(this); + }); // Get current time + + player.embed.getCurrentTime().then(value => { + currentTime = value; + triggerEvent.call(player, player.media, 'timeupdate'); + }); // Get duration + + player.embed.getDuration().then(value => { + player.media.duration = value; + triggerEvent.call(player, player.media, 'durationchange'); + }); // Get captions + + player.embed.getTextTracks().then(tracks => { + player.media.textTracks = tracks; + captions.setup.call(player); + }); + player.embed.on('cuechange', ({ + cues = [] + }) => { + const strippedCues = cues.map(cue => stripHTML(cue.text)); + captions.updateCues.call(player, strippedCues); + }); + player.embed.on('loaded', () => { + // Assure state and events are updated on autoplay + player.embed.getPaused().then(paused => { + assurePlaybackState$1.call(player, !paused); + + if (!paused) { + triggerEvent.call(player, player.media, 'playing'); + } + }); + + if (is.element(player.embed.element) && player.supported.ui) { + const frame = player.embed.element; // Fix keyboard focus issues + // https://github.com/sampotts/plyr/issues/317 + + frame.setAttribute('tabindex', -1); + } + }); + player.embed.on('bufferstart', () => { + triggerEvent.call(player, player.media, 'waiting'); + }); + player.embed.on('bufferend', () => { + triggerEvent.call(player, player.media, 'playing'); + }); + player.embed.on('play', () => { + assurePlaybackState$1.call(player, true); + triggerEvent.call(player, player.media, 'playing'); + }); + player.embed.on('pause', () => { + assurePlaybackState$1.call(player, false); + }); + player.embed.on('timeupdate', data => { + player.media.seeking = false; + currentTime = data.seconds; + triggerEvent.call(player, player.media, 'timeupdate'); + }); + player.embed.on('progress', data => { + player.media.buffered = data.percent; + triggerEvent.call(player, player.media, 'progress'); // Check all loaded + + if (parseInt(data.percent, 10) === 1) { + triggerEvent.call(player, player.media, 'canplaythrough'); + } // Get duration as if we do it before load, it gives an incorrect value + // https://github.com/sampotts/plyr/issues/891 + + + player.embed.getDuration().then(value => { + if (value !== player.media.duration) { + player.media.duration = value; + triggerEvent.call(player, player.media, 'durationchange'); + } + }); + }); + player.embed.on('seeked', () => { + player.media.seeking = false; + triggerEvent.call(player, player.media, 'seeked'); + }); + player.embed.on('ended', () => { + player.media.paused = true; + triggerEvent.call(player, player.media, 'ended'); + }); + player.embed.on('error', detail => { + player.media.error = detail; + triggerEvent.call(player, player.media, 'error'); + }); // Rebuild UI + + if (config.customControls) { + setTimeout(() => ui.build.call(player), 0); + } + } + +}; + +// ========================================================================== + +function parseId(url) { + if (is.empty(url)) { + return null; + } + + const regex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/; + return url.match(regex) ? RegExp.$2 : url; +} // Set playback state and trigger change (only on actual change) + + +function assurePlaybackState(play) { + if (play && !this.embed.hasPlayed) { + this.embed.hasPlayed = true; + } + + if (this.media.paused === play) { + this.media.paused = !play; + triggerEvent.call(this, this.media, play ? 'play' : 'pause'); + } +} + +function getHost(config) { + if (config.noCookie) { + return 'https://www.youtube-nocookie.com'; + } + + if (window.location.protocol === 'http:') { + return 'http://www.youtube.com'; + } // Use YouTube's default + + + return undefined; +} + +const youtube = { + setup() { + // Add embed class for responsive + toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Setup API + + if (is.object(window.YT) && is.function(window.YT.Player)) { + youtube.ready.call(this); + } else { + // Reference current global callback + const callback = window.onYouTubeIframeAPIReady; // Set callback to process queue + + window.onYouTubeIframeAPIReady = () => { + // Call global callback if set + if (is.function(callback)) { + callback(); + } + + youtube.ready.call(this); + }; // Load the SDK + + + loadScript(this.config.urls.youtube.sdk).catch(error => { + this.debug.warn('YouTube API failed to load', error); + }); + } + }, + + // Get the media title + getTitle(videoId) { + const url = format(this.config.urls.youtube.api, videoId); + fetch(url).then(data => { + if (is.object(data)) { + const { + title, + height, + width + } = data; // Set title + + this.config.title = title; + ui.setTitle.call(this); // Set aspect ratio + + this.embed.ratio = roundAspectRatio(width, height); + } + + setAspectRatio.call(this); + }).catch(() => { + // Set aspect ratio + setAspectRatio.call(this); + }); + }, + + // API ready + ready() { + const player = this; + const config = player.config.youtube; // Ignore already setup (race condition) + + const currentId = player.media && player.media.getAttribute('id'); + + if (!is.empty(currentId) && currentId.startsWith('youtube-')) { + return; + } // Get the source URL or ID + + + let source = player.media.getAttribute('src'); // Get from <div> if needed + + if (is.empty(source)) { + source = player.media.getAttribute(this.config.attributes.embed.id); + } // Replace the <iframe> with a <div> due to YouTube API issues + + + const videoId = parseId(source); + const id = generateId(player.provider); // Replace media element + + const container = createElement('div', { + id, + 'data-poster': config.customControls ? player.poster : undefined + }); + player.media = replaceElement(container, player.media); // Only load the poster when using custom controls + + if (config.customControls) { + const posterSrc = s => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`; // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide) + + + loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded + .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3 + .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists + .then(image => ui.setPoster.call(player, image.src)).then(src => { + // If the image is padded, use background-size "cover" instead (like youtube does too with their posters) + if (!src.includes('maxres')) { + player.elements.poster.style.backgroundSize = 'cover'; + } + }).catch(() => {}); + } // Setup instance + // https://developers.google.com/youtube/iframe_api_reference + + + player.embed = new window.YT.Player(player.media, { + videoId, + host: getHost(config), + playerVars: extend({}, { + // Autoplay + autoplay: player.config.autoplay ? 1 : 0, + // iframe interface language + hl: player.config.hl, + // Only show controls if not fully supported or opted out + controls: player.supported.ui && config.customControls ? 0 : 1, + // Disable keyboard as we handle it + disablekb: 1, + // Allow iOS inline playback + playsinline: !player.config.fullscreen.iosNative ? 1 : 0, + // 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 + if (!player.media.error) { + const code = event.data; // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError + + const message = { + 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.', + 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.', + 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.', + 101: 'The owner of the requested video does not allow it to be played in embedded players.', + 150: 'The owner of the requested video does not allow it to be played in embedded players.' + }[code] || 'An unknown error occured'; + player.media.error = { + code, + message + }; + triggerEvent.call(player, player.media, 'error'); + } + }, + + onPlaybackRateChange(event) { + // Get the instance + const instance = event.target; // Get current speed + + player.media.playbackRate = instance.getPlaybackRate(); + triggerEvent.call(player, player.media, 'ratechange'); + }, + + onReady(event) { + // Bail if onReady has already been called. See issue #1108 + if (is.function(player.media.play)) { + return; + } // Get the instance + + + const instance = event.target; // Get the title + + youtube.getTitle.call(player, videoId); // Create a faux HTML5 API using the YouTube API + + player.media.play = () => { + assurePlaybackState.call(player, true); + instance.playVideo(); + }; + + player.media.pause = () => { + assurePlaybackState.call(player, false); + instance.pauseVideo(); + }; + + player.media.stop = () => { + instance.stopVideo(); + }; + + player.media.duration = instance.getDuration(); + player.media.paused = true; // Seeking + + player.media.currentTime = 0; + Object.defineProperty(player.media, 'currentTime', { + get() { + return Number(instance.getCurrentTime()); + }, + + set(time) { + // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet). + if (player.paused && !player.embed.hasPlayed) { + player.embed.mute(); + } // Set seeking state and trigger event + + + player.media.seeking = true; + triggerEvent.call(player, player.media, 'seeking'); // Seek after events sent + + instance.seekTo(time); + } + + }); // Playback speed + + Object.defineProperty(player.media, 'playbackRate', { + get() { + return instance.getPlaybackRate(); + }, + + set(input) { + instance.setPlaybackRate(input); + } + + }); // Volume + + let { + volume + } = player.config; + Object.defineProperty(player.media, 'volume', { + get() { + return volume; + }, + + set(input) { + volume = input; + instance.setVolume(volume * 100); + triggerEvent.call(player, player.media, 'volumechange'); + } + + }); // Muted + + let { + muted + } = player.config; + Object.defineProperty(player.media, 'muted', { + get() { + return muted; + }, + + set(input) { + const toggle = is.boolean(input) ? input : muted; + muted = toggle; + instance[toggle ? 'mute' : 'unMute'](); + instance.setVolume(volume * 100); + triggerEvent.call(player, player.media, 'volumechange'); + } + + }); // Source + + Object.defineProperty(player.media, 'currentSrc', { + get() { + return instance.getVideoUrl(); + } + + }); // Ended + + Object.defineProperty(player.media, 'ended', { + get() { + return player.currentTime === player.duration; + } + + }); // Get available speeds + + const speeds = instance.getAvailablePlaybackRates(); // Filter based on config + + player.options.speed = speeds.filter(s => player.config.speed.options.includes(s)); // Set the tabindex to avoid focus entering iframe + + if (player.supported.ui && config.customControls) { + player.media.setAttribute('tabindex', -1); + } + + triggerEvent.call(player, player.media, 'timeupdate'); + triggerEvent.call(player, player.media, 'durationchange'); // Reset timer + + clearInterval(player.timers.buffering); // Setup buffering + + player.timers.buffering = setInterval(() => { + // Get loaded % from YouTube + player.media.buffered = instance.getVideoLoadedFraction(); // Trigger progress only when we actually buffer something + + if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) { + triggerEvent.call(player, player.media, 'progress'); + } // Set last buffer point + + + player.media.lastBuffered = player.media.buffered; // Bail if we're at 100% + + if (player.media.buffered === 1) { + clearInterval(player.timers.buffering); // Trigger event + + triggerEvent.call(player, player.media, 'canplaythrough'); + } + }, 200); // Rebuild UI + + if (config.customControls) { + setTimeout(() => ui.build.call(player), 50); + } + }, + + onStateChange(event) { + // Get the instance + const instance = event.target; // Reset timer + + clearInterval(player.timers.playing); + const seeked = player.media.seeking && [1, 2].includes(event.data); + + if (seeked) { + // Unset seeking and fire seeked event + player.media.seeking = false; + triggerEvent.call(player, player.media, 'seeked'); + } // Handle events + // -1 Unstarted + // 0 Ended + // 1 Playing + // 2 Paused + // 3 Buffering + // 5 Video cued + + + switch (event.data) { + case -1: + // Update scrubber + triggerEvent.call(player, player.media, 'timeupdate'); // Get loaded % from YouTube + + player.media.buffered = instance.getVideoLoadedFraction(); + triggerEvent.call(player, player.media, 'progress'); + break; + + case 0: + assurePlaybackState.call(player, false); // YouTube doesn't support loop for a single video, so mimick it. + + if (player.media.loop) { + // YouTube needs a call to `stopVideo` before playing again + instance.stopVideo(); + instance.playVideo(); + } else { + triggerEvent.call(player, player.media, 'ended'); + } + + break; + + case 1: + // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet) + if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) { + player.media.pause(); + } else { + assurePlaybackState.call(player, true); + triggerEvent.call(player, player.media, 'playing'); // Poll to get playback progress + + player.timers.playing = setInterval(() => { + triggerEvent.call(player, player.media, 'timeupdate'); + }, 50); // Check duration again due to YouTube bug + // https://github.com/sampotts/plyr/issues/374 + // https://code.google.com/p/gdata-issues/issues/detail?id=8690 + + if (player.media.duration !== instance.getDuration()) { + player.media.duration = instance.getDuration(); + triggerEvent.call(player, player.media, 'durationchange'); + } + } + + break; + + case 2: + // Restore audio (YouTube starts playing on seek if the video hasn't been played yet) + if (!player.muted) { + player.embed.unMute(); + } + + assurePlaybackState.call(player, false); + break; + + case 3: + // Trigger waiting event to add loading classes to container as the video buffers. + triggerEvent.call(player, player.media, 'waiting'); + break; + } + + triggerEvent.call(player, player.elements.container, 'statechange', false, { + code: event.data + }); + } + + } + }); + } + +}; + +// ========================================================================== +const media = { + // Setup media + setup() { + // If there's no media, bail + if (!this.media) { + this.debug.warn('No media element found!'); + return; + } // Add type class + + + toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true); // Add provider class + + toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true); // Add video class for embeds + // This will require changes if audio embeds are added + + if (this.isEmbed) { + toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true); + } // Inject the player wrapper + + + if (this.isVideo) { + // Create the wrapper div + this.elements.wrapper = createElement('div', { + class: this.config.classNames.video + }); // Wrap the video in a container + + wrap(this.media, this.elements.wrapper); // Poster image container + + this.elements.poster = createElement('div', { + class: this.config.classNames.poster + }); + this.elements.wrapper.appendChild(this.elements.poster); + } + + if (this.isHTML5) { + html5.setup.call(this); + } else if (this.isYouTube) { + youtube.setup.call(this); + } else if (this.isVimeo) { + vimeo.setup.call(this); + } + } + +}; + +const destroy = instance => { + // Destroy our adsManager + if (instance.manager) { + instance.manager.destroy(); + } // Destroy our adsManager + + + if (instance.elements.displayContainer) { + instance.elements.displayContainer.destroy(); + } + + instance.elements.container.remove(); +}; + +class Ads { + /** + * Ads constructor. + * @param {Object} player + * @return {Ads} + */ + constructor(player) { + _defineProperty$1(this, "load", () => { + if (!this.enabled) { + return; + } // Check if the Google IMA3 SDK is loaded or load it ourselves + + + if (!is.object(window.google) || !is.object(window.google.ima)) { + loadScript(this.player.config.urls.googleIMA.sdk).then(() => { + this.ready(); + }).catch(() => { + // Script failed to load or is blocked + this.trigger('error', new Error('Google IMA SDK failed to load')); + }); + } else { + this.ready(); + } + }); + + _defineProperty$1(this, "ready", () => { + // Double check we're enabled + if (!this.enabled) { + destroy(this); + } // Start ticking our safety timer. If the whole advertisement + // thing doesn't resolve within our set time; we bail + + + this.startSafetyTimer(12000, 'ready()'); // Clear the safety timer + + this.managerPromise.then(() => { + this.clearSafetyTimer('onAdsManagerLoaded()'); + }); // Set listeners on the Plyr instance + + this.listeners(); // Setup the IMA SDK + + this.setupIMA(); + }); + + _defineProperty$1(this, "setupIMA", () => { + // Create the container for our advertisements + this.elements.container = createElement('div', { + class: this.player.config.classNames.ads + }); + this.player.elements.container.appendChild(this.elements.container); // So we can run VPAID2 + + google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED); // Set language + + google.ima.settings.setLocale(this.player.config.ads.language); // 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); // Create ads loader + + this.loader = new google.ima.AdsLoader(this.elements.displayContainer); // Listen and respond to ads loaded and error events + + this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false); + this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false); // Request video ads to be pre-loaded + + this.requestAds(); + }); + + _defineProperty$1(this, "requestAds", () => { + const { + container + } = this.player.elements; + + try { + // Request video ads + const request = new google.ima.AdsRequest(); + request.adTagUrl = this.tagUrl; // Specify the linear and nonlinear slot sizes. This helps the SDK + // to select the correct creative if multiple are returned + + request.linearAdSlotWidth = container.offsetWidth; + request.linearAdSlotHeight = container.offsetHeight; + request.nonLinearAdSlotWidth = container.offsetWidth; + request.nonLinearAdSlotHeight = container.offsetHeight; // We only overlay ads as we only support video. + + request.forceNonLinearFullSlot = false; // Mute based on current state + + request.setAdWillPlayMuted(!this.player.muted); + this.loader.requestAds(request); + } catch (error) { + this.onAdError(error); + } + }); + + _defineProperty$1(this, "pollCountdown", (start = false) => { + if (!start) { + clearInterval(this.countdownTimer); + this.elements.container.removeAttribute('data-badge-text'); + return; + } + + const update = () => { + const time = formatTime(Math.max(this.manager.getRemainingTime(), 0)); + const label = `${i18n.get('advertisement', this.player.config)} - ${time}`; + this.elements.container.setAttribute('data-badge-text', label); + }; + + this.countdownTimer = setInterval(update, 100); + }); + + _defineProperty$1(this, "onAdsManagerLoaded", event => { + // Load could occur after a source change (race condition) + if (!this.enabled) { + return; + } // Get the ads manager + + + const settings = new google.ima.AdsRenderingSettings(); // Tell the SDK to save and restore content video state on our behalf + + settings.restoreCustomPlaybackStateOnAdBreakComplete = true; + settings.enablePreloading = true; // The SDK is polling currentTime on the contentPlayback. And needs a duration + // so it can determine when to start the mid- and post-roll + + this.manager = event.getAdsManager(this.player, settings); // Get the cue points for any mid-rolls by filtering out the pre- and post-roll + + this.cuePoints = this.manager.getCuePoints(); // Add listeners to the required events + // Advertisement error events + + this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error)); // Advertisement regular events + + Object.keys(google.ima.AdEvent.Type).forEach(type => { + this.manager.addEventListener(google.ima.AdEvent.Type[type], e => this.onAdEvent(e)); + }); // Resolve our adsManager + + this.trigger('loaded'); + }); + + _defineProperty$1(this, "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); + } + } + }); + } + }); + + _defineProperty$1(this, "onAdEvent", event => { + const { + container + } = this.player.elements; // 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 => { + triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`); + }; // Bubble the event + + + dispatchEvent(event.type); + + switch (event.type) { + case google.ima.AdEvent.Type.LOADED: + // This is the first event sent for an ad - it is possible to determine whether the + // ad is a video ad or an overlay + this.trigger('loaded'); // Start countdown + + this.pollCountdown(true); + + if (!ad.isLinear()) { + // Position AdDisplayContainer correctly for overlay + ad.width = container.offsetWidth; + ad.height = container.offsetHeight; + } // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex()); + // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset()); + + + break; + + case google.ima.AdEvent.Type.STARTED: + // Set volume to match player + this.manager.setVolume(this.player.volume); + break; + + case google.ima.AdEvent.Type.ALL_ADS_COMPLETED: + // All ads for the current videos are done. We can now request new advertisements + // in case the video is re-played + // TODO: Example for what happens when a next video in a playlist would be loaded. + // So here we load a new video when all ads are done. + // Then we load new ads within a new adsManager. When the video + // Is started - after - the ads are loaded, then we get ads. + // You can also easily test cancelling and reloading by running + // player.ads.cancel() and player.ads.play from the console I guess. + // this.player.source = { + // type: 'video', + // title: 'View From A Blue Moon', + // sources: [{ + // src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type: + // 'video/mp4', }], poster: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks: + // [ { kind: 'captions', label: 'English', srclang: 'en', src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt', + // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ], + // }; + // TODO: So there is still this thing where a video should only be allowed to start + // playing when the IMA SDK is ready or has failed + if (this.player.ended) { + this.loadAds(); + } else { + // The SDK won't allow new ads to be called without receiving a contentComplete() + this.loader.contentComplete(); + } + + break; + + case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED: + // This event indicates the ad has started - the video player can adjust the UI, + // for example display a pause button and remaining time. Fired when content should + // be paused. This usually happens right before an ad is about to cover the content + this.pauseContent(); + break; + + case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED: + // This event indicates the ad has finished - the video player can perform + // appropriate UI actions, such as removing the timer for remaining time detection. + // Fired when content should be resumed. This usually happens when an ad finishes + // or collapses + this.pollCountdown(); + this.resumeContent(); + break; + + case google.ima.AdEvent.Type.LOG: + if (adData.adError) { + this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`); + } + + break; + } + }); + + _defineProperty$1(this, "onAdError", event => { + this.cancel(); + this.player.debug.warn('Ads error', event); + }); + + _defineProperty$1(this, "listeners", () => { + const { + container + } = this.player.elements; + let time; + this.player.on('canplay', () => { + this.addCuePoints(); + }); + this.player.on('ended', () => { + this.loader.contentComplete(); + }); + this.player.on('timeupdate', () => { + time = this.player.currentTime; + }); + this.player.on('seeked', () => { + const seekedTime = this.player.currentTime; + + if (is.empty(this.cuePoints)) { + return; + } + + this.cuePoints.forEach((cuePoint, index) => { + if (time < cuePoint && cuePoint < seekedTime) { + this.manager.discardAdBreak(); + this.cuePoints.splice(index, 1); + } + }); + }); // Listen to the resizing of the window. And resize ad accordingly + // TODO: eventually implement ResizeObserver + + window.addEventListener('resize', () => { + if (this.manager) { + this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); + } + }); + }); + + _defineProperty$1(this, "play", () => { + const { + container + } = this.player.elements; + + if (!this.managerPromise) { + this.resumeContent(); + } // Play the requested advertisement whenever the adsManager is ready + + + this.managerPromise.then(() => { + // Set volume to match player + this.manager.setVolume(this.player.volume); // Initialize the container. Must be done via a user action on mobile devices + + this.elements.displayContainer.initialize(); + + try { + if (!this.initialized) { + // Initialize the ads manager. Ad rules playlist will start at this time + this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will + // start at this time; the call will be ignored for ad rules + + this.manager.start(); + } + + this.initialized = true; + } catch (adError) { + // An error may be thrown if there was a problem with the + // VAST response + this.onAdError(adError); + } + }).catch(() => {}); + }); + + _defineProperty$1(this, "resumeContent", () => { + // Hide the advertisement container + this.elements.container.style.zIndex = ''; // Ad is stopped + + this.playing = false; // Play video + + silencePromise(this.player.media.play()); + }); + + _defineProperty$1(this, "pauseContent", () => { + // Show the advertisement container + this.elements.container.style.zIndex = 3; // Ad is playing + + this.playing = true; // Pause our video. + + this.player.media.pause(); + }); + + _defineProperty$1(this, "cancel", () => { + // Pause our video + if (this.initialized) { + this.resumeContent(); + } // Tell our instance that we're done for now + + + this.trigger('error'); // Re-create our adsManager + + this.loadAds(); + }); + + _defineProperty$1(this, "loadAds", () => { + // Tell our adsManager to go bye bye + this.managerPromise.then(() => { + // Destroy our adsManager + if (this.manager) { + this.manager.destroy(); + } // Re-set our adsManager promises + + + this.managerPromise = new Promise(resolve => { + this.on('loaded', resolve); + this.player.debug.log(this.manager); + }); // Now that the manager has been destroyed set it to also be un-initialized + + this.initialized = false; // Now request some new advertisements + + this.requestAds(); + }).catch(() => {}); + }); + + _defineProperty$1(this, "trigger", (event, ...args) => { + const handlers = this.events[event]; + + if (is.array(handlers)) { + handlers.forEach(handler => { + if (is.function(handler)) { + handler.apply(this, args); + } + }); + } + }); + + _defineProperty$1(this, "on", (event, callback) => { + if (!is.array(this.events[event])) { + this.events[event] = []; + } + + this.events[event].push(callback); + return this; + }); + + _defineProperty$1(this, "startSafetyTimer", (time, from) => { + this.player.debug.log(`Safety timer invoked from: ${from}`); + this.safetyTimer = setTimeout(() => { + this.cancel(); + this.clearSafetyTimer('startSafetyTimer()'); + }, time); + }); + + _defineProperty$1(this, "clearSafetyTimer", from => { + if (!is.nullOrUndefined(this.safetyTimer)) { + this.player.debug.log(`Safety timer cleared from: ${from}`); + clearTimeout(this.safetyTimer); + this.safetyTimer = null; + } + }); + + this.player = player; + this.config = player.config.ads; + this.playing = false; + this.initialized = false; + this.elements = { + container: null, + displayContainer: null + }; + this.manager = null; + this.loader = null; + this.cuePoints = null; + this.events = {}; + this.safetyTimer = null; + this.countdownTimer = null; // Setup a promise to resolve when the IMA manager is ready + + this.managerPromise = new Promise((resolve, reject) => { + // The ad is loaded and ready + this.on('loaded', resolve); // Ads failed + + this.on('error', reject); + }); + this.load(); + } + + get enabled() { + const { + config + } = this; + return this.player.isHTML5 && this.player.isVideo && config.enabled && (!is.empty(config.publisherId) || is.url(config.tagUrl)); + } + /** + * Load the IMA SDK + */ + + + // 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', + AV_URL: window.location.hostname, + cb: Date.now(), + AV_WIDTH: 640, + AV_HEIGHT: 480, + AV_CDIM2: config.publisherId + }; + const base = 'https://go.aniview.com/api/adserver6/vast/'; + return `${base}?${buildUrlParams(params)}`; + } + /** + * In order for the SDK to display ads for our video, we need to tell it where to put them, + * so here we define our ad container. This div is set up to render on top of the video player. + * Using the code below, we tell the SDK to render ads within that div. We also provide a + * handle to the content video player - the SDK will poll the current time of our player to + * properly place mid-rolls. After we create the ad display container, we initialize it. On + * mobile devices, this initialization is done as the result of a user action. + */ + + +} + +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] || 0) * 60 * 60 + Number(matchTimes[2]) * 60 + Number(matchTimes[3]) + Number(`0.${matchTimes[4]}`); + result.endTime = Number(matchTimes[6] || 0) * 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 + */ + + +const fitRatio = (ratio, outer) => { + const targetRatio = outer.width / outer.height; + const result = {}; + + if (ratio > targetRatio) { + result.width = outer.width; + result.height = 1 / ratio * outer.width; + } else { + result.height = outer.height; + result.width = ratio * outer.height; + } + + return result; +}; + +class PreviewThumbnails { + /** + * PreviewThumbnails constructor. + * @param {Plyr} player + * @return {PreviewThumbnails} + */ + constructor(player) { + _defineProperty$1(this, "load", () => { + // Toggle the regular seek tooltip + if (this.player.elements.display.seekTooltip) { + this.player.elements.display.seekTooltip.hidden = this.enabled; + } + + if (!this.enabled) { + return; + } + + this.getThumbnails().then(() => { + if (!this.enabled) { + return; + } // Render DOM elements + + + this.render(); // Check to see if thumb container size was specified manually in CSS + + this.determineContainerAutoSizing(); + this.loaded = true; + }); + }); + + _defineProperty$1(this, "getThumbnails", () => { + return new Promise(resolve => { + const { + src + } = this.player.config.previewThumbnails; + + if (is.empty(src)) { + throw new Error('Missing previewThumbnails.src config attribute'); + } // Resolve promise + + + const sortAndResolve = () => { + // 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(); + }; // Via callback() + + + if (is.function(src)) { + src(thumbnails => { + this.thumbnails = thumbnails; + sortAndResolve(); + }); + } // VTT urls + else { + // 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)); // Resolve + + Promise.all(promises).then(sortAndResolve); + } + }); + }); + + _defineProperty$1(this, "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 the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file + + if (!thumbnail.frames[0].text.startsWith('/') && !thumbnail.frames[0].text.startsWith('http://') && !thumbnail.frames[0].text.startsWith('https://')) { + 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; + }); + }); + }); + + _defineProperty$1(this, "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(); + }); + + _defineProperty$1(this, "endMove", () => { + this.toggleThumbContainer(false, true); + }); + + _defineProperty$1(this, "startScrubbing", event => { + // Only act on left mouse button (0), or touch device (event.button does not exist or is false) + if (is.nullOrUndefined(event.button) || 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(); + } + } + }); + + _defineProperty$1(this, "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); + } + }); + } + }); + + _defineProperty$1(this, "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; + }); + }); + + _defineProperty$1(this, "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 + + if (is.element(this.player.elements.progress)) { + 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); + }); + + _defineProperty$1(this, "destroy", () => { + if (this.elements.thumb.container) { + this.elements.thumb.container.remove(); + } + + if (this.elements.scrubbing.container) { + this.elements.scrubbing.container.remove(); + } + }); + + _defineProperty$1(this, "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); + } + }); + + _defineProperty$1(this, "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); + } + }); + + _defineProperty$1(this, "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)); + }); + + _defineProperty$1(this, "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 + // eslint-disable-next-line no-param-reassign + 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); + } + }); + }); + + _defineProperty$1(this, "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); + }); + }); + + _defineProperty$1(this, "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); + } + } + }); + + _defineProperty$1(this, "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; + } + }); + + _defineProperty$1(this, "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; + } + }); + + _defineProperty$1(this, "determineContainerAutoSizing", () => { + if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) { + // This will prevent auto sizing in this.setThumbContainerSizeAndPos() + this.sizeSpecifiedInCSS = true; + } + }); + + _defineProperty$1(this, "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`; + } else if (this.elements.thumb.imageContainer.clientHeight > 20 && this.elements.thumb.imageContainer.clientWidth < 20) { + const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio); + this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`; + } else if (this.elements.thumb.imageContainer.clientHeight < 20 && this.elements.thumb.imageContainer.clientWidth > 20) { + const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio); + this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`; + } + + this.setThumbContainerPos(); + }); + + _defineProperty$1(this, "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`; + }); + + _defineProperty$1(this, "setScrubbingContainerSize", () => { + const { + width, + height + } = fitRatio(this.thumbAspectRatio, { + width: this.player.media.clientWidth, + height: this.player.media.clientHeight + }); + this.elements.scrubbing.container.style.width = `${width}px`; + this.elements.scrubbing.container.style.height = `${height}px`; + }); + + _defineProperty$1(this, "setImageSizeAndOffset", (previewImage, frame) => { + if (!this.usingSprites) { + return; + } // Find difference between height and preview container height + + + const multiplier = this.thumbContainerHeight / frame.h; // eslint-disable-next-line no-param-reassign + + previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.left = `-${frame.x * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.top = `-${frame.y * multiplier}px`; + }); + + 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; + } + + 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) { + const { + height + } = fitRatio(this.thumbAspectRatio, { + width: this.player.media.clientWidth, + height: this.player.media.clientHeight + }); + return height; + } // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset) + + + if (this.sizeSpecifiedInCSS) { + return this.elements.thumb.imageContainer.clientHeight; + } + + 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; + } + } + +} + +// ========================================================================== +const source = { + // Add elements to HTML5 media (source, tracks, etc) + insertElements(type, attributes) { + if (is.string(attributes)) { + insertElement(type, this.media, { + src: attributes + }); + } else if (is.array(attributes)) { + attributes.forEach(attribute => { + insertElement(type, this.media, attribute); + }); + } + }, + + // Update source + // Sources are not checked for support so be careful + change(input) { + if (!getDeep(input, 'sources.length')) { + this.debug.warn('Invalid source format'); + return; + } // Cancel current network requests + + + html5.cancelRequests.call(this); // Destroy instance and re-setup + + this.destroy.call(this, () => { + // Reset quality options + this.options.quality = []; // Remove elements + + removeElement(this.media); + this.media = null; // Reset class name + + if (is.element(this.elements.container)) { + this.elements.container.removeAttribute('class'); + } // Set the type and provider + + + const { + sources, + type + } = input; + const [{ + provider = providers.html5, + src + }] = sources; + const tagName = provider === 'html5' ? type : 'div'; + const attributes = provider === 'html5' ? {} : { + src + }; + Object.assign(this, { + provider, + type, + // Check for support + supported: support.check(type, provider, this.config.playsinline), + // Create new element + media: createElement(tagName, attributes) + }); // Inject the new element + + this.elements.container.appendChild(this.media); // Autoplay the new source? + + if (is.boolean(input.autoplay)) { + this.config.autoplay = input.autoplay; + } // Set attributes for audio and video + + + if (this.isHTML5) { + if (this.config.crossorigin) { + this.media.setAttribute('crossorigin', ''); + } + + if (this.config.autoplay) { + this.media.setAttribute('autoplay', ''); + } + + if (!is.empty(input.poster)) { + this.poster = input.poster; + } + + if (this.config.loop.active) { + this.media.setAttribute('loop', ''); + } + + if (this.config.muted) { + this.media.setAttribute('muted', ''); + } + + if (this.config.playsinline) { + this.media.setAttribute('playsinline', ''); + } + } // Restore class hook + + + ui.addStyleHook.call(this); // Set new sources for html5 + + if (this.isHTML5) { + source.insertElements.call(this, 'source', sources); + } // Set video title + + + this.config.title = input.title; // Set up from scratch + + media.setup.call(this); // HTML5 stuff + + if (this.isHTML5) { + // Setup captions + if (Object.keys(input).includes('tracks')) { + source.insertElements.call(this, 'track', input.tracks); + } + } // If HTML5 or embed but not fully supported, setupInterface and call ready now + + + if (this.isHTML5 || this.isEmbed && !this.supported.ui) { + // Setup interface + ui.build.call(this); + } // Load HTML5 sources + + + if (this.isHTML5) { + this.media.load(); + } // Update previewThumbnails config & reload plugin + + + if (!is.empty(input.previewThumbnails)) { + Object.assign(this.config.previewThumbnails, input.previewThumbnails); // Cleanup previewThumbnails plugin if it was loaded + + if (this.previewThumbnails && this.previewThumbnails.loaded) { + this.previewThumbnails.destroy(); + this.previewThumbnails = null; + } // Create new instance if it is still enabled + + + if (this.config.previewThumbnails.enabled) { + this.previewThumbnails = new PreviewThumbnails(this); + } + } // Update the fullscreen support + + + this.fullscreen.update(); + }, true); + } + +}; + +/** + * Returns a number whose value is limited to the given range. + * + * Example: limit the output of this computation to between 0 and 255 + * (x * 255).clamp(0, 255) + * + * @param {Number} input + * @param {Number} min The lower boundary of the output range + * @param {Number} max The upper boundary of the output range + * @returns A number in the range [min, max] + * @type Number + */ +function clamp(input = 0, min = 0, max = 255) { + return Math.min(Math.max(input, min), max); +} + +// TODO: Use a WeakMap for private globals +// const globals = new WeakMap(); +// Plyr instance + +class Plyr { + constructor(target, options) { + _defineProperty$1(this, "play", () => { + if (!is.function(this.media.play)) { + return null; + } // Intecept play with ads + + + if (this.ads && this.ads.enabled) { + this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play())); + } // Return the promise (for HTML5) + + + return this.media.play(); + }); + + _defineProperty$1(this, "pause", () => { + if (!this.playing || !is.function(this.media.pause)) { + return null; + } + + return this.media.pause(); + }); + + _defineProperty$1(this, "togglePlay", input => { + // Toggle based on current state if nothing passed + const toggle = is.boolean(input) ? input : !this.playing; + + if (toggle) { + return this.play(); + } + + return this.pause(); + }); + + _defineProperty$1(this, "stop", () => { + if (this.isHTML5) { + this.pause(); + this.restart(); + } else if (is.function(this.media.stop)) { + this.media.stop(); + } + }); + + _defineProperty$1(this, "restart", () => { + this.currentTime = 0; + }); + + _defineProperty$1(this, "rewind", seekTime => { + this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime; + }); + + _defineProperty$1(this, "forward", seekTime => { + this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime; + }); + + _defineProperty$1(this, "increaseVolume", step => { + const volume = this.media.muted ? 0 : this.volume; + this.volume = volume + (is.number(step) ? step : 0); + }); + + _defineProperty$1(this, "decreaseVolume", step => { + this.increaseVolume(-step); + }); + + _defineProperty$1(this, "airplay", () => { + // Show dialog if supported + if (support.airplay) { + this.media.webkitShowPlaybackTargetPicker(); + } + }); + + _defineProperty$1(this, "toggleControls", toggle => { + // Don't toggle if missing UI support or if it's audio + if (this.supported.ui && !this.isAudio) { + // Get state before change + const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls); // Negate the argument if not undefined since adding the class to hides the controls + + const force = typeof toggle === 'undefined' ? undefined : !toggle; // Apply and get updated state + + const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force); // Close menu + + if (hiding && is.array(this.config.controls) && this.config.controls.includes('settings') && !is.empty(this.config.settings)) { + controls.toggleMenu.call(this, false); + } // Trigger event on change + + + if (hiding !== isHidden) { + const eventName = hiding ? 'controlshidden' : 'controlsshown'; + triggerEvent.call(this, this.media, eventName); + } + + return !hiding; + } + + return false; + }); + + _defineProperty$1(this, "on", (event, callback) => { + on.call(this, this.elements.container, event, callback); + }); + + _defineProperty$1(this, "once", (event, callback) => { + once.call(this, this.elements.container, event, callback); + }); + + _defineProperty$1(this, "off", (event, callback) => { + off(this.elements.container, event, callback); + }); + + _defineProperty$1(this, "destroy", (callback, soft = false) => { + if (!this.ready) { + return; + } + + const done = () => { + // Reset overflow (incase destroyed while in fullscreen) + document.body.style.overflow = ''; // GC for embed + + this.embed = null; // If it's a soft destroy, make minimal changes + + if (soft) { + if (Object.keys(this.elements).length) { + // Remove elements + removeElement(this.elements.buttons.play); + removeElement(this.elements.captions); + removeElement(this.elements.controls); + removeElement(this.elements.wrapper); // Clear for GC + + this.elements.buttons.play = null; + this.elements.captions = null; + this.elements.controls = null; + this.elements.wrapper = null; + } // Callback + + + if (is.function(callback)) { + callback(); + } + } else { + // Unbind listeners + unbindListeners.call(this); // Cancel current network requests + + html5.cancelRequests.call(this); // Replace the container with the original element provided + + replaceElement(this.elements.original, this.elements.container); // Event + + triggerEvent.call(this, this.elements.original, 'destroyed', true); // Callback + + if (is.function(callback)) { + callback.call(this.elements.original); + } // Reset state + + + this.ready = false; // Clear for garbage collection + + setTimeout(() => { + this.elements = null; + this.media = null; + }, 200); + } + }; // Stop playback + + + this.stop(); // Clear timeouts + + clearTimeout(this.timers.loading); + clearTimeout(this.timers.controls); + clearTimeout(this.timers.resized); // Provider specific stuff + + if (this.isHTML5) { + // Restore native video controls + ui.toggleNativeControls.call(this, true); // Clean up + + done(); + } else if (this.isYouTube) { + // Clear timers + clearInterval(this.timers.buffering); + clearInterval(this.timers.playing); // Destroy YouTube API + + if (this.embed !== null && is.function(this.embed.destroy)) { + this.embed.destroy(); + } // Clean up + + + done(); + } else if (this.isVimeo) { + // Destroy Vimeo API + // then clean up (wait, to prevent postmessage errors) + if (this.embed !== null) { + this.embed.unload().then(done); + } // Vimeo does not always return + + + setTimeout(done, 200); + } + }); + + _defineProperty$1(this, "supports", type => support.mime.call(this, type)); + + this.timers = {}; // State + + this.ready = false; + this.loading = false; + this.failed = false; // Touch device + + this.touch = support.touch; // Set the media element + + this.media = target; // String selector passed + + if (is.string(this.media)) { + this.media = document.querySelectorAll(this.media); + } // jQuery, NodeList or Array passed, use first element + + + if (window.jQuery && this.media instanceof jQuery || is.nodeList(this.media) || is.array(this.media)) { + // eslint-disable-next-line + this.media = this.media[0]; + } // Set config + + + this.config = extend({}, defaults, Plyr.defaults, options || {}, (() => { + try { + return JSON.parse(this.media.getAttribute('data-plyr-config')); + } catch (_) { + return {}; + } + })()); // Elements cache + + this.elements = { + container: null, + fullscreen: null, + captions: null, + buttons: {}, + display: {}, + progress: {}, + inputs: {}, + settings: { + popup: null, + menu: null, + panels: {}, + buttons: {} + } + }; // Captions + + this.captions = { + active: null, + currentTrack: -1, + meta: new WeakMap() + }; // Fullscreen + + this.fullscreen = { + active: false + }; // Options + + this.options = { + speed: [], + quality: [] + }; // Debugging + // TODO: move to globals + + this.debug = new Console(this.config.debug); // Log config options and support + + this.debug.log('Config', this.config); + this.debug.log('Support', support); // We need an element to setup + + if (is.nullOrUndefined(this.media) || !is.element(this.media)) { + this.debug.error('Setup failed: no suitable element passed'); + return; + } // Bail if the element is initialized + + + if (this.media.plyr) { + this.debug.warn('Target already setup'); + return; + } // Bail if not enabled + + + if (!this.config.enabled) { + this.debug.error('Setup failed: disabled by config'); + return; + } // Bail if disabled or no basic support + // You may want to disable certain UAs etc + + + if (!support.check().api) { + this.debug.error('Setup failed: no support'); + return; + } // Cache original element state for .destroy() + + + const clone = this.media.cloneNode(true); + clone.autoplay = false; + this.elements.original = clone; // Set media type based on tag or data attribute + // Supported: video, audio, vimeo, youtube + + const _type = this.media.tagName.toLowerCase(); // Embed properties + + + let iframe = null; + let url = null; // Different setup based on type + + switch (_type) { + case 'div': + // Find the frame + iframe = this.media.querySelector('iframe'); // <iframe> type + + if (is.element(iframe)) { + // Detect provider + url = parseUrl(iframe.getAttribute('src')); + this.provider = getProviderByUrl(url.toString()); // Rework elements + + this.elements.container = this.media; + this.media = iframe; // Reset classname + + this.elements.container.className = ''; // Get attributes from URL and set config + + if (url.search.length) { + const truthy = ['1', 'true']; + + if (truthy.includes(url.searchParams.get('autoplay'))) { + this.config.autoplay = true; + } + + if (truthy.includes(url.searchParams.get('loop'))) { + this.config.loop.active = true; + } // TODO: replace fullscreen.iosNative with this playsinline config option + // YouTube requires the playsinline in the URL + + + if (this.isYouTube) { + this.config.playsinline = truthy.includes(url.searchParams.get('playsinline')); + this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language? + } else { + this.config.playsinline = true; + } + } + } else { + // <div> with attributes + this.provider = this.media.getAttribute(this.config.attributes.embed.provider); // Remove attribute + + this.media.removeAttribute(this.config.attributes.embed.provider); + } // Unsupported or missing provider + + + if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) { + this.debug.error('Setup failed: Invalid provider'); + return; + } // Audio will come later for external providers + + + this.type = types.video; + break; + + case 'video': + case 'audio': + this.type = _type; + this.provider = providers.html5; // Get config from attributes + + if (this.media.hasAttribute('crossorigin')) { + this.config.crossorigin = true; + } + + if (this.media.hasAttribute('autoplay')) { + this.config.autoplay = true; + } + + if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) { + this.config.playsinline = true; + } + + if (this.media.hasAttribute('muted')) { + this.config.muted = true; + } + + if (this.media.hasAttribute('loop')) { + this.config.loop.active = true; + } + + break; + + default: + this.debug.error('Setup failed: unsupported type'); + return; + } // Check for support again but with type + + + this.supported = support.check(this.type, this.provider, this.config.playsinline); // If no support for even API, bail + + if (!this.supported.api) { + this.debug.error('Setup failed: no support'); + return; + } + + this.eventListeners = []; // Create listeners + + this.listeners = new Listeners(this); // Setup local storage for user settings + + this.storage = new Storage(this); // Store reference + + this.media.plyr = this; // Wrap media + + if (!is.element(this.elements.container)) { + this.elements.container = createElement('div', { + tabindex: 0 + }); + wrap(this.media, this.elements.container); + } // Migrate custom properties from media to container (so they work 😉) + + + ui.migrateStyles.call(this); // Add style hook + + ui.addStyleHook.call(this); // Setup media + + media.setup.call(this); // Listen for events if debugging + + if (this.config.debug) { + on.call(this, this.elements.container, this.config.events.join(' '), event => { + this.debug.log(`event: ${event.type}`); + }); + } // Setup fullscreen + + + this.fullscreen = new Fullscreen(this); // Setup interface + // If embed but not fully supported, build interface now to avoid flash of controls + + if (this.isHTML5 || this.isEmbed && !this.supported.ui) { + ui.build.call(this); + } // Container listeners + + + this.listeners.container(); // Global listeners + + this.listeners.global(); // Setup ads if provided + + if (this.config.ads.enabled) { + this.ads = new Ads(this); + } // Autoplay if required + + + if (this.isHTML5 && this.config.autoplay) { + this.once('canplay', () => silencePromise(this.play())); + } // 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); + } + } // --------------------------------------- + // API + // --------------------------------------- + + /** + * Types and provider helpers + */ + + + get isHTML5() { + return this.provider === providers.html5; + } + + get isEmbed() { + return this.isYouTube || this.isVimeo; + } + + get isYouTube() { + return this.provider === providers.youtube; + } + + get isVimeo() { + return this.provider === providers.vimeo; + } + + get isVideo() { + return this.type === types.video; + } + + get isAudio() { + return this.type === types.audio; + } + /** + * Play the media, or play the advertisement (if they are not blocked) + */ + + + /** + * Get playing state + */ + get playing() { + return Boolean(this.ready && !this.paused && !this.ended); + } + /** + * Get paused state + */ + + + get paused() { + return Boolean(this.media.paused); + } + /** + * Get stopped state + */ + + + get stopped() { + return Boolean(this.paused && this.currentTime === 0); + } + /** + * Get ended state + */ + + + get ended() { + return Boolean(this.media.ended); + } + /** + * Toggle playback based on current status + * @param {Boolean} input + */ + + + /** + * Seek to a time + * @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 + if (!this.duration) { + return; + } // Validate input + + + const inputIsValid = is.number(input) && input > 0; // Set + + this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0; // Logging + + this.debug.log(`Seeking to ${this.currentTime} seconds`); + } + /** + * Get current time + */ + + + get currentTime() { + return Number(this.media.currentTime); + } + /** + * Get buffered + */ + + + get buffered() { + const { + buffered + } = this.media; // YouTube / Vimeo return a float between 0-1 + + if (is.number(buffered)) { + return buffered; + } // HTML5 + // TODO: Handle buffered chunks of the media + // (i.e. seek to another section buffers only that section) + + + if (buffered && buffered.length && this.duration > 0) { + return buffered.end(0) / this.duration; + } + + return 0; + } + /** + * Get seeking status + */ + + + get seeking() { + return Boolean(this.media.seeking); + } + /** + * Get the duration of the current media + */ + + + get duration() { + // Faux duration set via config + const fauxDuration = parseFloat(this.config.duration); // Media duration can be NaN or Infinity before the media has loaded + + const realDuration = (this.media || {}).duration; + const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration; // If config duration is funky, use regular duration + + return fauxDuration || duration; + } + /** + * 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 + */ + + + set volume(value) { + let volume = value; + const max = 1; + const min = 0; + + if (is.string(volume)) { + volume = Number(volume); + } // Load volume from storage if no value specified + + + if (!is.number(volume)) { + volume = this.storage.get('volume'); + } // Use config if all else fails + + + if (!is.number(volume)) { + ({ + volume + } = this.config); + } // Maximum is volumeMax + + + if (volume > max) { + volume = max; + } // Minimum is volumeMin + + + if (volume < min) { + volume = min; + } // Update config + + + this.config.volume = volume; // Set the player volume + + this.media.volume = volume; // If muted, and we're increasing volume manually, reset muted state + + if (!is.empty(value) && this.muted && volume > 0) { + this.muted = false; + } + } + /** + * Get the current player volume + */ + + + get volume() { + return Number(this.media.volume); + } + /** + * Increase volume + * @param {Boolean} step - How much to decrease by (between 0 and 1) + */ + + + /** + * Set muted state + * @param {Boolean} mute + */ + set muted(mute) { + let toggle = mute; // Load muted state from storage + + if (!is.boolean(toggle)) { + toggle = this.storage.get('muted'); + } // Use config if all else fails + + + if (!is.boolean(toggle)) { + toggle = this.config.muted; + } // Update config + + + this.config.muted = toggle; // Set mute on the player + + this.media.muted = toggle; + } + /** + * Get current muted state + */ + + + get muted() { + return Boolean(this.media.muted); + } + /** + * Check if the media has audio + */ + + + get hasAudio() { + // Assume yes for all non HTML5 (as we can't tell...) + if (!this.isHTML5) { + return true; + } + + if (this.isAudio) { + return true; + } // Get audio tracks + + + return Boolean(this.media.mozHasAudio) || Boolean(this.media.webkitAudioDecodedByteCount) || Boolean(this.media.audioTracks && this.media.audioTracks.length); + } + /** + * Set playback speed + * @param {Number} speed - the speed of playback (0.5-2.0) + */ + + + set speed(input) { + let speed = null; + + if (is.number(input)) { + speed = input; + } + + if (!is.number(speed)) { + speed = this.storage.get('speed'); + } + + if (!is.number(speed)) { + speed = this.config.speed.selected; + } // Clamp to min/max + + + const { + minimumSpeed: min, + maximumSpeed: max + } = this; + speed = clamp(speed, min, max); // Update config + + this.config.speed.selected = speed; // Set media speed + + setTimeout(() => { + if (this.media) { + this.media.playbackRate = speed; + } + }, 0); + } + /** + * Get current playback speed + */ + + + get speed() { + return Number(this.media.playbackRate); + } + /** + * Get the minimum allowed speed + */ + + + get minimumSpeed() { + if (this.isYouTube) { + // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate + return Math.min(...this.options.speed); + } + + if (this.isVimeo) { + // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror + return 0.5; + } // https://stackoverflow.com/a/32320020/1191319 + + + return 0.0625; + } + /** + * Get the maximum allowed speed + */ + + + get maximumSpeed() { + if (this.isYouTube) { + // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate + return Math.max(...this.options.speed); + } + + if (this.isVimeo) { + // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror + return 2; + } // https://stackoverflow.com/a/32320020/1191319 + + + return 16; + } + /** + * Set playback quality + * Currently HTML5 & YouTube only + * @param {Number} input - Quality level + */ + + + set quality(input) { + const config = this.config.quality; + const options = this.options.quality; + + if (!options.length) { + return; + } + + let quality = [!is.empty(input) && Number(input), this.storage.get('quality'), config.selected, config.default].find(is.number); + let updateStorage = true; + + if (!options.includes(quality)) { + const value = closest(options, quality); + this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`); + quality = value; // Don't update storage if quality is not supported + + updateStorage = false; + } // Update config + + + config.selected = quality; // Set quality + + this.media.quality = quality; // Save to storage + + if (updateStorage) { + this.storage.set({ + quality + }); + } + } + /** + * Get current quality level + */ + + + get quality() { + return this.media.quality; + } + /** + * 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 + */ + + + set loop(input) { + const toggle = is.boolean(input) ? input : this.config.loop.active; + this.config.loop.active = toggle; + this.media.loop = toggle; // Set default to be a true toggle + + /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle'; + switch (type) { + case 'start': + if (this.config.loop.end && this.config.loop.end <= this.currentTime) { + this.config.loop.end = null; + } + this.config.loop.start = this.currentTime; + // this.config.loop.indicator.start = this.elements.display.played.value; + break; + case 'end': + if (this.config.loop.start >= this.currentTime) { + return this; + } + this.config.loop.end = this.currentTime; + // this.config.loop.indicator.end = this.elements.display.played.value; + break; + case 'all': + this.config.loop.start = 0; + this.config.loop.end = this.duration - 2; + this.config.loop.indicator.start = 0; + this.config.loop.indicator.end = 100; + break; + case 'toggle': + if (this.config.loop.active) { + this.config.loop.start = 0; + this.config.loop.end = null; + } else { + this.config.loop.start = 0; + this.config.loop.end = this.duration - 2; + } + break; + default: + this.config.loop.start = 0; + this.config.loop.end = null; + break; + } */ + } + /** + * Get current loop state + */ + + + get loop() { + return Boolean(this.media.loop); + } + /** + * Set new media source + * @param {Object} input - The new source object (see docs) + */ + + + set source(input) { + source.change.call(this, input); + } + /** + * Get current source + */ + + + get source() { + return this.media.currentSrc; + } + /** + * Get a download URL (either source or custom) + */ + + + get download() { + const { + download + } = this.config.urls; + return is.url(download) ? download : this.source; + } + /** + * Set the download URL + */ + + + set download(input) { + if (!is.url(input)) { + return; + } + + this.config.urls.download = input; + controls.setDownloadUrl.call(this); + } + /** + * Set the poster image for a video + * @param {String} input - the URL for the new poster image + */ + + + set poster(input) { + if (!this.isVideo) { + this.debug.warn('Poster can only be set for video'); + return; + } + + ui.setPoster.call(this, input, false).catch(() => {}); + } + /** + * Get the current poster image + */ + + + get poster() { + if (!this.isVideo) { + return null; + } + + return this.media.getAttribute('poster') || this.media.getAttribute('data-poster'); + } + /** + * Get the current aspect ratio in use + */ + + + get ratio() { + if (!this.isVideo) { + return null; + } + + const ratio = reduceAspectRatio(getAspectRatio.call(this)); + return is.array(ratio) ? ratio.join(':') : ratio; + } + /** + * Set video aspect ratio + */ + + + set ratio(input) { + if (!this.isVideo) { + this.debug.warn('Aspect ratio can only be set for video'); + return; + } + + if (!is.string(input) || !validateAspectRatio(input)) { + this.debug.error(`Invalid aspect ratio specified (${input})`); + return; + } + + this.config.ratio = reduceAspectRatio(input); + setAspectRatio.call(this); + } + /** + * Set the autoplay state + * @param {Boolean} input - Whether to autoplay or not + */ + + + set autoplay(input) { + const toggle = is.boolean(input) ? input : this.config.autoplay; + this.config.autoplay = toggle; + } + /** + * Get the current autoplay state + */ + + + get autoplay() { + return Boolean(this.config.autoplay); + } + /** + * Toggle captions + * @param {Boolean} input - Whether to enable captions + */ + + + toggleCaptions(input) { + captions.toggle.call(this, input, false); + } + /** + * Set the caption track by index + * @param {Number} - Caption index + */ + + + set currentTrack(input) { + captions.set.call(this, input, false); + captions.setup(); + } + /** + * Get the current caption track index (-1 if disabled) + */ + + + get currentTrack() { + const { + toggled, + currentTrack + } = this.captions; + return toggled ? currentTrack : -1; + } + /** + * 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) + */ + + + set language(input) { + captions.setLanguage.call(this, input, false); + } + /** + * Get the current track's language + */ + + + get language() { + return (captions.getCurrentTrack.call(this) || {}).language; + } + /** + * Toggle picture-in-picture playback on WebKit/MacOS + * TODO: update player with state, support, enabled + * TODO: detect outside changes + */ + + + set pip(input) { + // Bail if no support + if (!support.pip) { + return; + } // Toggle based on current state if not passed + + + const toggle = is.boolean(input) ? input : !this.pip; // Toggle based on current state + // Safari + + if (is.function(this.media.webkitSetPresentationMode)) { + this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive); + } // Chrome + + + if (is.function(this.media.requestPictureInPicture)) { + if (!this.pip && toggle) { + this.media.requestPictureInPicture(); + } else if (this.pip && !toggle) { + document.exitPictureInPicture(); + } + } + } + /** + * Get the current picture-in-picture state + */ + + + get pip() { + if (!support.pip) { + return null; + } // Safari + + + if (!is.empty(this.media.webkitPresentationMode)) { + return this.media.webkitPresentationMode === pip.active; + } // Chrome + + + return this.media === document.pictureInPictureElement; + } + /** + * Sets the preview thubmnails for the current source + */ + + + setPreviewThumbnails(thumbnailSource) { + if (this.previewThumbnails && this.previewThumbnails.loaded) { + this.previewThumbnails.destroy(); + this.previewThumbnails = null; + } + + Object.assign(this.config.previewThumbnails, thumbnailSource); // Create new instance if it is still enabled + + if (this.config.previewThumbnails.enabled) { + this.previewThumbnails = new PreviewThumbnails(this); + } + } + /** + * Trigger the airplay dialog + * TODO: update player with state, support, enabled + */ + + + /** + * Check for support + * @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); + } + /** + * Load an SVG sprite into the page + * @param {String} url - URL for the SVG sprite + * @param {String} [id] - Unique ID + */ + + + static loadSprite(url, id) { + return loadSprite(url, id); + } + /** + * Setup multiple instances + * @param {*} selector + * @param {Object} options + */ + + + static setup(selector, options = {}) { + let targets = null; + + if (is.string(selector)) { + targets = Array.from(document.querySelectorAll(selector)); + } else if (is.nodeList(selector)) { + targets = Array.from(selector); + } else if (is.array(selector)) { + targets = selector.filter(is.element); + } + + if (is.empty(targets)) { + return null; + } + + return targets.map(t => new Plyr(t, options)); + } + +} + +Plyr.defaults = cloneDeep(defaults); + +export { Plyr as default }; diff --git a/extlib/plyr/plyr.polyfilled.js b/extlib/plyr/plyr.polyfilled.js new file mode 100644 index 00000000..f2f362bc --- /dev/null +++ b/extlib/plyr/plyr.polyfilled.js @@ -0,0 +1,9215 @@ +typeof navigator === "object" && (function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define('Plyr', factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Plyr = factory()); +})(this, (function () { 'use strict'; + + // Polyfill for creating CustomEvents on IE9/10/11 + // code pulled from: + // https://github.com/d4tocchini/customevent-polyfill + // https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill + (function () { + if (typeof window === 'undefined') { + return; + } + + try { + var ce = new window.CustomEvent('test', { + cancelable: true + }); + ce.preventDefault(); + + if (ce.defaultPrevented !== true) { + // IE has problems with .preventDefault() on custom events + // http://stackoverflow.com/questions/23349191 + throw new Error('Could not prevent default'); + } + } catch (e) { + var CustomEvent = function (event, params) { + var evt, origPrevent; + params = params || {}; + params.bubbles = !!params.bubbles; + params.cancelable = !!params.cancelable; + evt = document.createEvent('CustomEvent'); + evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); + origPrevent = evt.preventDefault; + + evt.preventDefault = function () { + origPrevent.call(this); + + try { + Object.defineProperty(this, 'defaultPrevented', { + get: function () { + return true; + } + }); + } catch (e) { + this.defaultPrevented = true; + } + }; + + return evt; + }; + + CustomEvent.prototype = window.Event.prototype; + window.CustomEvent = CustomEvent; // expose definition to window + } + })(); + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + (function (global) { + /**
+ * Polyfill URLSearchParams
+ *
+ * Inspired from : https://github.com/WebReflection/url-search-params/blob/master/src/url-search-params.js
+ */ + var checkIfIteratorIsSupported = function () { + try { + return !!Symbol.iterator; + } catch (error) { + return false; + } + }; + + var iteratorSupported = checkIfIteratorIsSupported(); + + var createIterator = function (items) { + var iterator = { + next: function () { + var value = items.shift(); + return { + done: value === void 0, + value: value + }; + } + }; + + if (iteratorSupported) { + iterator[Symbol.iterator] = function () { + return iterator; + }; + } + + return iterator; + }; + /**
+ * Search param name and values should be encoded according to https://url.spec.whatwg.org/#urlencoded-serializing
+ * encodeURIComponent() produces the same result except encoding spaces as `%20` instead of `+`.
+ */ + + + var serializeParam = function (value) { + return encodeURIComponent(value).replace(/%20/g, '+'); + }; + + var deserializeParam = function (value) { + return decodeURIComponent(String(value).replace(/\+/g, ' ')); + }; + + var polyfillURLSearchParams = function () { + var URLSearchParams = function (searchString) { + Object.defineProperty(this, '_entries', { + writable: true, + value: {} + }); + var typeofSearchString = typeof searchString; + + if (typeofSearchString === 'undefined') ; else if (typeofSearchString === 'string') { + if (searchString !== '') { + this._fromString(searchString); + } + } else if (searchString instanceof URLSearchParams) { + var _this = this; + + searchString.forEach(function (value, name) { + _this.append(name, value); + }); + } else if (searchString !== null && typeofSearchString === 'object') { + if (Object.prototype.toString.call(searchString) === '[object Array]') { + for (var i = 0; i < searchString.length; i++) { + var entry = searchString[i]; + + if (Object.prototype.toString.call(entry) === '[object Array]' || entry.length !== 2) { + this.append(entry[0], entry[1]); + } else { + throw new TypeError('Expected [string, any] as entry at index ' + i + ' of URLSearchParams\'s input'); + } + } + } else { + for (var key in searchString) { + if (searchString.hasOwnProperty(key)) { + this.append(key, searchString[key]); + } + } + } + } else { + throw new TypeError('Unsupported input\'s type for URLSearchParams'); + } + }; + + var proto = URLSearchParams.prototype; + + proto.append = function (name, value) { + if (name in this._entries) { + this._entries[name].push(String(value)); + } else { + this._entries[name] = [String(value)]; + } + }; + + proto.delete = function (name) { + delete this._entries[name]; + }; + + proto.get = function (name) { + return name in this._entries ? this._entries[name][0] : null; + }; + + proto.getAll = function (name) { + return name in this._entries ? this._entries[name].slice(0) : []; + }; + + proto.has = function (name) { + return name in this._entries; + }; + + proto.set = function (name, value) { + this._entries[name] = [String(value)]; + }; + + proto.forEach = function (callback, thisArg) { + var entries; + + for (var name in this._entries) { + if (this._entries.hasOwnProperty(name)) { + entries = this._entries[name]; + + for (var i = 0; i < entries.length; i++) { + callback.call(thisArg, entries[i], name, this); + } + } + } + }; + + proto.keys = function () { + var items = []; + this.forEach(function (value, name) { + items.push(name); + }); + return createIterator(items); + }; + + proto.values = function () { + var items = []; + this.forEach(function (value) { + items.push(value); + }); + return createIterator(items); + }; + + proto.entries = function () { + var items = []; + this.forEach(function (value, name) { + items.push([name, value]); + }); + return createIterator(items); + }; + + if (iteratorSupported) { + proto[Symbol.iterator] = proto.entries; + } + + proto.toString = function () { + var searchArray = []; + this.forEach(function (value, name) { + searchArray.push(serializeParam(name) + '=' + serializeParam(value)); + }); + return searchArray.join('&'); + }; + + global.URLSearchParams = URLSearchParams; + }; + + var checkIfURLSearchParamsSupported = function () { + try { + var URLSearchParams = global.URLSearchParams; + return new URLSearchParams('?a=1').toString() === 'a=1' && typeof URLSearchParams.prototype.set === 'function' && typeof URLSearchParams.prototype.entries === 'function'; + } catch (e) { + return false; + } + }; + + if (!checkIfURLSearchParamsSupported()) { + polyfillURLSearchParams(); + } + + var proto = global.URLSearchParams.prototype; + + if (typeof proto.sort !== 'function') { + proto.sort = function () { + var _this = this; + + var items = []; + this.forEach(function (value, name) { + items.push([name, value]); + + if (!_this._entries) { + _this.delete(name); + } + }); + items.sort(function (a, b) { + if (a[0] < b[0]) { + return -1; + } else if (a[0] > b[0]) { + return +1; + } else { + return 0; + } + }); + + if (_this._entries) { + // force reset because IE keeps keys index + _this._entries = {}; + } + + for (var i = 0; i < items.length; i++) { + this.append(items[i][0], items[i][1]); + } + }; + } + + if (typeof proto._fromString !== 'function') { + Object.defineProperty(proto, '_fromString', { + enumerable: false, + configurable: false, + writable: false, + value: function (searchString) { + if (this._entries) { + this._entries = {}; + } else { + var keys = []; + this.forEach(function (value, name) { + keys.push(name); + }); + + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + + searchString = searchString.replace(/^\?/, ''); + var attributes = searchString.split('&'); + var attribute; + + for (var i = 0; i < attributes.length; i++) { + attribute = attributes[i].split('='); + this.append(deserializeParam(attribute[0]), attribute.length > 1 ? deserializeParam(attribute[1]) : ''); + } + } + }); + } // HTMLAnchorElement + + })(typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal); + + (function (global) { + /**
+ * Polyfill URL
+ *
+ * Inspired from : https://github.com/arv/DOM-URL-Polyfill/blob/master/src/url.js
+ */ + var checkIfURLIsSupported = function () { + try { + var u = new global.URL('b', 'http://a'); + u.pathname = 'c d'; + return u.href === 'http://a/c%20d' && u.searchParams; + } catch (e) { + return false; + } + }; + + var polyfillURL = function () { + var _URL = global.URL; + + var URL = function (url, base) { + if (typeof url !== 'string') url = String(url); + if (base && typeof base !== 'string') base = String(base); // Only create another document if the base is different from current location. + + var doc = document, + baseElement; + + if (base && (global.location === void 0 || base !== global.location.href)) { + base = base.toLowerCase(); + doc = document.implementation.createHTMLDocument(''); + baseElement = doc.createElement('base'); + baseElement.href = base; + doc.head.appendChild(baseElement); + + try { + if (baseElement.href.indexOf(base) !== 0) throw new Error(baseElement.href); + } catch (err) { + throw new Error('URL unable to set base ' + base + ' due to ' + err); + } + } + + var anchorElement = doc.createElement('a'); + anchorElement.href = url; + + if (baseElement) { + doc.body.appendChild(anchorElement); + anchorElement.href = anchorElement.href; // force href to refresh + } + + var inputElement = doc.createElement('input'); + inputElement.type = 'url'; + inputElement.value = url; + + if (anchorElement.protocol === ':' || !/:/.test(anchorElement.href) || !inputElement.checkValidity() && !base) { + throw new TypeError('Invalid URL'); + } + + Object.defineProperty(this, '_anchorElement', { + value: anchorElement + }); // create a linked searchParams which reflect its changes on URL + + var searchParams = new global.URLSearchParams(this.search); + var enableSearchUpdate = true; + var enableSearchParamsUpdate = true; + + var _this = this; + + ['append', 'delete', 'set'].forEach(function (methodName) { + var method = searchParams[methodName]; + + searchParams[methodName] = function () { + method.apply(searchParams, arguments); + + if (enableSearchUpdate) { + enableSearchParamsUpdate = false; + _this.search = searchParams.toString(); + enableSearchParamsUpdate = true; + } + }; + }); + Object.defineProperty(this, 'searchParams', { + value: searchParams, + enumerable: true + }); + var search = void 0; + Object.defineProperty(this, '_updateSearchParams', { + enumerable: false, + configurable: false, + writable: false, + value: function () { + if (this.search !== search) { + search = this.search; + + if (enableSearchParamsUpdate) { + enableSearchUpdate = false; + + this.searchParams._fromString(this.search); + + enableSearchUpdate = true; + } + } + } + }); + }; + + var proto = URL.prototype; + + var linkURLWithAnchorAttribute = function (attributeName) { + Object.defineProperty(proto, attributeName, { + get: function () { + return this._anchorElement[attributeName]; + }, + set: function (value) { + this._anchorElement[attributeName] = value; + }, + enumerable: true + }); + }; + + ['hash', 'host', 'hostname', 'port', 'protocol'].forEach(function (attributeName) { + linkURLWithAnchorAttribute(attributeName); + }); + Object.defineProperty(proto, 'search', { + get: function () { + return this._anchorElement['search']; + }, + set: function (value) { + this._anchorElement['search'] = value; + + this._updateSearchParams(); + }, + enumerable: true + }); + Object.defineProperties(proto, { + 'toString': { + get: function () { + var _this = this; + + return function () { + return _this.href; + }; + } + }, + 'href': { + get: function () { + return this._anchorElement.href.replace(/\?$/, ''); + }, + set: function (value) { + this._anchorElement.href = value; + + this._updateSearchParams(); + }, + enumerable: true + }, + 'pathname': { + get: function () { + return this._anchorElement.pathname.replace(/(^\/?)/, '/'); + }, + set: function (value) { + this._anchorElement.pathname = value; + }, + enumerable: true + }, + 'origin': { + get: function () { + // get expected port from protocol + var expectedPort = { + 'http:': 80, + 'https:': 443, + 'ftp:': 21 + }[this._anchorElement.protocol]; // add port to origin if, expected port is different than actual port + // and it is not empty f.e http://foo:8080 + // 8080 != 80 && 8080 != '' + + var addPortToOrigin = this._anchorElement.port != expectedPort && this._anchorElement.port !== ''; + return this._anchorElement.protocol + '//' + this._anchorElement.hostname + (addPortToOrigin ? ':' + this._anchorElement.port : ''); + }, + enumerable: true + }, + 'password': { + // TODO + get: function () { + return ''; + }, + set: function (value) {}, + enumerable: true + }, + 'username': { + // TODO + get: function () { + return ''; + }, + set: function (value) {}, + enumerable: true + } + }); + + URL.createObjectURL = function (blob) { + return _URL.createObjectURL.apply(_URL, arguments); + }; + + URL.revokeObjectURL = function (url) { + return _URL.revokeObjectURL.apply(_URL, arguments); + }; + + global.URL = URL; + }; + + if (!checkIfURLIsSupported()) { + polyfillURL(); + } + + if (global.location !== void 0 && !('origin' in global.location)) { + var getOrigin = function () { + return global.location.protocol + '//' + global.location.hostname + (global.location.port ? ':' + global.location.port : ''); + }; + + try { + Object.defineProperty(global.location, 'origin', { + get: getOrigin, + enumerable: true + }); + } catch (e) { + setInterval(function () { + global.location.origin = getOrigin(); + }, 100); + } + } + })(typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal); + + function _defineProperty$1(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; + } + + function _classCallCheck(e, t) { + if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function"); + } + + function _defineProperties(e, t) { + for (var n = 0; n < t.length; n++) { + var r = t[n]; + r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r); + } + } + + function _createClass(e, t, n) { + return t && _defineProperties(e.prototype, t), n && _defineProperties(e, n), e; + } + + function _defineProperty(e, t, n) { + return t in e ? Object.defineProperty(e, t, { + value: n, + enumerable: !0, + configurable: !0, + writable: !0 + }) : e[t] = n, e; + } + + function ownKeys(e, t) { + var n = Object.keys(e); + + if (Object.getOwnPropertySymbols) { + var r = Object.getOwnPropertySymbols(e); + t && (r = r.filter(function (t) { + return Object.getOwnPropertyDescriptor(e, t).enumerable; + })), n.push.apply(n, r); + } + + return n; + } + + function _objectSpread2(e) { + for (var t = 1; t < arguments.length; t++) { + var n = null != arguments[t] ? arguments[t] : {}; + t % 2 ? ownKeys(Object(n), !0).forEach(function (t) { + _defineProperty(e, t, n[t]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : ownKeys(Object(n)).forEach(function (t) { + Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)); + }); + } + + return e; + } + + var defaults$1 = { + addCSS: !0, + thumbWidth: 15, + watch: !0 + }; + + function matches$1(e, t) { + return function () { + return Array.from(document.querySelectorAll(t)).includes(this); + }.call(e, t); + } + + function trigger(e, t) { + if (e && t) { + var n = new Event(t, { + bubbles: !0 + }); + e.dispatchEvent(n); + } + } + + var getConstructor$1 = function (e) { + return null != e ? e.constructor : null; + }, + instanceOf$1 = function (e, t) { + return !!(e && t && e instanceof t); + }, + isNullOrUndefined$1 = function (e) { + return null == e; + }, + isObject$1 = function (e) { + return getConstructor$1(e) === Object; + }, + isNumber$1 = function (e) { + return getConstructor$1(e) === Number && !Number.isNaN(e); + }, + isString$1 = function (e) { + return getConstructor$1(e) === String; + }, + isBoolean$1 = function (e) { + return getConstructor$1(e) === Boolean; + }, + isFunction$1 = function (e) { + return getConstructor$1(e) === Function; + }, + isArray$1 = function (e) { + return Array.isArray(e); + }, + isNodeList$1 = function (e) { + return instanceOf$1(e, NodeList); + }, + isElement$1 = function (e) { + return instanceOf$1(e, Element); + }, + isEvent$1 = function (e) { + return instanceOf$1(e, Event); + }, + isEmpty$1 = function (e) { + return isNullOrUndefined$1(e) || (isString$1(e) || isArray$1(e) || isNodeList$1(e)) && !e.length || isObject$1(e) && !Object.keys(e).length; + }, + is$1 = { + nullOrUndefined: isNullOrUndefined$1, + object: isObject$1, + number: isNumber$1, + string: isString$1, + boolean: isBoolean$1, + function: isFunction$1, + array: isArray$1, + nodeList: isNodeList$1, + element: isElement$1, + event: isEvent$1, + empty: isEmpty$1 + }; + + function getDecimalPlaces(e) { + var t = "".concat(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); + return t ? Math.max(0, (t[1] ? t[1].length : 0) - (t[2] ? +t[2] : 0)) : 0; + } + + function round(e, t) { + if (1 > t) { + var n = getDecimalPlaces(t); + return parseFloat(e.toFixed(n)); + } + + return Math.round(e / t) * t; + } + + var RangeTouch = function () { + function e(t, n) { + _classCallCheck(this, e), is$1.element(t) ? this.element = t : is$1.string(t) && (this.element = document.querySelector(t)), is$1.element(this.element) && is$1.empty(this.element.rangeTouch) && (this.config = _objectSpread2({}, defaults$1, {}, n), this.init()); + } + + return _createClass(e, [{ + key: "init", + value: function () { + e.enabled && (this.config.addCSS && (this.element.style.userSelect = "none", this.element.style.webKitUserSelect = "none", this.element.style.touchAction = "manipulation"), this.listeners(!0), this.element.rangeTouch = this); + } + }, { + key: "destroy", + value: function () { + e.enabled && (this.config.addCSS && (this.element.style.userSelect = "", this.element.style.webKitUserSelect = "", this.element.style.touchAction = ""), this.listeners(!1), this.element.rangeTouch = null); + } + }, { + key: "listeners", + value: function (e) { + var t = this, + n = e ? "addEventListener" : "removeEventListener"; + ["touchstart", "touchmove", "touchend"].forEach(function (e) { + t.element[n](e, function (e) { + return t.set(e); + }, !1); + }); + } + }, { + key: "get", + value: function (t) { + if (!e.enabled || !is$1.event(t)) return null; + var n, + r = t.target, + i = t.changedTouches[0], + o = parseFloat(r.getAttribute("min")) || 0, + s = parseFloat(r.getAttribute("max")) || 100, + u = parseFloat(r.getAttribute("step")) || 1, + c = r.getBoundingClientRect(), + a = 100 / c.width * (this.config.thumbWidth / 2) / 100; + return 0 > (n = 100 / c.width * (i.clientX - c.left)) ? n = 0 : 100 < n && (n = 100), 50 > n ? n -= (100 - 2 * n) * a : 50 < n && (n += 2 * (n - 50) * a), o + round(n / 100 * (s - o), u); + } + }, { + key: "set", + value: function (t) { + e.enabled && is$1.event(t) && !t.target.disabled && (t.preventDefault(), t.target.value = this.get(t), trigger(t.target, "touchend" === t.type ? "change" : "input")); + } + }], [{ + key: "setup", + value: function (t) { + var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}, + r = null; + if (is$1.empty(t) || is$1.string(t) ? r = Array.from(document.querySelectorAll(is$1.string(t) ? t : 'input[type="range"]')) : is$1.element(t) ? r = [t] : is$1.nodeList(t) ? r = Array.from(t) : is$1.array(t) && (r = t.filter(is$1.element)), is$1.empty(r)) return null; + + var i = _objectSpread2({}, defaults$1, {}, n); + + if (is$1.string(t) && i.watch) { + var o = new MutationObserver(function (n) { + Array.from(n).forEach(function (n) { + Array.from(n.addedNodes).forEach(function (n) { + is$1.element(n) && matches$1(n, t) && new e(n, i); + }); + }); + }); + o.observe(document.body, { + childList: !0, + subtree: !0 + }); + } + + return r.map(function (t) { + return new e(t, n); + }); + } + }, { + key: "enabled", + get: function () { + return "ontouchstart" in document.documentElement; + } + }]), e; + }(); + + // ========================================================================== + // Type checking utils + // ========================================================================== + const getConstructor = input => input !== null && typeof input !== 'undefined' ? input.constructor : null; + + const instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor); + + const isNullOrUndefined = input => input === null || typeof input === 'undefined'; + + const isObject = input => getConstructor(input) === Object; + + const isNumber = input => getConstructor(input) === Number && !Number.isNaN(input); + + const isString = input => getConstructor(input) === String; + + const isBoolean = input => getConstructor(input) === Boolean; + + const isFunction = input => getConstructor(input) === Function; + + const isArray = input => Array.isArray(input); + + const isWeakMap = input => instanceOf(input, WeakMap); + + const isNodeList = input => instanceOf(input, NodeList); + + const isTextNode = input => getConstructor(input) === Text; + + 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) && isFunction(input.then); + + const isElement = input => input !== null && typeof input === 'object' && input.nodeType === 1 && typeof input.style === 'object' && typeof input.ownerDocument === 'object'; + + const isEmpty = input => isNullOrUndefined(input) || (isString(input) || isArray(input) || isNodeList(input)) && !input.length || isObject(input) && !Object.keys(input).length; + + const isUrl = input => { + // Accept a URL object + if (instanceOf(input, window.URL)) { + return true; + } // Must be string from here + + + if (!isString(input)) { + return false; + } // Add the protocol if required + + + let string = input; + + if (!input.startsWith('http://') || !input.startsWith('https://')) { + string = `http://${input}`; + } + + try { + return !isEmpty(new URL(string).hostname); + } catch (_) { + return false; + } + }; + + var is = { + nullOrUndefined: isNullOrUndefined, + object: isObject, + number: isNumber, + string: isString, + boolean: isBoolean, + function: isFunction, + array: isArray, + weakMap: isWeakMap, + nodeList: isNodeList, + element: isElement, + textNode: isTextNode, + event: isEvent, + keyboardEvent: isKeyboardEvent, + cue: isCue, + track: isTrack, + promise: isPromise, + url: isUrl, + empty: isEmpty + }; + + // ========================================================================== + const transitionEndEvent = (() => { + const element = document.createElement('span'); + const events = { + WebkitTransition: 'webkitTransitionEnd', + MozTransition: 'transitionend', + OTransition: 'oTransitionEnd otransitionend', + transition: 'transitionend' + }; + const type = Object.keys(events).find(event => element.style[event] !== undefined); + return is.string(type) ? events[type] : false; + })(); // Force repaint of element + + function repaint(element, delay) { + setTimeout(() => { + try { + // eslint-disable-next-line no-param-reassign + element.hidden = true; // eslint-disable-next-line no-unused-expressions + + element.offsetHeight; // eslint-disable-next-line no-param-reassign + + element.hidden = false; + } catch (_) {// Do nothing + } + }, delay); + } + + // ========================================================================== + // Browser sniffing + // Unfortunately, due to mixed support, UA sniffing is required + // ========================================================================== + const browser = { + isIE: Boolean(window.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: navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 || /(iPad|iPhone|iPod)/gi.test(navigator.platform) + }; + + // ========================================================================== + + function cloneDeep(object) { + return JSON.parse(JSON.stringify(object)); + } // Get a nested value in an object + + function getDeep(object, path) { + return path.split('.').reduce((obj, key) => obj && obj[key], object); + } // Deep extend destination object with N more objects + + function extend(target = {}, ...sources) { + if (!sources.length) { + return target; + } + + const source = sources.shift(); + + if (!is.object(source)) { + return target; + } + + Object.keys(source).forEach(key => { + if (is.object(source[key])) { + if (!Object.keys(target).includes(key)) { + Object.assign(target, { + [key]: {} + }); + } + + extend(target[key], source[key]); + } else { + Object.assign(target, { + [key]: source[key] + }); + } + }); + return extend(target, ...sources); + } + + // ========================================================================== + + function wrap(elements, wrapper) { + // Convert `elements` to an array, if necessary. + const targets = elements.length ? elements : [elements]; // Loops backwards to prevent having to clone the wrapper on the + // first element (see `child` below). + + Array.from(targets).reverse().forEach((element, index) => { + const child = index > 0 ? wrapper.cloneNode(true) : wrapper; // Cache the current parent and sibling. + + const parent = element.parentNode; + const sibling = element.nextSibling; // Wrap the element (is automatically removed from its current + // parent). + + child.appendChild(element); // If the element had a sibling, insert the wrapper before + // the sibling to maintain the HTML structure; otherwise, just + // append it to the parent. + + if (sibling) { + parent.insertBefore(child, sibling); + } else { + parent.appendChild(child); + } + }); + } // Set attributes + + function setAttributes(element, attributes) { + if (!is.element(element) || is.empty(attributes)) { + return; + } // Assume null and undefined attributes should be left out, + // Setting them would otherwise convert them to "null" and "undefined" + + + Object.entries(attributes).filter(([, value]) => !is.nullOrUndefined(value)).forEach(([key, value]) => element.setAttribute(key, value)); + } // Create a DocumentFragment + + function createElement(type, attributes, text) { + // Create a new <element> + const element = document.createElement(type); // Set all passed attributes + + if (is.object(attributes)) { + setAttributes(element, attributes); + } // Add text node + + + if (is.string(text)) { + element.innerText = text; + } // Return built element + + + return element; + } // Inaert an element after another + + function insertAfter(element, target) { + if (!is.element(element) || !is.element(target)) { + return; + } + + target.parentNode.insertBefore(element, target.nextSibling); + } // Insert a DocumentFragment + + function insertElement(type, parent, attributes, text) { + if (!is.element(parent)) { + return; + } + + parent.appendChild(createElement(type, attributes, text)); + } // Remove element(s) + + function removeElement(element) { + if (is.nodeList(element) || is.array(element)) { + Array.from(element).forEach(removeElement); + return; + } + + if (!is.element(element) || !is.element(element.parentNode)) { + return; + } + + element.parentNode.removeChild(element); + } // Remove all child elements + + function emptyElement(element) { + if (!is.element(element)) { + return; + } + + let { + length + } = element.childNodes; + + while (length > 0) { + element.removeChild(element.lastChild); + length -= 1; + } + } // Replace element + + function replaceElement(newChild, oldChild) { + if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) { + return null; + } + + oldChild.parentNode.replaceChild(newChild, oldChild); + return newChild; + } // Get an attribute object from a string selector + + function getAttributesFromSelector(sel, existingAttributes) { + // For example: + // '.test' to { class: 'test' } + // '#test' to { id: 'test' } + // '[data-test="test"]' to { 'data-test': 'test' } + if (!is.string(sel) || is.empty(sel)) { + return {}; + } + + const attributes = {}; + const existing = extend({}, existingAttributes); + sel.split(',').forEach(s => { + // Remove whitespace + const selector = s.trim(); + const className = selector.replace('.', ''); + const stripped = selector.replace(/[[\]]/g, ''); // Get the parts and value + + const parts = stripped.split('='); + const [key] = parts; + const value = parts.length > 1 ? parts[1].replace(/["']/g, '') : ''; // Get the first character + + const start = selector.charAt(0); + + switch (start) { + case '.': + // Add to existing classname + if (is.string(existing.class)) { + attributes.class = `${existing.class} ${className}`; + } else { + attributes.class = className; + } + + break; + + case '#': + // ID selector + attributes.id = selector.replace('#', ''); + break; + + case '[': + // Attribute selector + attributes[key] = value; + break; + } + }); + return extend(existing, attributes); + } // Toggle hidden + + function toggleHidden(element, hidden) { + if (!is.element(element)) { + return; + } + + let hide = hidden; + + if (!is.boolean(hide)) { + hide = !element.hidden; + } // eslint-disable-next-line no-param-reassign + + + element.hidden = hide; + } // Mirror Element.classList.toggle, with IE compatibility for "force" argument + + function toggleClass(element, className, force) { + if (is.nodeList(element)) { + return Array.from(element).map(e => toggleClass(e, className, force)); + } + + if (is.element(element)) { + let method = 'toggle'; + + if (typeof force !== 'undefined') { + method = force ? 'add' : 'remove'; + } + + element.classList[method](className); + return element.classList.contains(className); + } + + return false; + } // Has class name + + function hasClass(element, className) { + return is.element(element) && element.classList.contains(className); + } // Element matches selector + + function matches(element, selector) { + const { + prototype + } = Element; + + function match() { + return Array.from(document.querySelectorAll(selector)).includes(this); + } + + const method = prototype.matches || prototype.webkitMatchesSelector || prototype.mozMatchesSelector || prototype.msMatchesSelector || match; + return method.call(element, selector); + } // Closest ancestor element matching selector (also tests element itself) + + function closest$1(element, selector) { + const { + prototype + } = Element; // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill + + function closestElement() { + let el = this; + + do { + if (matches.matches(el, selector)) return el; + el = el.parentElement || el.parentNode; + } while (el !== null && el.nodeType === 1); + + return null; + } + + const method = prototype.closest || closestElement; + return method.call(element, selector); + } // Find all elements + + function getElements(selector) { + return this.elements.container.querySelectorAll(selector); + } // Find a single element + + function getElement(selector) { + return this.elements.container.querySelector(selector); + } // Set focus and tab focus class + + function setFocus(element = null, tabFocus = false) { + if (!is.element(element)) { + return; + } // Set regular focus + + + element.focus({ + preventScroll: true + }); // If we want to mimic keyboard focus via tab + + if (tabFocus) { + toggleClass(element, this.config.classNames.tabFocus); + } + } + + // ========================================================================== + + const defaultCodecs = { + 'audio/ogg': 'vorbis', + 'audio/wav': '1', + 'video/webm': 'vp8, vorbis', + 'video/mp4': 'avc1.42E01E, mp4a.40.2', + 'video/ogg': 'theora' + }; // Check for feature support + + const support = { + // Basic support + audio: 'canPlayType' in document.createElement('audio'), + video: 'canPlayType' in document.createElement('video'), + + // Check for support + // Basic functionality vs full UI + check(type, provider, playsinline) { + const canPlayInline = browser.isIPhone && playsinline && support.playsinline; + const api = support[type] || provider !== 'html5'; + const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline); + return { + api, + ui + }; + }, + + // Picture-in-picture support + // Safari & Chrome only currently + pip: (() => { + if (browser.isIPhone) { + return false; + } // Safari + // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls + + + if (is.function(createElement('video').webkitSetPresentationMode)) { + return true; + } // Chrome + // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture + + + if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) { + return true; + } + + return false; + })(), + // Airplay support + // Safari only currently + airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent), + // Inline playback support + // https://webkit.org/blog/6784/new-video-policies-for-ios/ + playsinline: 'playsInline' in document.createElement('video'), + + // Check for mime type support against a player instance + // Credits: http://diveintohtml5.info/everything.html + // Related: http://www.leanbackplayer.com/test/h5mt.html + 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) { + return false; + } // Add codec if required + + + if (Object.keys(defaultCodecs).includes(type)) { + type += `; codecs="${defaultCodecs[input]}"`; + } + + try { + return Boolean(type && this.media.canPlayType(type).replace(/no/, '')); + } catch (_) { + return false; + } + }, + + // Check for textTracks support + textTracks: 'textTracks' in document.createElement('video'), + // <input type="range"> Sliders + rangeInput: (() => { + const range = document.createElement('input'); + range.type = 'range'; + return range.type === 'range'; + })(), + // Touch + // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event + touch: 'ontouchstart' in document.documentElement, + // Detect transitions support + transitions: transitionEndEvent !== false, + // Reduced motion iOS & MacOS setting + // https://webkit.org/blog/7551/responsive-design-for-motion/ + reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches + }; + + // ========================================================================== + // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md + // https://www.youtube.com/watch?v=NPM6172J22g + + const supportsPassiveListeners = (() => { + // Test via a getter in the options object to see if the passive property is accessed + let supported = false; + + try { + const options = Object.defineProperty({}, 'passive', { + get() { + supported = true; + return null; + } + + }); + window.addEventListener('test', null, options); + window.removeEventListener('test', null, options); + } catch (_) {// Do nothing + } + + return supported; + })(); // Toggle event listener + + + function toggleListener(element, event, callback, toggle = false, passive = true, capture = false) { + // Bail if no element, event, or callback + if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) { + return; + } // Allow multiple events + + + const events = event.split(' '); // Build options + // Default to just the capture boolean for browsers with no passive listener support + + let options = capture; // If passive events listeners are supported + + if (supportsPassiveListeners) { + options = { + // Whether the listener can be passive (i.e. default never prevented) + passive, + // Whether the listener is a capturing listener or not + capture + }; + } // If a single node is passed, bind the event listener + + + events.forEach(type => { + if (this && this.eventListeners && toggle) { + // Cache event listener + this.eventListeners.push({ + element, + type, + callback, + options + }); + } + + element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options); + }); + } // Bind event handler + + function on(element, events = '', callback, passive = true, capture = false) { + toggleListener.call(this, element, events, callback, true, passive, capture); + } // Unbind event handler + + function off(element, events = '', callback, passive = true, capture = false) { + toggleListener.call(this, element, events, callback, false, passive, capture); + } // Bind once-only event handler + + function once(element, events = '', callback, passive = true, capture = false) { + const onceCallback = (...args) => { + off(element, events, onceCallback, passive, capture); + callback.apply(this, args); + }; + + toggleListener.call(this, element, events, onceCallback, true, passive, capture); + } // Trigger event + + function triggerEvent(element, type = '', bubbles = false, detail = {}) { + // Bail if no element + if (!is.element(element) || is.empty(type)) { + return; + } // Create and dispatch the event + + + const event = new CustomEvent(type, { + bubbles, + detail: { ...detail, + plyr: this + } + }); // Dispatch the event + + element.dispatchEvent(event); + } // Unbind all cached event listeners + + function unbindListeners() { + if (this && this.eventListeners) { + this.eventListeners.forEach(item => { + const { + element, + type, + callback, + options + } = item; + element.removeEventListener(type, callback, options); + }); + this.eventListeners = []; + } + } // Run method when / if player is ready + + function ready() { + return new Promise(resolve => this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve)).then(() => {}); + } + + /** + * Silence a Promise-like object. + * This is useful for avoiding non-harmful, but potentially confusing "uncaught + * play promise" rejection error messages. + * @param {Object} value An object that may or may not be `Promise`-like. + */ + + function silencePromise(value) { + if (is.promise(value)) { + value.then(null, () => {}); + } + } + + // ========================================================================== + + function dedupe(array) { + if (!is.array(array)) { + return array; + } + + return array.filter((item, index) => array.indexOf(item) === index); + } // Get the closest value in an array + + function closest(array, value) { + if (!is.array(array) || !array.length) { + return null; + } + + return array.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev); + } + + // ========================================================================== + + function supportsCSS(declaration) { + if (!window || !window.CSS) { + return false; + } + + return window.CSS.supports(declaration); + } // Standard/common aspect ratios + + const standardRatios = [[1, 1], [4, 3], [3, 4], [5, 4], [4, 5], [3, 2], [2, 3], [16, 10], [10, 16], [16, 9], [9, 16], [21, 9], [9, 21], [32, 9], [9, 32]].reduce((out, [x, y]) => ({ ...out, + [x / y]: [x, y] + }), {}); // Validate an aspect ratio + + function validateAspectRatio(input) { + if (!is.array(input) && (!is.string(input) || !input.includes(':'))) { + return false; + } + + const ratio = is.array(input) ? input : input.split(':'); + return ratio.map(Number).every(is.number); + } // Reduce an aspect ratio to it's lowest form + + function reduceAspectRatio(ratio) { + if (!is.array(ratio) || !ratio.every(is.number)) { + return null; + } + + const [width, height] = ratio; + + const getDivider = (w, h) => h === 0 ? w : getDivider(h, w % h); + + const divider = getDivider(width, height); + return [width / divider, height / divider]; + } // Calculate an aspect ratio + + function getAspectRatio(input) { + const parse = ratio => validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null; // Try provided ratio + + + let ratio = parse(input); // Get from config + + if (ratio === null) { + ratio = parse(this.config.ratio); + } // Get from embed + + + if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) { + ({ + ratio + } = this.embed); + } // Get from HTML5 video + + + if (ratio === null && this.isHTML5) { + const { + videoWidth, + videoHeight + } = this.media; + ratio = [videoWidth, videoHeight]; + } + + return reduceAspectRatio(ratio); + } // Set aspect ratio for responsive container + + function setAspectRatio(input) { + if (!this.isVideo) { + return {}; + } + + const { + wrapper + } = this.elements; + const ratio = getAspectRatio.call(this, input); + + if (!is.array(ratio)) { + return {}; + } + + const [x, y] = reduceAspectRatio(ratio); + const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`); + const padding = 100 / x * y; + + if (useNative) { + wrapper.style.aspectRatio = `${x}/${y}`; + } else { + wrapper.style.paddingBottom = `${padding}%`; + } // For Vimeo we have an extra <div> to hide the standard controls and UI + + + if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) { + const height = 100 / this.media.offsetWidth * parseInt(window.getComputedStyle(this.media).paddingBottom, 10); + const offset = (height - padding) / (height / 50); + + if (this.fullscreen.active) { + wrapper.style.paddingBottom = null; + } else { + this.media.style.transform = `translateY(-${offset}%)`; + } + } else if (this.isHTML5) { + wrapper.classList.add(this.config.classNames.videoFixedRatio); + } + + return { + padding, + ratio + }; + } // Round an aspect ratio to closest standard ratio + + function roundAspectRatio(x, y, tolerance = 0.05) { + const ratio = x / y; + const closestRatio = closest(Object.keys(standardRatios), ratio); // Check match is within tolerance + + if (Math.abs(closestRatio - ratio) <= tolerance) { + return standardRatios[closestRatio]; + } // No match + + + return [x, y]; + } // Get the size of the viewport + // https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions + + function getViewportSize() { + const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0); + const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0); + return [width, height]; + } + + // ========================================================================== + const html5 = { + getSources() { + if (!this.isHTML5) { + return []; + } + + const sources = Array.from(this.media.querySelectorAll('source')); // 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 + getQualityOptions() { + // Whether we're forcing all options (e.g. for streaming) + if (this.config.quality.forced) { + return this.config.quality.options; + } // Get sizes from <source> elements + + + return html5.getSources.call(this).map(source => Number(source.getAttribute('data-res'))).filter(Boolean); + }, + + setup() { + if (!this.isHTML5) { + return; + } + + const player = this; // Set speed options from config + + player.options.speed = player.config.speed.options; // Set aspect ratio if fixed + + if (!is.empty(this.config.ratio)) { + setAspectRatio.call(player); + } // Quality + + + Object.defineProperty(player.media, 'quality', { + get() { + // Get sources + const sources = html5.getSources.call(player); + const source = sources.find(s => s.getAttribute('src') === player.source); // Return size, if match is found + + return source && Number(source.getAttribute('data-res')); + }, + + set(input) { + if (player.quality === input) { + return; + } // If we're using an external handler... + + + if (player.config.quality.forced && is.function(player.config.quality.onChange)) { + player.config.quality.onChange(input); + } else { + // Get sources + const sources = html5.getSources.call(player); // Get first match for requested size + + const source = sources.find(s => Number(s.getAttribute('data-res')) === input); // No matching source found + + if (!source) { + return; + } // Get current state + + + const { + currentTime, + paused, + preload, + readyState, + playbackRate + } = player.media; // Set new source + + player.media.src = source.getAttribute('src'); // Prevent loading if preload="none" and the current source isn't loaded (#1044) + + if (preload !== 'none' || readyState) { + // Restore time + player.once('loadedmetadata', () => { + player.speed = playbackRate; + player.currentTime = currentTime; // Resume playing + + if (!paused) { + silencePromise(player.play()); + } + }); // Load new source + + player.media.load(); + } + } // Trigger change event + + + triggerEvent.call(player, player.media, 'qualitychange', false, { + quality: input + }); + } + + }); + }, + + // Cancel current network requests + // See https://github.com/sampotts/plyr/issues/174 + cancelRequests() { + if (!this.isHTML5) { + return; + } // Remove child sources + + + removeElement(html5.getSources.call(this)); // Set blank video src attribute + // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error + // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection + + this.media.setAttribute('src', this.config.blankVideo); // Load the new empty source + // This will cancel existing requests + // See https://github.com/sampotts/plyr/issues/174 + + this.media.load(); // Debugging + + this.debug.log('Cancelled network requests'); + } + + }; + + // ========================================================================== + + function generateId(prefix) { + return `${prefix}-${Math.floor(Math.random() * 10000)}`; + } // Format string + + function format(input, ...args) { + if (is.empty(input)) { + return input; + } + + return input.toString().replace(/{(\d+)}/g, (match, i) => args[i].toString()); + } // Get percentage + + function getPercentage(current, max) { + if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) { + return 0; + } + + return (current / max * 100).toFixed(2); + } // Replace all occurances of a string in a string + + const replaceAll = (input = '', find = '', replace = '') => input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\]/\\])/g, '\\$1'), 'g'), replace.toString()); // Convert to title case + + const toTitleCase = (input = '') => input.toString().replace(/\w\S*/g, text => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()); // Convert string to pascalCase + + function toPascalCase(input = '') { + let string = input.toString(); // Convert kebab case + + string = replaceAll(string, '-', ' '); // Convert snake case + + string = replaceAll(string, '_', ' '); // Convert to title case + + string = toTitleCase(string); // Convert to pascal case + + return replaceAll(string, ' ', ''); + } // Convert string to pascalCase + + function toCamelCase(input = '') { + let string = input.toString(); // Convert to pascal case + + string = toPascalCase(string); // Convert first character to lowercase + + return string.charAt(0).toLowerCase() + string.slice(1); + } // Remove HTML from a string + + function stripHTML(source) { + const fragment = document.createDocumentFragment(); + const element = document.createElement('div'); + fragment.appendChild(element); + element.innerHTML = source; + return fragment.firstChild.innerText; + } // Like outerHTML, but also works for DocumentFragment + + function getHTML(element) { + const wrapper = document.createElement('div'); + wrapper.appendChild(element); + return wrapper.innerHTML; + } + + // ========================================================================== + + const resources = { + pip: 'PIP', + airplay: 'AirPlay', + html5: 'HTML5', + vimeo: 'Vimeo', + youtube: 'YouTube' + }; + const i18n = { + get(key = '', config = {}) { + if (is.empty(key) || is.empty(config)) { + return ''; + } + + let string = getDeep(config.i18n, key); + + if (is.empty(string)) { + if (Object.keys(resources).includes(key)) { + return resources[key]; + } + + return ''; + } + + const replace = { + '{seektime}': config.seekTime, + '{title}': config.title + }; + Object.entries(replace).forEach(([k, v]) => { + string = replaceAll(string, k, v); + }); + return string; + } + + }; + + class Storage { + constructor(player) { + _defineProperty$1(this, "get", key => { + if (!Storage.supported || !this.enabled) { + return null; + } + + const store = window.localStorage.getItem(this.key); + + if (is.empty(store)) { + return null; + } + + const json = JSON.parse(store); + return is.string(key) && key.length ? json[key] : json; + }); + + _defineProperty$1(this, "set", object => { + // Bail if we don't have localStorage support or it's disabled + if (!Storage.supported || !this.enabled) { + return; + } // Can only store objectst + + + if (!is.object(object)) { + return; + } // Get current storage + + + let storage = this.get(); // Default to empty object + + if (is.empty(storage)) { + storage = {}; + } // Update the working copy of the values + + + extend(storage, object); // Update storage + + try { + window.localStorage.setItem(this.key, JSON.stringify(storage)); + } catch (_) {// Do nothing + } + }); + + this.enabled = player.config.storage.enabled; + this.key = player.config.storage.key; + } // Check for actual support (see if we can use it) + + + static get supported() { + try { + if (!('localStorage' in window)) { + return false; + } + + const test = '___test'; // Try to use it (it might be disabled, e.g. user is in private mode) + // see: https://github.com/sampotts/plyr/issues/131 + + window.localStorage.setItem(test, test); + window.localStorage.removeItem(test); + return true; + } catch (_) { + return false; + } + } + + } + + // ========================================================================== + // Fetch wrapper + // Using XHR to avoid issues with older browsers + // ========================================================================== + function fetch(url, responseType = 'text') { + return new Promise((resolve, reject) => { + try { + const request = new XMLHttpRequest(); // Check for CORS support + + if (!('withCredentials' in request)) { + return; + } + + request.addEventListener('load', () => { + if (responseType === 'text') { + try { + resolve(JSON.parse(request.responseText)); + } catch (_) { + resolve(request.responseText); + } + } else { + resolve(request.response); + } + }); + request.addEventListener('error', () => { + throw new Error(request.status); + }); + request.open('GET', url, true); // Set the required response type + + request.responseType = responseType; + request.send(); + } catch (error) { + reject(error); + } + }); + } + + // ========================================================================== + + function loadSprite(url, id) { + if (!is.string(url)) { + return; + } + + const prefix = 'cache'; + const hasId = is.string(id); + let isCached = false; + + const exists = () => document.getElementById(id) !== null; + + const update = (container, data) => { + // eslint-disable-next-line no-param-reassign + container.innerHTML = data; // Check again incase of race condition + + if (hasId && exists()) { + return; + } // Inject the SVG to the body + + + document.body.insertAdjacentElement('afterbegin', container); + }; // Only load once if ID set + + + if (!hasId || !exists()) { + const useStorage = Storage.supported; // Create container + + const container = document.createElement('div'); + container.setAttribute('hidden', ''); + + if (hasId) { + container.setAttribute('id', id); + } // Check in cache + + + if (useStorage) { + const cached = window.localStorage.getItem(`${prefix}-${id}`); + isCached = cached !== null; + + if (isCached) { + const data = JSON.parse(cached); + update(container, data.content); + } + } // Get the sprite + + + fetch(url).then(result => { + if (is.empty(result)) { + return; + } + + if (useStorage) { + try { + window.localStorage.setItem(`${prefix}-${id}`, JSON.stringify({ + content: result + })); + } catch (_) {// Do nothing + } + } + + update(container, result); + }).catch(() => {}); + } + } + + // ========================================================================== + + const getHours = value => Math.trunc(value / 60 / 60 % 60, 10); + const getMinutes = value => Math.trunc(value / 60 % 60, 10); + const getSeconds = value => Math.trunc(value % 60, 10); // Format time to UI friendly string + + function formatTime(time = 0, displayHours = false, inverted = false) { + // Bail if the value isn't a number + if (!is.number(time)) { + return formatTime(undefined, displayHours, inverted); + } // Format time component to add leading zero + + + const format = value => `0${value}`.slice(-2); // Breakdown to hours, mins, secs + + + let hours = getHours(time); + const mins = getMinutes(time); + const secs = getSeconds(time); // Do we need to display hours? + + if (displayHours || hours > 0) { + hours = `${hours}:`; + } else { + hours = ''; + } // Render + + + return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`; + } + + // ========================================================================== + + const controls = { + // Get icon URL + getIconUrl() { + const url = new URL(this.config.iconUrl, window.location); + const host = window.location.host ? window.location.host : window.top.location.host; + const cors = url.host !== host || browser.isIE && !window.svg4everybody; + return { + url: this.config.iconUrl, + cors + }; + }, + + // Find the UI controls + findElements() { + try { + this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper); // Buttons + + this.elements.buttons = { + play: getElements.call(this, this.config.selectors.buttons.play), + pause: getElement.call(this, this.config.selectors.buttons.pause), + restart: getElement.call(this, this.config.selectors.buttons.restart), + rewind: getElement.call(this, this.config.selectors.buttons.rewind), + fastForward: getElement.call(this, this.config.selectors.buttons.fastForward), + mute: getElement.call(this, this.config.selectors.buttons.mute), + pip: getElement.call(this, this.config.selectors.buttons.pip), + airplay: getElement.call(this, this.config.selectors.buttons.airplay), + settings: getElement.call(this, this.config.selectors.buttons.settings), + captions: getElement.call(this, this.config.selectors.buttons.captions), + fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen) + }; // Progress + + this.elements.progress = getElement.call(this, this.config.selectors.progress); // Inputs + + this.elements.inputs = { + seek: getElement.call(this, this.config.selectors.inputs.seek), + volume: getElement.call(this, this.config.selectors.inputs.volume) + }; // Display + + this.elements.display = { + buffer: getElement.call(this, this.config.selectors.display.buffer), + currentTime: getElement.call(this, this.config.selectors.display.currentTime), + duration: getElement.call(this, this.config.selectors.display.duration) + }; // Seek tooltip + + if (is.element(this.elements.progress)) { + this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`); + } + + return true; + } catch (error) { + // Log it + this.debug.warn('It looks like there is a problem with your custom controls HTML', error); // Restore native video controls + + this.toggleNativeControls(true); + return false; + } + }, + + // Create <svg> icon + createIcon(type, attributes) { + const namespace = 'http://www.w3.org/2000/svg'; + const iconUrl = controls.getIconUrl.call(this); + const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`; // Create <svg> + + const icon = document.createElementNS(namespace, 'svg'); + setAttributes(icon, extend(attributes, { + 'aria-hidden': 'true', + focusable: 'false' + })); // Create the <use> to reference sprite + + const use = document.createElementNS(namespace, 'use'); + const path = `${iconPath}-${type}`; // Set `href` attributes + // https://github.com/sampotts/plyr/issues/460 + // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href + + if ('href' in use) { + use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path); + } // Always set the older attribute even though it's "deprecated" (it'll be around for ages) + + + use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path); // Add <use> to <svg> + + icon.appendChild(use); + return icon; + }, + + // Create hidden text label + createLabel(key, attr = {}) { + const text = i18n.get(key, this.config); + const attributes = { ...attr, + class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ') + }; + return createElement('span', attributes, text); + }, + + // Create a badge + createBadge(text) { + if (is.empty(text)) { + return null; + } + + const badge = createElement('span', { + class: this.config.classNames.menu.value + }); + badge.appendChild(createElement('span', { + class: this.config.classNames.menu.badge + }, text)); + return badge; + }, + + // Create a <button> + createButton(buttonType, attr) { + const attributes = extend({}, attr); + let type = toCamelCase(buttonType); + const props = { + element: 'button', + toggle: false, + label: null, + icon: null, + labelPressed: null, + iconPressed: null + }; + ['element', 'icon', 'label'].forEach(key => { + if (Object.keys(attributes).includes(key)) { + props[key] = attributes[key]; + delete attributes[key]; + } + }); // Default to 'button' type to prevent form submission + + if (props.element === 'button' && !Object.keys(attributes).includes('type')) { + attributes.type = 'button'; + } // Set class name + + + if (Object.keys(attributes).includes('class')) { + if (!attributes.class.split(' ').some(c => c === this.config.classNames.control)) { + extend(attributes, { + class: `${attributes.class} ${this.config.classNames.control}` + }); + } + } else { + attributes.class = this.config.classNames.control; + } // Large play button + + + switch (buttonType) { + case 'play': + props.toggle = true; + props.label = 'play'; + props.labelPressed = 'pause'; + props.icon = 'play'; + props.iconPressed = 'pause'; + break; + + case 'mute': + props.toggle = true; + props.label = 'mute'; + props.labelPressed = 'unmute'; + props.icon = 'volume'; + props.iconPressed = 'muted'; + break; + + case 'captions': + props.toggle = true; + props.label = 'enableCaptions'; + props.labelPressed = 'disableCaptions'; + props.icon = 'captions-off'; + props.iconPressed = 'captions-on'; + break; + + case 'fullscreen': + props.toggle = true; + props.label = 'enterFullscreen'; + props.labelPressed = 'exitFullscreen'; + props.icon = 'enter-fullscreen'; + props.iconPressed = 'exit-fullscreen'; + break; + + case 'play-large': + attributes.class += ` ${this.config.classNames.control}--overlaid`; + type = 'play'; + props.label = 'play'; + props.icon = 'play'; + break; + + default: + if (is.empty(props.label)) { + props.label = type; + } + + if (is.empty(props.icon)) { + props.icon = buttonType; + } + + } + + const button = createElement(props.element); // Setup toggle icon and labels + + if (props.toggle) { + // Icon + button.appendChild(controls.createIcon.call(this, props.iconPressed, { + class: 'icon--pressed' + })); + button.appendChild(controls.createIcon.call(this, props.icon, { + class: 'icon--not-pressed' + })); // Label/Tooltip + + button.appendChild(controls.createLabel.call(this, props.labelPressed, { + class: 'label--pressed' + })); + button.appendChild(controls.createLabel.call(this, props.label, { + class: 'label--not-pressed' + })); + } else { + button.appendChild(controls.createIcon.call(this, props.icon)); + button.appendChild(controls.createLabel.call(this, props.label)); + } // Merge and set attributes + + + extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes)); + setAttributes(button, attributes); // We have multiple play buttons + + if (type === 'play') { + if (!is.array(this.elements.buttons[type])) { + this.elements.buttons[type] = []; + } + + this.elements.buttons[type].push(button); + } else { + this.elements.buttons[type] = button; + } + + return button; + }, + + // Create an <input type='range'> + createRange(type, attributes) { + // Seek input + const input = createElement('input', extend(getAttributesFromSelector(this.config.selectors.inputs[type]), { + type: 'range', + min: 0, + max: 100, + step: 0.01, + value: 0, + autocomplete: 'off', + // A11y fixes for https://github.com/sampotts/plyr/issues/905 + role: 'slider', + 'aria-label': i18n.get(type, this.config), + 'aria-valuemin': 0, + 'aria-valuemax': 100, + 'aria-valuenow': 0 + }, attributes)); + this.elements.inputs[type] = input; // Set the fill for webkit now + + controls.updateRangeFill.call(this, input); // Improve support on touch devices + + RangeTouch.setup(input); + return input; + }, + + // Create a <progress> + createProgress(type, attributes) { + const progress = createElement('progress', extend(getAttributesFromSelector(this.config.selectors.display[type]), { + min: 0, + max: 100, + value: 0, + role: 'progressbar', + 'aria-hidden': true + }, attributes)); // Create the label inside + + if (type !== 'volume') { + progress.appendChild(createElement('span', null, '0')); + const suffixKey = { + played: 'played', + buffer: 'buffered' + }[type]; + const suffix = suffixKey ? i18n.get(suffixKey, this.config) : ''; + progress.innerText = `% ${suffix.toLowerCase()}`; + } + + this.elements.display[type] = progress; + return progress; + }, + + // Create time display + createTime(type, attrs) { + const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs); + const container = createElement('div', extend(attributes, { + class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(), + 'aria-label': i18n.get(type, this.config) + }), '00:00'); // Reference for updates + + this.elements.display[type] = container; + return container; + }, + + // Bind keyboard shortcuts for a menu item + // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus + // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143 + bindMenuItemShortcuts(menuItem, type) { + // Navigate through menus via arrow keys and space + on.call(this, menuItem, 'keydown keyup', event => { + // We only care about space and ⬆️ ⬇️️ ➡️ + if (![32, 38, 39, 40].includes(event.which)) { + return; + } // Prevent play / seek + + + event.preventDefault(); + event.stopPropagation(); // We're just here to prevent the keydown bubbling + + if (event.type === 'keydown') { + return; + } + + const isRadioButton = matches(menuItem, '[role="menuitemradio"]'); // Show the respective menu + + if (!isRadioButton && [32, 39].includes(event.which)) { + controls.showMenuPanel.call(this, type, true); + } else { + let target; + + if (event.which !== 32) { + if (event.which === 40 || isRadioButton && event.which === 39) { + target = menuItem.nextElementSibling; + + if (!is.element(target)) { + target = menuItem.parentNode.firstElementChild; + } + } else { + target = menuItem.previousElementSibling; + + if (!is.element(target)) { + target = menuItem.parentNode.lastElementChild; + } + } + + setFocus.call(this, target, true); + } + } + }, false); // Enter will fire a `click` event but we still need to manage focus + // So we bind to keyup which fires after and set focus here + + on.call(this, menuItem, 'keyup', event => { + if (event.which !== 13) { + return; + } + + controls.focusFirstMenuItem.call(this, null, true); + }); + }, + + // Create a settings menu item + createMenuItem({ + value, + list, + type, + title, + badge = null, + checked = false + }) { + const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]); + const menuItem = createElement('button', extend(attributes, { + type: 'button', + role: 'menuitemradio', + class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(), + 'aria-checked': checked, + value + })); + const flex = createElement('span'); // We have to set as HTML incase of special characters + + flex.innerHTML = title; + + if (is.element(badge)) { + flex.appendChild(badge); + } + + menuItem.appendChild(flex); // Replicate radio button behaviour + + Object.defineProperty(menuItem, 'checked', { + enumerable: true, + + get() { + return menuItem.getAttribute('aria-checked') === 'true'; + }, + + set(check) { + // Ensure exclusivity + if (check) { + Array.from(menuItem.parentNode.children).filter(node => matches(node, '[role="menuitemradio"]')).forEach(node => node.setAttribute('aria-checked', 'false')); + } + + menuItem.setAttribute('aria-checked', check ? 'true' : 'false'); + } + + }); + this.listeners.bind(menuItem, 'click keyup', event => { + if (is.keyboardEvent(event) && event.which !== 32) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + menuItem.checked = true; + + switch (type) { + case 'language': + this.currentTrack = Number(value); + break; + + case 'quality': + this.quality = value; + break; + + case 'speed': + this.speed = parseFloat(value); + break; + } + + controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event)); + }, type, false); + controls.bindMenuItemShortcuts.call(this, menuItem, type); + list.appendChild(menuItem); + }, + + // Format a time for display + formatTime(time = 0, inverted = false) { + // Bail if the value isn't a number + if (!is.number(time)) { + return time; + } // Always display hours if duration is over an hour + + + const forceHours = getHours(this.duration) > 0; + return formatTime(time, forceHours, inverted); + }, + + // Update the displayed time + updateTimeDisplay(target = null, time = 0, inverted = false) { + // Bail if there's no element to display or the value isn't a number + if (!is.element(target) || !is.number(time)) { + return; + } // eslint-disable-next-line no-param-reassign + + + target.innerText = controls.formatTime(time, inverted); + }, + + // Update volume UI and storage + updateVolume() { + if (!this.supported.ui) { + return; + } // Update range + + + if (is.element(this.elements.inputs.volume)) { + controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume); + } // Update mute state + + + if (is.element(this.elements.buttons.mute)) { + this.elements.buttons.mute.pressed = this.muted || this.volume === 0; + } + }, + + // Update seek value and lower fill + setRange(target, value = 0) { + if (!is.element(target)) { + return; + } // eslint-disable-next-line + + + target.value = value; // Webkit range fill + + controls.updateRangeFill.call(this, target); + }, + + // Update <progress> elements + updateProgress(event) { + if (!this.supported.ui || !is.event(event)) { + return; + } + + let value = 0; + + const setProgress = (target, input) => { + const val = is.number(input) ? input : 0; + const progress = is.element(target) ? target : this.elements.display.buffer; // Update value and label + + if (is.element(progress)) { + progress.value = val; // Update text label inside + + const label = progress.getElementsByTagName('span')[0]; + + if (is.element(label)) { + label.childNodes[0].nodeValue = val; + } + } + }; + + if (event) { + switch (event.type) { + // Video playing + case 'timeupdate': + case 'seeking': + case 'seeked': + value = getPercentage(this.currentTime, this.duration); // Set seek range value only if it's a 'natural' time event + + if (event.type === 'timeupdate') { + controls.setRange.call(this, this.elements.inputs.seek, value); + } + + break; + // Check buffer status + + case 'playing': + case 'progress': + setProgress(this.elements.display.buffer, this.buffered * 100); + break; + } + } + }, + + // Webkit polyfill for lower fill range + updateRangeFill(target) { + // Get range from event if event passed + const range = is.event(target) ? target.target : target; // Needs to be a valid <input type='range'> + + if (!is.element(range) || range.getAttribute('type') !== 'range') { + return; + } // Set aria values for https://github.com/sampotts/plyr/issues/905 + + + if (matches(range, this.config.selectors.inputs.seek)) { + range.setAttribute('aria-valuenow', this.currentTime); + const currentTime = controls.formatTime(this.currentTime); + const duration = controls.formatTime(this.duration); + const format = i18n.get('seekLabel', this.config); + range.setAttribute('aria-valuetext', format.replace('{currentTime}', currentTime).replace('{duration}', duration)); + } else if (matches(range, this.config.selectors.inputs.volume)) { + const percent = range.value * 100; + range.setAttribute('aria-valuenow', percent); + range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`); + } else { + range.setAttribute('aria-valuenow', range.value); + } // WebKit only + + + if (!browser.isWebkit) { + return; + } // Set CSS custom property + + + range.style.setProperty('--value', `${range.value / range.max * 100}%`); + }, + + // Update hover tooltip for seeking + updateSeekTooltip(event) { + // Bail if setting not true + if (!this.config.tooltips.seek || !is.element(this.elements.inputs.seek) || !is.element(this.elements.display.seekTooltip) || this.duration === 0) { + return; + } + + const visible = `${this.config.classNames.tooltip}--visible`; + + const toggle = show => toggleClass(this.elements.display.seekTooltip, visible, show); // Hide on touch + + + if (this.touch) { + toggle(false); + return; + } // Determine percentage, if already visible + + + let percent = 0; + const clientRect = this.elements.progress.getBoundingClientRect(); + + if (is.event(event)) { + percent = 100 / clientRect.width * (event.pageX - clientRect.left); + } else if (hasClass(this.elements.display.seekTooltip, visible)) { + percent = parseFloat(this.elements.display.seekTooltip.style.left, 10); + } else { + return; + } // Set bounds + + + if (percent < 0) { + percent = 0; + } else if (percent > 100) { + percent = 100; + } // Display the time a click would seek to + + + controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent); // Set position + + this.elements.display.seekTooltip.style.left = `${percent}%`; // Show/hide the tooltip + // If the event is a moues in/out and percentage is inside bounds + + if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) { + toggle(event.type === 'mouseenter'); + } + }, + + // Handle time change event + timeUpdate(event) { + // Only invert if only one time element is displayed and used for both duration and currentTime + const invert = !is.element(this.elements.display.duration) && this.config.invertTime; // Duration + + controls.updateTimeDisplay.call(this, this.elements.display.currentTime, invert ? this.duration - this.currentTime : this.currentTime, invert); // Ignore updates while seeking + + if (event && event.type === 'timeupdate' && this.media.seeking) { + return; + } // Playing progress + + + controls.updateProgress.call(this, event); + }, + + // Show the duration on metadataloaded or durationchange events + durationUpdate() { + // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false + if (!this.supported.ui || !this.config.invertTime && this.currentTime) { + return; + } // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar. + // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415 + // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062 + // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338 + + + if (this.duration >= 2 ** 32) { + toggleHidden(this.elements.display.currentTime, true); + toggleHidden(this.elements.progress, true); + return; + } // Update ARIA values + + + if (is.element(this.elements.inputs.seek)) { + this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration); + } // If there's a spot to display duration + + + const hasDuration = is.element(this.elements.display.duration); // If there's only one time display, display duration there + + if (!hasDuration && this.config.displayDuration && this.paused) { + controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration); + } // If there's a duration element, update content + + + if (hasDuration) { + controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration); + } // Update the tooltip (if visible) + + + controls.updateSeekTooltip.call(this); + }, + + // Hide/show a tab + toggleMenuButton(setting, toggle) { + toggleHidden(this.elements.settings.buttons[setting], !toggle); + }, + + // Update the selected setting + updateSetting(setting, container, input) { + const pane = this.elements.settings.panels[setting]; + let value = null; + let list = container; + + if (setting === 'captions') { + value = this.currentTrack; + } else { + value = !is.empty(input) ? input : this[setting]; // Get default + + if (is.empty(value)) { + value = this.config[setting].default; + } // Unsupported value + + + if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) { + this.debug.warn(`Unsupported value of '${value}' for ${setting}`); + return; + } // Disabled value + + + if (!this.config[setting].options.includes(value)) { + this.debug.warn(`Disabled value of '${value}' for ${setting}`); + return; + } + } // Get the list if we need to + + + if (!is.element(list)) { + list = pane && pane.querySelector('[role="menu"]'); + } // If there's no list it means it's not been rendered... + + + if (!is.element(list)) { + return; + } // Update the label + + + const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`); + label.innerHTML = controls.getLabel.call(this, setting, value); // Find the radio option and check it + + const target = list && list.querySelector(`[value="${value}"]`); + + if (is.element(target)) { + target.checked = true; + } + }, + + // Translate a value into a nice label + getLabel(setting, value) { + switch (setting) { + case 'speed': + return value === 1 ? i18n.get('normal', this.config) : `${value}×`; + + case 'quality': + if (is.number(value)) { + const label = i18n.get(`qualityLabel.${value}`, this.config); + + if (!label.length) { + return `${value}p`; + } + + return label; + } + + return toTitleCase(value); + + case 'captions': + return captions.getLabel.call(this); + + default: + return null; + } + }, + + // Set the quality menu + setQualityMenu(options) { + // Menu required + if (!is.element(this.elements.settings.panels.quality)) { + return; + } + + const type = 'quality'; + const list = this.elements.settings.panels.quality.querySelector('[role="menu"]'); // Set options if passed and filter based on uniqueness and config + + if (is.array(options)) { + this.options.quality = dedupe(options).filter(quality => this.config.quality.options.includes(quality)); + } // Toggle the pane and tab + + + const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1; + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If we're hiding, nothing more to do + + if (!toggle) { + return; + } // Get the badge HTML for HD, 4K etc + + + const getBadge = quality => { + const label = i18n.get(`qualityBadge.${quality}`, this.config); + + if (!label.length) { + return null; + } + + return controls.createBadge.call(this, label); + }; // Sort options by the config and then render options + + + this.options.quality.sort((a, b) => { + const sorting = this.config.quality.options; + return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1; + }).forEach(quality => { + controls.createMenuItem.call(this, { + value: quality, + list, + type, + title: controls.getLabel.call(this, 'quality', quality), + badge: getBadge(quality) + }); + }); + controls.updateSetting.call(this, type, list); + }, + + // Set the looping options + + /* setLoopMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.loop)) { + return; + } + const options = ['start', 'end', 'all', 'reset']; + const list = this.elements.settings.panels.loop.querySelector('[role="menu"]'); + // Show the pane and tab + toggleHidden(this.elements.settings.buttons.loop, false); + toggleHidden(this.elements.settings.panels.loop, false); + // Toggle the pane and tab + const toggle = !is.empty(this.loop.options); + controls.toggleMenuButton.call(this, 'loop', toggle); + // Empty the menu + emptyElement(list); + options.forEach(option => { + const item = createElement('li'); + const button = createElement( + 'button', + extend(getAttributesFromSelector(this.config.selectors.buttons.loop), { + type: 'button', + class: this.config.classNames.control, + 'data-plyr-loop-action': option, + }), + i18n.get(option, this.config) + ); + if (['start', 'end'].includes(option)) { + const badge = controls.createBadge.call(this, '00:00'); + button.appendChild(badge); + } + item.appendChild(button); + list.appendChild(item); + }); + }, */ + // Get current selected caption language + // TODO: rework this to user the getter in the API? + // Set a list of available captions languages + setCaptionsMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.captions)) { + return; + } // TODO: Captions or language? Currently it's mixed + + + const type = 'captions'; + const list = this.elements.settings.panels.captions.querySelector('[role="menu"]'); + const tracks = captions.getTracks.call(this); + const toggle = Boolean(tracks.length); // Toggle the pane and tab + + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If there's no captions, bail + + if (!toggle) { + return; + } // Generate options data + + + const options = tracks.map((track, value) => ({ + value, + checked: this.captions.toggled && this.currentTrack === value, + title: captions.getLabel.call(this, track), + badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()), + list, + type: 'language' + })); // Add the "Disabled" option to turn off captions + + options.unshift({ + value: -1, + checked: !this.captions.toggled, + title: i18n.get('disabled', this.config), + list, + type: 'language' + }); // Generate options + + options.forEach(controls.createMenuItem.bind(this)); + controls.updateSetting.call(this, type, list); + }, + + // Set a list of available captions languages + setSpeedMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.speed)) { + return; + } + + const type = 'speed'; + const list = this.elements.settings.panels.speed.querySelector('[role="menu"]'); // Filter out invalid speeds + + this.options.speed = this.options.speed.filter(o => o >= this.minimumSpeed && o <= this.maximumSpeed); // Toggle the pane and tab + + const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1; + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If we're hiding, nothing more to do + + if (!toggle) { + return; + } // Create items + + + this.options.speed.forEach(speed => { + controls.createMenuItem.call(this, { + value: speed, + list, + type, + title: controls.getLabel.call(this, 'speed', speed) + }); + }); + controls.updateSetting.call(this, type, list); + }, + + // Check if we need to hide/show the settings menu + checkMenu() { + const { + buttons + } = this.elements.settings; + const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden); + toggleHidden(this.elements.settings.menu, !visible); + }, + + // Focus the first menu item in a given (or visible) menu + focusFirstMenuItem(pane, tabFocus = false) { + if (this.elements.settings.popup.hidden) { + return; + } + + let target = pane; + + if (!is.element(target)) { + target = Object.values(this.elements.settings.panels).find(p => !p.hidden); + } + + const firstItem = target.querySelector('[role^="menuitem"]'); + setFocus.call(this, firstItem, tabFocus); + }, + + // Show/hide menu + toggleMenu(input) { + const { + popup + } = this.elements.settings; + const button = this.elements.buttons.settings; // Menu and button are required + + if (!is.element(popup) || !is.element(button)) { + return; + } // True toggle by default + + + const { + hidden + } = popup; + let show = hidden; + + if (is.boolean(input)) { + show = input; + } else if (is.keyboardEvent(input) && input.which === 27) { + show = false; + } else if (is.event(input)) { + // If Plyr is in a shadowDOM, the event target is set to the component, instead of the + // Element in the shadowDOM. The path, if available, is complete. + const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target; + const isMenuItem = popup.contains(target); // If the click was inside the menu or if the click + // wasn't the button or menu item and we're trying to + // show the menu (a doc click shouldn't show the menu) + + if (isMenuItem || !isMenuItem && input.target !== button && show) { + return; + } + } // Set button attributes + + + button.setAttribute('aria-expanded', show); // Show the actual popup + + toggleHidden(popup, !show); // Add class hook + + toggleClass(this.elements.container, this.config.classNames.menu.open, show); // Focus the first item if key interaction + + if (show && is.keyboardEvent(input)) { + controls.focusFirstMenuItem.call(this, null, true); + } else if (!show && !hidden) { + // If closing, re-focus the button + setFocus.call(this, button, is.keyboardEvent(input)); + } + }, + + // Get the natural size of a menu panel + getMenuSize(tab) { + const clone = tab.cloneNode(true); + clone.style.position = 'absolute'; + clone.style.opacity = 0; + clone.removeAttribute('hidden'); // Append to parent so we get the "real" size + + tab.parentNode.appendChild(clone); // Get the sizes before we remove + + const width = clone.scrollWidth; + const height = clone.scrollHeight; // Remove from the DOM + + removeElement(clone); + return { + width, + height + }; + }, + + // Show a panel in the menu + showMenuPanel(type = '', tabFocus = false) { + const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`); // Nothing to show, bail + + if (!is.element(target)) { + return; + } // Hide all other panels + + + const container = target.parentNode; + const current = Array.from(container.children).find(node => !node.hidden); // If we can do fancy animations, we'll animate the height/width + + if (support.transitions && !support.reducedMotion) { + // Set the current width as a base + container.style.width = `${current.scrollWidth}px`; + container.style.height = `${current.scrollHeight}px`; // Get potential sizes + + const size = controls.getMenuSize.call(this, target); // Restore auto height/width + + const restore = event => { + // We're only bothered about height and width on the container + if (event.target !== container || !['width', 'height'].includes(event.propertyName)) { + return; + } // Revert back to auto + + + container.style.width = ''; + container.style.height = ''; // Only listen once + + off.call(this, container, transitionEndEvent, restore); + }; // Listen for the transition finishing and restore auto height/width + + + on.call(this, container, transitionEndEvent, restore); // Set dimensions to target + + container.style.width = `${size.width}px`; + container.style.height = `${size.height}px`; + } // Set attributes on current tab + + + toggleHidden(current, true); // Set attributes on target + + toggleHidden(target, false); // Focus the first item + + controls.focusFirstMenuItem.call(this, target, tabFocus); + }, + + // Set the download URL + setDownloadUrl() { + const button = this.elements.buttons.download; // Bail if no button + + if (!is.element(button)) { + return; + } // Set attribute + + + button.setAttribute('href', this.download); + }, + + // Build the default HTML + create(data) { + const { + bindMenuItemShortcuts, + createButton, + createProgress, + createRange, + createTime, + setQualityMenu, + setSpeedMenu, + showMenuPanel + } = controls; + this.elements.controls = null; // Larger overlaid play button + + if (is.array(this.config.controls) && this.config.controls.includes('play-large')) { + this.elements.container.appendChild(createButton.call(this, 'play-large')); + } // Create the container + + + const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper)); + this.elements.controls = container; // Default item attributes + + const defaultAttributes = { + class: 'plyr__controls__item' + }; // Loop through controls in order + + dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach(control => { + // Restart button + if (control === 'restart') { + container.appendChild(createButton.call(this, 'restart', defaultAttributes)); + } // Rewind button + + + if (control === 'rewind') { + container.appendChild(createButton.call(this, 'rewind', defaultAttributes)); + } // Play/Pause button + + + if (control === 'play') { + container.appendChild(createButton.call(this, 'play', defaultAttributes)); + } // Fast forward button + + + if (control === 'fast-forward') { + container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes)); + } // Progress + + + if (control === 'progress') { + const progressContainer = createElement('div', { + class: `${defaultAttributes.class} plyr__progress__container` + }); + const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress)); // Seek range slider + + progress.appendChild(createRange.call(this, 'seek', { + id: `plyr-seek-${data.id}` + })); // Buffer progress + + progress.appendChild(createProgress.call(this, 'buffer')); // TODO: Add loop display indicator + // Seek tooltip + + if (this.config.tooltips.seek) { + const tooltip = createElement('span', { + class: this.config.classNames.tooltip + }, '00:00'); + progress.appendChild(tooltip); + this.elements.display.seekTooltip = tooltip; + } + + this.elements.progress = progress; + progressContainer.appendChild(this.elements.progress); + container.appendChild(progressContainer); + } // Media current time display + + + if (control === 'current-time') { + container.appendChild(createTime.call(this, 'currentTime', defaultAttributes)); + } // Media duration display + + + if (control === 'duration') { + container.appendChild(createTime.call(this, 'duration', defaultAttributes)); + } // Volume controls + + + if (control === 'mute' || control === 'volume') { + let { + volume + } = this.elements; // Create the volume container if needed + + if (!is.element(volume) || !container.contains(volume)) { + volume = createElement('div', extend({}, defaultAttributes, { + class: `${defaultAttributes.class} plyr__volume`.trim() + })); + this.elements.volume = volume; + container.appendChild(volume); + } // Toggle mute button + + + if (control === 'mute') { + volume.appendChild(createButton.call(this, 'mute')); + } // Volume range control + // Ignored on iOS as it's handled globally + // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html + + + if (control === 'volume' && !browser.isIos) { + // Set the attributes + const attributes = { + max: 1, + step: 0.05, + value: this.config.volume + }; // Create the volume range slider + + volume.appendChild(createRange.call(this, 'volume', extend(attributes, { + id: `plyr-volume-${data.id}` + }))); + } + } // Toggle captions button + + + if (control === 'captions') { + container.appendChild(createButton.call(this, 'captions', defaultAttributes)); + } // Settings button / menu + + + if (control === 'settings' && !is.empty(this.config.settings)) { + const wrapper = createElement('div', extend({}, defaultAttributes, { + class: `${defaultAttributes.class} plyr__menu`.trim(), + hidden: '' + })); + wrapper.appendChild(createButton.call(this, 'settings', { + 'aria-haspopup': true, + 'aria-controls': `plyr-settings-${data.id}`, + 'aria-expanded': false + })); + const popup = createElement('div', { + class: 'plyr__menu__container', + id: `plyr-settings-${data.id}`, + hidden: '' + }); + const inner = createElement('div'); + const home = createElement('div', { + id: `plyr-settings-${data.id}-home` + }); // Create the menu + + const menu = createElement('div', { + role: 'menu' + }); + home.appendChild(menu); + inner.appendChild(home); + this.elements.settings.panels.home = home; // Build the menu items + + this.config.settings.forEach(type => { + // TODO: bundle this with the createMenuItem helper and bindings + const menuItem = createElement('button', extend(getAttributesFromSelector(this.config.selectors.buttons.settings), { + type: 'button', + class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`, + role: 'menuitem', + 'aria-haspopup': true, + hidden: '' + })); // Bind menu shortcuts for keyboard users + + bindMenuItemShortcuts.call(this, menuItem, type); // Show menu on click + + on.call(this, menuItem, 'click', () => { + showMenuPanel.call(this, type, false); + }); + const flex = createElement('span', null, i18n.get(type, this.config)); + const value = createElement('span', { + class: this.config.classNames.menu.value + }); // Speed contains HTML entities + + value.innerHTML = data[type]; + flex.appendChild(value); + menuItem.appendChild(flex); + menu.appendChild(menuItem); // Build the panes + + const pane = createElement('div', { + id: `plyr-settings-${data.id}-${type}`, + hidden: '' + }); // Back button + + const backButton = createElement('button', { + type: 'button', + class: `${this.config.classNames.control} ${this.config.classNames.control}--back` + }); // Visible label + + backButton.appendChild(createElement('span', { + 'aria-hidden': true + }, i18n.get(type, this.config))); // Screen reader label + + backButton.appendChild(createElement('span', { + class: this.config.classNames.hidden + }, i18n.get('menuBack', this.config))); // Go back via keyboard + + on.call(this, pane, 'keydown', event => { + // We only care about <- + if (event.which !== 37) { + return; + } // Prevent seek + + + event.preventDefault(); + event.stopPropagation(); // Show the respective menu + + showMenuPanel.call(this, 'home', true); + }, false); // Go back via button click + + on.call(this, backButton, 'click', () => { + showMenuPanel.call(this, 'home', false); + }); // Add to pane + + pane.appendChild(backButton); // Menu + + pane.appendChild(createElement('div', { + role: 'menu' + })); + inner.appendChild(pane); + this.elements.settings.buttons[type] = menuItem; + this.elements.settings.panels[type] = pane; + }); + popup.appendChild(inner); + wrapper.appendChild(popup); + container.appendChild(wrapper); + this.elements.settings.popup = popup; + this.elements.settings.menu = wrapper; + } // Picture in picture button + + + if (control === 'pip' && support.pip) { + container.appendChild(createButton.call(this, 'pip', defaultAttributes)); + } // Airplay button + + + if (control === 'airplay' && support.airplay) { + container.appendChild(createButton.call(this, 'airplay', defaultAttributes)); + } // Download button + + + if (control === 'download') { + const attributes = extend({}, defaultAttributes, { + element: 'a', + href: this.download, + target: '_blank' + }); // Set download attribute for HTML5 only + + if (this.isHTML5) { + attributes.download = ''; + } + + const { + download + } = this.config.urls; + + if (!is.url(download) && this.isEmbed) { + extend(attributes, { + icon: `logo-${this.provider}`, + label: this.provider + }); + } + + container.appendChild(createButton.call(this, 'download', attributes)); + } // Toggle fullscreen button + + + if (control === 'fullscreen') { + container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes)); + } + }); // Set available quality levels + + if (this.isHTML5) { + setQualityMenu.call(this, html5.getQualityOptions.call(this)); + } + + setSpeedMenu.call(this); + return container; + }, + + // Insert controls + inject() { + // Sprite + if (this.config.loadSprite) { + const icon = controls.getIconUrl.call(this); // Only load external sprite using AJAX + + if (icon.cors) { + loadSprite(icon.url, 'sprite-plyr'); + } + } // Create a unique ID + + + this.id = Math.floor(Math.random() * 10000); // Null by default + + let container = null; + this.elements.controls = null; // Set template properties + + const props = { + id: this.id, + seektime: this.config.seekTime, + title: this.config.title + }; + let update = true; // If function, run it and use output + + if (is.function(this.config.controls)) { + this.config.controls = this.config.controls.call(this, props); + } // Convert falsy controls to empty array (primarily for empty strings) + + + if (!this.config.controls) { + this.config.controls = []; + } + + if (is.element(this.config.controls) || is.string(this.config.controls)) { + // HTMLElement or Non-empty string passed as the option + container = this.config.controls; + } else { + // Create controls + container = controls.create.call(this, { + id: this.id, + seektime: this.config.seekTime, + speed: this.speed, + quality: this.quality, + captions: captions.getLabel.call(this) // TODO: Looping + // loop: 'None', + + }); + update = false; + } // Replace props with their value + + + const replace = input => { + let result = input; + Object.entries(props).forEach(([key, value]) => { + result = replaceAll(result, `{${key}}`, value); + }); + return result; + }; // Update markup + + + if (update) { + if (is.string(this.config.controls)) { + container = replace(container); + } + } // Controls container + + + let target; // Inject to custom location + + if (is.string(this.config.selectors.controls.container)) { + target = document.querySelector(this.config.selectors.controls.container); + } // Inject into the container by default + + + if (!is.element(target)) { + target = this.elements.container; + } // Inject controls HTML (needs to be before captions, hence "afterbegin") + + + const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML'; + target[insertMethod]('afterbegin', container); // Find the elements if need be + + if (!is.element(this.elements.controls)) { + controls.findElements.call(this); + } // Add pressed property to buttons + + + if (!is.empty(this.elements.buttons)) { + const addProperty = button => { + const className = this.config.classNames.controlPressed; + Object.defineProperty(button, 'pressed', { + enumerable: true, + + get() { + return hasClass(button, className); + }, + + set(pressed = false) { + toggleClass(button, className, pressed); + } + + }); + }; // Toggle classname when pressed property is set + + + Object.values(this.elements.buttons).filter(Boolean).forEach(button => { + if (is.array(button) || is.nodeList(button)) { + Array.from(button).filter(Boolean).forEach(addProperty); + } else { + addProperty(button); + } + }); + } // Edge sometimes doesn't finish the paint so force a repaint + + + if (browser.isEdge) { + repaint(target); + } // Setup tooltips + + + if (this.config.tooltips.controls) { + const { + classNames, + selectors + } = this.config; + const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`; + const labels = getElements.call(this, selector); + Array.from(labels).forEach(label => { + toggleClass(label, this.config.classNames.hidden, false); + toggleClass(label, this.config.classNames.tooltip, true); + }); + } + } + + }; + + // ========================================================================== + /** + * Parse a string to a URL object + * @param {String} input - the URL to be parsed + * @param {Boolean} safe - failsafe parsing + */ + + function parseUrl(input, safe = true) { + let url = input; + + if (safe) { + const parser = document.createElement('a'); + parser.href = url; + url = parser.href; + } + + try { + return new URL(url); + } catch (_) { + return null; + } + } // Convert object to URLSearchParams + + function buildUrlParams(input) { + const params = new URLSearchParams(); + + if (is.object(input)) { + Object.entries(input).forEach(([key, value]) => { + params.set(key, value); + }); + } + + return params; + } + + // ========================================================================== + const captions = { + // Setup captions + setup() { + // Requires UI support + if (!this.supported.ui) { + return; + } // Only Vimeo and HTML5 video supported at this point + + + if (!this.isVideo || this.isYouTube || this.isHTML5 && !support.textTracks) { + // Clear menu and hide + if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) { + controls.setCaptionsMenu.call(this); + } + + return; + } // Inject the container + + + if (!is.element(this.elements.captions)) { + this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions)); + insertAfter(this.elements.captions, this.elements.wrapper); + } // Fix IE captions if CORS is used + // Fetch captions and inject as blobs instead (data URIs not supported!) + + + if (browser.isIE && window.URL) { + const elements = this.media.querySelectorAll('track'); + Array.from(elements).forEach(track => { + const src = track.getAttribute('src'); + const url = parseUrl(src); + + if (url !== null && url.hostname !== window.location.href.hostname && ['http:', 'https:'].includes(url.protocol)) { + fetch(src, 'blob').then(blob => { + track.setAttribute('src', window.URL.createObjectURL(blob)); + }).catch(() => { + removeElement(track); + }); + } + }); + } // Get and set initial data + // The "preferred" options are not realized unless / until the wanted language has a match + // * languages: Array of user's browser languages. + // * language: The language preferred by user settings or config + // * active: The state preferred by user settings or config + // * toggled: The real captions state + + + const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en']; + const languages = dedupe(browserLanguages.map(language => language.split('-')[0])); + let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase(); // Use first browser language when language is 'auto' + + if (language === 'auto') { + [language] = languages; + } + + let active = this.storage.get('captions'); + + if (!is.boolean(active)) { + ({ + active + } = this.config.captions); + } + + Object.assign(this.captions, { + toggled: false, + active, + language, + languages + }); // Watch changes to textTracks and update captions menu + + if (this.isHTML5) { + const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack'; + on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this)); + } // Update available languages in list next tick (the event must not be triggered before the listeners) + + + setTimeout(captions.update.bind(this), 0); + }, + + // Update available language options in settings based on tracks + update() { + const tracks = captions.getTracks.call(this, true); // Get the wanted language + + const { + active, + language, + meta, + currentTrackNode + } = this.captions; + const languageExists = Boolean(tracks.find(track => track.language === language)); // Handle tracks (add event listener and "pseudo"-default) + + if (this.isHTML5 && this.isVideo) { + tracks.filter(track => !meta.get(track)).forEach(track => { + this.debug.log('Track added', track); // Attempt to store if the original dom element was "default" + + meta.set(track, { + default: track.mode === 'showing' + }); // Turn off native caption rendering to avoid double captions + // Note: mode='hidden' forces a track to download. To ensure every track + // isn't downloaded at once, only 'showing' tracks should be reassigned + // eslint-disable-next-line no-param-reassign + + if (track.mode === 'showing') { + // eslint-disable-next-line no-param-reassign + track.mode = 'hidden'; + } // Add event listener for cue changes + + + on.call(this, track, 'cuechange', () => captions.updateCues.call(this)); + }); + } // Update language first time it matches, or if the previous matching track was removed + + + if (languageExists && this.language !== language || !tracks.includes(currentTrackNode)) { + captions.setLanguage.call(this, language); + captions.toggle.call(this, active && languageExists); + } // Enable or disable captions based on track length + + + if (this.elements) { + toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks)); + } // Update available languages in list + + + if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) { + controls.setCaptionsMenu.call(this); + } + }, + + // Toggle captions display + // Used internally for the toggleCaptions method, with the passive option forced to false + toggle(input, passive = true) { + // If there's no full support + if (!this.supported.ui) { + return; + } + + const { + toggled + } = this.captions; // Current state + + const activeClass = this.config.classNames.captions.active; // Get the next state + // If the method is called without parameter, toggle based on current value + + const active = is.nullOrUndefined(input) ? !toggled : input; // Update state and trigger event + + if (active !== toggled) { + // When passive, don't override user preferences + if (!passive) { + this.captions.active = active; + this.storage.set({ + captions: active + }); + } // Force language if the call isn't passive and there is no matching language to toggle to + + + if (!this.language && active && !passive) { + const tracks = captions.getTracks.call(this); + const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true); // Override user preferences to avoid switching languages if a matching track is added + + this.captions.language = track.language; // Set caption, but don't store in localStorage as user preference + + captions.set.call(this, tracks.indexOf(track)); + return; + } // Toggle button if it's enabled + + + if (this.elements.buttons.captions) { + this.elements.buttons.captions.pressed = active; + } // Add class hook + + + toggleClass(this.elements.container, activeClass, active); + this.captions.toggled = active; // Update settings menu + + controls.updateSetting.call(this, 'captions'); // Trigger event (not used internally) + + triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled'); + } // Wait for the call stack to clear before setting mode='hidden' + // on the active track - forcing the browser to download it + + + setTimeout(() => { + if (active && this.captions.toggled) { + this.captions.currentTrackNode.mode = 'hidden'; + } + }); + }, + + // Set captions by track index + // Used internally for the currentTrack setter with the passive option forced to false + set(index, passive = true) { + const tracks = captions.getTracks.call(this); // Disable captions if setting to -1 + + if (index === -1) { + captions.toggle.call(this, false, passive); + return; + } + + if (!is.number(index)) { + this.debug.warn('Invalid caption argument', index); + return; + } + + if (!(index in tracks)) { + this.debug.warn('Track not found', index); + return; + } + + if (this.captions.currentTrack !== index) { + this.captions.currentTrack = index; + const track = tracks[index]; + const { + language + } = track || {}; // Store reference to node for invalidation on remove + + this.captions.currentTrackNode = track; // Update settings menu + + controls.updateSetting.call(this, 'captions'); // When passive, don't override user preferences + + if (!passive) { + this.captions.language = language; + this.storage.set({ + language + }); + } // Handle Vimeo captions + + + if (this.isVimeo) { + this.embed.enableTextTrack(language); + } // Trigger event + + + triggerEvent.call(this, this.media, 'languagechange'); + } // Show captions + + + captions.toggle.call(this, true, passive); + + if (this.isHTML5 && this.isVideo) { + // If we change the active track while a cue is already displayed we need to update it + captions.updateCues.call(this); + } + }, + + // Set captions by language + // Used internally for the language setter with the passive option forced to false + setLanguage(input, passive = true) { + if (!is.string(input)) { + this.debug.warn('Invalid language argument', input); + return; + } // Normalize + + + const language = input.toLowerCase(); + this.captions.language = language; // Set currentTrack + + const tracks = captions.getTracks.call(this); + const track = captions.findTrack.call(this, [language]); + captions.set.call(this, tracks.indexOf(track), passive); + }, + + // Get current valid caption tracks + // If update is false it will also ignore tracks without metadata + // This is used to "freeze" the language options when captions.update is false + getTracks(update = false) { + // Handle media or textTracks missing or null + const tracks = Array.from((this.media || {}).textTracks || []); // For HTML5, use cache instead of current tracks when it exists (if captions.update is false) + // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata) + + return tracks.filter(track => !this.isHTML5 || update || this.captions.meta.has(track)).filter(track => ['captions', 'subtitles'].includes(track.kind)); + }, + + // Match tracks based on languages and get the first + findTrack(languages, force = false) { + const tracks = captions.getTracks.call(this); + + const sortIsDefault = track => Number((this.captions.meta.get(track) || {}).default); + + const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a)); + let track; + languages.every(language => { + track = sorted.find(t => t.language === language); + return !track; // Break iteration if there is a match + }); // If no match is found but is required, get first + + return track || (force ? sorted[0] : undefined); + }, + + // Get the current track + getCurrentTrack() { + return captions.getTracks.call(this)[this.currentTrack]; + }, + + // Get UI label for track + getLabel(track) { + let currentTrack = track; + + if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) { + currentTrack = captions.getCurrentTrack.call(this); + } + + if (is.track(currentTrack)) { + if (!is.empty(currentTrack.label)) { + return currentTrack.label; + } + + if (!is.empty(currentTrack.language)) { + return track.language.toUpperCase(); + } + + return i18n.get('enabled', this.config); + } + + return i18n.get('disabled', this.config); + }, + + // Update captions using current track's active cues + // Also optional array argument in case there isn't any track (ex: vimeo) + updateCues(input) { + // Requires UI + if (!this.supported.ui) { + return; + } + + if (!is.element(this.elements.captions)) { + this.debug.warn('No captions element to render to'); + return; + } // Only accept array or empty input + + + if (!is.nullOrUndefined(input) && !Array.isArray(input)) { + this.debug.warn('updateCues: Invalid input', input); + return; + } + + let cues = input; // Get cues from track + + if (!cues) { + const track = captions.getCurrentTrack.call(this); + cues = Array.from((track || {}).activeCues || []).map(cue => cue.getCueAsHTML()).map(getHTML); + } // Set new caption text + + + const content = cues.map(cueText => cueText.trim()).join('\n'); + const changed = content !== this.elements.captions.innerHTML; + + if (changed) { + // Empty the container and create a new child element + emptyElement(this.elements.captions); + const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption)); + caption.innerHTML = content; + this.elements.captions.appendChild(caption); // Trigger event + + triggerEvent.call(this, this.media, 'cuechange'); + } + } + + }; + + // ========================================================================== + // Plyr default config + // ========================================================================== + const defaults = { + // Disable + enabled: true, + // Custom media title + title: '', + // Logging to console + debug: false, + // Auto play (if supported) + autoplay: false, + // Only allow one media playing at once (vimeo only) + autopause: true, + // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present) + // TODO: Remove iosNative fullscreen option in favour of this (logic needs work) + playsinline: true, + // Default time to skip when rewind/fast forward + seekTime: 10, + // Default volume + volume: 1, + muted: false, + // Pass a custom duration + duration: null, + // Display the media duration on load in the current time position + // If you have opted to display both duration and currentTime, this is ignored + displayDuration: true, + // Invert the current time to be a countdown + invertTime: true, + // Clicking the currentTime inverts it's value to show time left rather than elapsed + toggleInvert: true, + // Force an aspect ratio + // The format must be `'w:h'` (e.g. `'16:9'`) + ratio: null, + // Click video container to play/pause + clickToPlay: true, + // Auto hide the controls + hideControls: true, + // Reset to start when playback ended + resetOnEnd: false, + // Disable the standard context menu + disableContextMenu: true, + // Sprite (for icons) + loadSprite: true, + iconPrefix: 'plyr', + iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg', + // Blank video (used to prevent errors on source change) + blankVideo: 'https://cdn.plyr.io/static/blank.mp4', + // Quality default + quality: { + default: 576, + // The options to display in the UI, if available for the source media + options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240], + forced: false, + onChange: null + }, + // Set loops + loop: { + active: false // start: null, + // end: null, + + }, + // Speed default and options to display + speed: { + selected: 1, + // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x) + options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4] + }, + // Keyboard shortcut settings + keyboard: { + focused: true, + global: false + }, + // Display tooltips + tooltips: { + controls: false, + seek: true + }, + // Captions settings + captions: { + active: false, + language: 'auto', + // Listen to new tracks added after Plyr is initialized. + // This is needed for streaming captions, but may result in unselectable options + update: false + }, + // Fullscreen settings + fullscreen: { + enabled: true, + // Allow fullscreen? + fallback: true, + // Fallback using full viewport/window + iosNative: false // Use the native fullscreen in iOS (disables custom controls) + // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode + // Non-ancestors of the player element will be ignored + // container: null, // defaults to the player element + + }, + // Local storage + storage: { + enabled: true, + key: 'plyr' + }, + // Default controls + controls: ['play-large', // 'restart', + // 'rewind', + 'play', // 'fast-forward', + 'progress', 'current-time', // 'duration', + 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', // 'download', + 'fullscreen'], + settings: ['captions', 'quality', 'speed'], + // Localisation + i18n: { + restart: 'Restart', + rewind: 'Rewind {seektime}s', + play: 'Play', + pause: 'Pause', + fastForward: 'Forward {seektime}s', + seek: 'Seek', + seekLabel: '{currentTime} of {duration}', + played: 'Played', + buffered: 'Buffered', + currentTime: 'Current time', + duration: 'Duration', + volume: 'Volume', + mute: 'Mute', + unmute: 'Unmute', + enableCaptions: 'Enable captions', + disableCaptions: 'Disable captions', + download: 'Download', + enterFullscreen: 'Enter fullscreen', + exitFullscreen: 'Exit fullscreen', + frameTitle: 'Player for {title}', + captions: 'Captions', + settings: 'Settings', + pip: 'PIP', + menuBack: 'Go back to previous menu', + speed: 'Speed', + normal: 'Normal', + quality: 'Quality', + loop: 'Loop', + start: 'Start', + end: 'End', + all: 'All', + reset: 'Reset', + disabled: 'Disabled', + enabled: 'Enabled', + advertisement: 'Ad', + qualityBadge: { + 2160: '4K', + 1440: 'HD', + 1080: 'HD', + 720: 'HD', + 576: 'SD', + 480: 'SD' + } + }, + // URLs + urls: { + download: null, + vimeo: { + sdk: 'https://player.vimeo.com/api/player.js', + iframe: 'https://player.vimeo.com/video/{0}?{1}', + api: 'https://vimeo.com/api/oembed.json?url={0}' + }, + youtube: { + sdk: 'https://www.youtube.com/iframe_api', + api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}' + }, + googleIMA: { + sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js' + } + }, + // Custom control listeners + listeners: { + seek: null, + play: null, + pause: null, + restart: null, + rewind: null, + fastForward: null, + mute: null, + volume: null, + captions: null, + download: null, + fullscreen: null, + pip: null, + airplay: null, + speed: null, + quality: null, + loop: null, + language: null + }, + // Events to watch and bubble + events: [// Events to watch on HTML5 media elements and bubble + // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events + 'ended', 'progress', 'stalled', 'playing', 'waiting', 'canplay', 'canplaythrough', 'loadstart', 'loadeddata', 'loadedmetadata', 'timeupdate', 'volumechange', 'play', 'pause', 'error', 'seeking', 'seeked', 'emptied', 'ratechange', 'cuechange', // Custom events + 'download', 'enterfullscreen', 'exitfullscreen', 'captionsenabled', 'captionsdisabled', 'languagechange', 'controlshidden', 'controlsshown', 'ready', // YouTube + 'statechange', // Quality + 'qualitychange', // Ads + 'adsloaded', 'adscontentpause', 'adscontentresume', 'adstarted', 'adsmidpoint', 'adscomplete', 'adsallcomplete', 'adsimpression', 'adsclick'], + // Selectors + // Change these to match your template if using custom HTML + selectors: { + editable: 'input, textarea, select, [contenteditable]', + container: '.plyr', + controls: { + container: null, + wrapper: '.plyr__controls' + }, + labels: '[data-plyr]', + buttons: { + play: '[data-plyr="play"]', + pause: '[data-plyr="pause"]', + restart: '[data-plyr="restart"]', + rewind: '[data-plyr="rewind"]', + fastForward: '[data-plyr="fast-forward"]', + mute: '[data-plyr="mute"]', + captions: '[data-plyr="captions"]', + download: '[data-plyr="download"]', + fullscreen: '[data-plyr="fullscreen"]', + pip: '[data-plyr="pip"]', + airplay: '[data-plyr="airplay"]', + settings: '[data-plyr="settings"]', + loop: '[data-plyr="loop"]' + }, + inputs: { + seek: '[data-plyr="seek"]', + volume: '[data-plyr="volume"]', + speed: '[data-plyr="speed"]', + language: '[data-plyr="language"]', + quality: '[data-plyr="quality"]' + }, + display: { + currentTime: '.plyr__time--current', + duration: '.plyr__time--duration', + buffer: '.plyr__progress__buffer', + loop: '.plyr__progress__loop', + // Used later + volume: '.plyr__volume--display' + }, + progress: '.plyr__progress', + captions: '.plyr__captions', + caption: '.plyr__caption' + }, + // Class hooks added to the player in different states + classNames: { + type: 'plyr--{0}', + provider: 'plyr--{0}', + video: 'plyr__video-wrapper', + embed: 'plyr__video-embed', + videoFixedRatio: 'plyr__video-wrapper--fixed-ratio', + embedContainer: 'plyr__video-embed__container', + poster: 'plyr__poster', + posterEnabled: 'plyr__poster-enabled', + ads: 'plyr__ads', + control: 'plyr__control', + controlPressed: 'plyr__control--pressed', + playing: 'plyr--playing', + paused: 'plyr--paused', + stopped: 'plyr--stopped', + loading: 'plyr--loading', + hover: 'plyr--hover', + tooltip: 'plyr__tooltip', + cues: 'plyr__cues', + hidden: 'plyr__sr-only', + hideControls: 'plyr--hide-controls', + isIos: 'plyr--is-ios', + isTouch: 'plyr--is-touch', + uiSupported: 'plyr--full-ui', + noTransition: 'plyr--no-transition', + display: { + time: 'plyr__time' + }, + menu: { + value: 'plyr__menu__value', + badge: 'plyr__badge', + open: 'plyr--menu-open' + }, + captions: { + enabled: 'plyr--captions-enabled', + active: 'plyr--captions-active' + }, + fullscreen: { + enabled: 'plyr--fullscreen-enabled', + fallback: 'plyr--fullscreen-fallback' + }, + pip: { + supported: 'plyr--pip-supported', + active: 'plyr--pip-active' + }, + airplay: { + supported: 'plyr--airplay-supported', + 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 + attributes: { + embed: { + provider: 'data-plyr-provider', + id: 'data-plyr-embed-id', + hash: 'data-plyr-embed-hash' + } + }, + // Advertisements plugin + // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio + 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, + // Custom settings from Plyr + customControls: true, + referrerPolicy: null, + // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy + // Whether the owner of the video has a Pro or Business account + // (which allows us to properly hide controls without CSS hacks, etc) + premium: false + }, + // YouTube plugin + youtube: { + 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) + // Custom settings from Plyr + customControls: true, + noCookie: false // Whether to use an alternative version of YouTube without cookies + + } + }; + + // ========================================================================== + // Plyr states + // ========================================================================== + const pip = { + active: 'picture-in-picture', + inactive: 'inline' + }; + + // ========================================================================== + // Plyr supported types and providers + // ========================================================================== + const providers = { + html5: 'html5', + youtube: 'youtube', + vimeo: 'vimeo' + }; + const types = { + audio: 'audio', + video: 'video' + }; + /** + * Get provider by URL + * @param {String} url + */ + + function getProviderByUrl(url) { + // YouTube + if (/^(https?:\/\/)?(www\.)?(youtube\.com|youtube-nocookie\.com|youtu\.?be)\/.+$/.test(url)) { + return providers.youtube; + } // Vimeo + + + if (/^https?:\/\/player.vimeo.com\/video\/\d{0,9}(?=\b|\/)/.test(url)) { + return providers.vimeo; + } + + return null; + } + + // ========================================================================== + // Console wrapper + // ========================================================================== + const noop = () => {}; + + class Console { + constructor(enabled = false) { + this.enabled = window.console && enabled; + + if (this.enabled) { + this.log('Debugging enabled'); + } + } + + get log() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.log, console) : noop; + } + + get warn() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop; + } + + get error() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.error, console) : noop; + } + + } + + class Fullscreen { + constructor(player) { + _defineProperty$1(this, "onChange", () => { + if (!this.enabled) { + return; + } // Update toggle button + + + const button = this.player.elements.buttons.fullscreen; + + if (is.element(button)) { + button.pressed = this.active; + } // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up + + + const target = this.target === this.player.media ? this.target : this.player.elements.container; // Trigger an event + + triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true); + }); + + _defineProperty$1(this, "toggleFallback", (toggle = false) => { + // Store or restore scroll position + if (toggle) { + this.scrollPosition = { + x: window.scrollX || 0, + y: window.scrollY || 0 + }; + } else { + window.scrollTo(this.scrollPosition.x, this.scrollPosition.y); + } // Toggle scroll + + + document.body.style.overflow = toggle ? 'hidden' : ''; // Toggle class hook + + toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle); // Force full viewport on iPhone X+ + + if (browser.isIos) { + let viewport = document.head.querySelector('meta[name="viewport"]'); + const property = 'viewport-fit=cover'; // Inject the viewport meta if required + + if (!viewport) { + viewport = document.createElement('meta'); + viewport.setAttribute('name', 'viewport'); + } // Check if the property already exists + + + const hasProperty = is.string(viewport.content) && viewport.content.includes(property); + + if (toggle) { + this.cleanupViewport = !hasProperty; + + if (!hasProperty) { + viewport.content += `,${property}`; + } + } else if (this.cleanupViewport) { + viewport.content = viewport.content.split(',').filter(part => part.trim() !== property).join(','); + } + } // Toggle button and fire events + + + this.onChange(); + }); + + _defineProperty$1(this, "trapFocus", event => { + // Bail if iOS, not active, not the tab key + if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) { + return; + } // Get the current focused element + + + const focused = document.activeElement; + const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]'); + const [first] = focusable; + const last = focusable[focusable.length - 1]; + + if (focused === last && !event.shiftKey) { + // Move focus to first element that can be tabbed if Shift isn't used + first.focus(); + event.preventDefault(); + } else if (focused === first && event.shiftKey) { + // Move focus to last element that can be tabbed if Shift is used + last.focus(); + event.preventDefault(); + } + }); + + _defineProperty$1(this, "update", () => { + if (this.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'); + } // Add styling hook to show button + + + toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled); + }); + + _defineProperty$1(this, "enter", () => { + if (!this.enabled) { + return; + } // iOS native fullscreen doesn't need the request step + + + if (browser.isIos && this.player.config.fullscreen.iosNative) { + if (this.player.isVimeo) { + this.player.embed.requestFullscreen(); + } else { + this.target.webkitEnterFullscreen(); + } + } else if (!Fullscreen.native || this.forceFallback) { + this.toggleFallback(true); + } else if (!this.prefix) { + this.target.requestFullscreen({ + navigationUI: 'hide' + }); + } else if (!is.empty(this.prefix)) { + this.target[`${this.prefix}Request${this.property}`](); + } + }); + + _defineProperty$1(this, "exit", () => { + if (!this.enabled) { + return; + } // iOS native fullscreen + + + if (browser.isIos && this.player.config.fullscreen.iosNative) { + this.target.webkitExitFullscreen(); + silencePromise(this.player.play()); + } else if (!Fullscreen.native || this.forceFallback) { + this.toggleFallback(false); + } else if (!this.prefix) { + (document.cancelFullScreen || document.exitFullscreen).call(document); + } else if (!is.empty(this.prefix)) { + const action = this.prefix === 'moz' ? 'Cancel' : 'Exit'; + document[`${this.prefix}${action}${this.property}`](); + } + }); + + _defineProperty$1(this, "toggle", () => { + if (!this.active) { + this.enter(); + } else { + this.exit(); + } + }); + + // Keep reference to parent + this.player = player; // Get prefix + + this.prefix = Fullscreen.prefix; + this.property = Fullscreen.property; // 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'; // Get the fullscreen element + // Checks container is an ancestor, defaults to null + + this.player.elements.fullscreen = player.config.fullscreen.container && closest$1(this.player.elements.container, player.config.fullscreen.container); // Register event listeners + // Handle event (incase user presses escape etc) + + on.call(this.player, document, this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`, () => { + // TODO: Filter for target?? + this.onChange(); + }); // Fullscreen toggle on double click + + on.call(this.player, this.player.elements.container, 'dblclick', event => { + // Ignore double click in controls + if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) { + return; + } + + this.player.listeners.proxy(event, this.toggle, 'fullscreen'); + }); // Tap focus when in fullscreen + + on.call(this, this.player.elements.container, 'keydown', event => this.trapFocus(event)); // Update the UI + + this.update(); // this.toggle = this.toggle.bind(this); + } // Determine if native supported + + + static get native() { + return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled); + } // If we're actually using native + + + get usingNative() { + return Fullscreen.native && !this.forceFallback; + } // Get the prefix for handlers + + + static get prefix() { + // No prefix + if (is.function(document.exitFullscreen)) { + return ''; + } // Check for fullscreen support by vendor prefix + + + let value = ''; + const prefixes = ['webkit', 'moz', 'ms']; + prefixes.some(pre => { + if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) { + value = pre; + return true; + } + + return false; + }); + return value; + } + + static get property() { + return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen'; + } // Determine if fullscreen is enabled + + + get enabled() { + return (Fullscreen.native || this.player.config.fullscreen.fallback) && this.player.config.fullscreen.enabled && this.player.supported.ui && this.player.isVideo; + } // Get active state + + + get active() { + if (!this.enabled) { + return false; + } // Fallback using classname + + + if (!Fullscreen.native || this.forceFallback) { + return hasClass(this.target, this.player.config.classNames.fullscreen.fallback); + } + + const element = !this.prefix ? this.target.getRootNode().fullscreenElement : this.target.getRootNode()[`${this.prefix}${this.property}Element`]; + return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target; + } // Get target element + + + get target() { + return browser.isIos && this.player.config.fullscreen.iosNative ? this.player.media : this.player.elements.fullscreen || this.player.elements.container; + } + + } + + // ========================================================================== + // Load image avoiding xhr/fetch CORS issues + // Server status can't be obtained this way unfortunately, so this uses "naturalWidth" to determine if the image has loaded + // By default it checks if it is at least 1px, but you can add a second argument to change this + // ========================================================================== + function loadImage(src, minWidth = 1) { + return new Promise((resolve, reject) => { + const image = new Image(); + + const handler = () => { + delete image.onload; + delete image.onerror; + (image.naturalWidth >= minWidth ? resolve : reject)(image); + }; + + Object.assign(image, { + onload: handler, + onerror: handler, + src + }); + }); + } + + // ========================================================================== + const ui = { + addStyleHook() { + toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true); + toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui); + }, + + // Toggle native HTML5 media controls + toggleNativeControls(toggle = false) { + if (toggle && this.isHTML5) { + this.media.setAttribute('controls', ''); + } else { + this.media.removeAttribute('controls'); + } + }, + + // Setup the UI + build() { + // Re-attach media element listeners + // TODO: Use event bubbling? + this.listeners.media(); // Don't setup interface if no support + + if (!this.supported.ui) { + this.debug.warn(`Basic support only for ${this.provider} ${this.type}`); // Restore native controls + + ui.toggleNativeControls.call(this, true); // Bail + + return; + } // Inject custom controls if not present + + + if (!is.element(this.elements.controls)) { + // Inject custom controls + controls.inject.call(this); // Re-attach control listeners + + this.listeners.controls(); + } // Remove native controls + + + ui.toggleNativeControls.call(this); // Setup captions for HTML5 + + if (this.isHTML5) { + captions.setup.call(this); + } // Reset volume + + + this.volume = null; // Reset mute state + + this.muted = null; // Reset loop state + + this.loop = null; // Reset quality setting + + this.quality = null; // Reset speed + + this.speed = null; // Reset volume display + + controls.updateVolume.call(this); // Reset time display + + controls.timeUpdate.call(this); // Reset duration display + + controls.durationUpdate.call(this); // Update the UI + + ui.checkPlaying.call(this); // Check for picture-in-picture support + + toggleClass(this.elements.container, this.config.classNames.pip.supported, support.pip && this.isHTML5 && this.isVideo); // Check for airplay support + + toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5); // Add iOS class + + toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos); // Add touch class + + toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch); // Ready for API calls + + this.ready = true; // Ready event at end of execution stack + + setTimeout(() => { + triggerEvent.call(this, this.media, 'ready'); + }, 0); // Set the title + + ui.setTitle.call(this); // Assure the poster image is set, if the property was added before the element was created + + if (this.poster) { + ui.setPoster.call(this, this.poster, false).catch(() => {}); + } // Manually set the duration if user has overridden it. + // The event listeners for it doesn't get called if preload is disabled (#701) + + + if (this.config.duration) { + controls.durationUpdate.call(this); + } + }, + + // Setup aria attribute for play and iframe title + setTitle() { + // Find the current text + let label = i18n.get('play', this.config); // If there's a media title set, use that for the label + + if (is.string(this.config.title) && !is.empty(this.config.title)) { + label += `, ${this.config.title}`; + } // If there's a play button, set label + + + Array.from(this.elements.buttons.play || []).forEach(button => { + button.setAttribute('aria-label', label); + }); // Set iframe title + // https://github.com/sampotts/plyr/issues/124 + + if (this.isEmbed) { + const iframe = getElement.call(this, 'iframe'); + + if (!is.element(iframe)) { + return; + } // Default to media type + + + const title = !is.empty(this.config.title) ? this.config.title : 'video'; + const format = i18n.get('frameTitle', this.config); + iframe.setAttribute('title', format.replace('{title}', title)); + } + }, + + // Toggle poster + togglePoster(enable) { + toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable); + }, + + // Set the poster image (async) + // Used internally for the poster setter, with the passive option forced to false + setPoster(poster, passive = true) { + // Don't override if call is passive + if (passive && this.poster) { + return Promise.reject(new Error('Poster already set')); + } // Set property synchronously to respect the call order + + + this.media.setAttribute('data-poster', poster); // Show the poster + + this.elements.poster.removeAttribute('hidden'); // Wait until ui is ready + + return ready.call(this) // Load image + .then(() => loadImage(poster)).catch(error => { + // Hide poster on error unless it's been set by another call + if (poster === this.poster) { + ui.togglePoster.call(this, false); + } // Rethrow + + + throw error; + }).then(() => { + // Prevent race conditions + if (poster !== this.poster) { + throw new Error('setPoster cancelled by later call to setPoster'); + } + }).then(() => { + Object.assign(this.elements.poster.style, { + backgroundImage: `url('${poster}')`, + // Reset backgroundSize as well (since it can be set to "cover" for padded thumbnails for youtube) + backgroundSize: '' + }); + ui.togglePoster.call(this, true); + return poster; + }); + }, + + // Check playing state + checkPlaying(event) { + // Class hooks + toggleClass(this.elements.container, this.config.classNames.playing, this.playing); + toggleClass(this.elements.container, this.config.classNames.paused, this.paused); + toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped); // Set state + + Array.from(this.elements.buttons.play || []).forEach(target => { + Object.assign(target, { + pressed: this.playing + }); + target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config)); + }); // Only update controls on non timeupdate events + + if (is.event(event) && event.type === 'timeupdate') { + return; + } // Toggle controls + + + ui.toggleControls.call(this); + }, + + // Check if media is loading + checkLoading(event) { + this.loading = ['stalled', 'waiting'].includes(event.type); // Clear timer + + clearTimeout(this.timers.loading); // Timer to prevent flicker when seeking + + this.timers.loading = setTimeout(() => { + // Update progress bar loading class state + toggleClass(this.elements.container, this.config.classNames.loading, this.loading); // Update controls visibility + + ui.toggleControls.call(this); + }, this.loading ? 250 : 0); + }, + + // Toggle controls based on state and `force` argument + toggleControls(force) { + const { + controls: controlsElement + } = this.elements; + + if (controlsElement && this.config.hideControls) { + // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.) + const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now(); // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide + + this.toggleControls(Boolean(force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek)); + } + }, + + // Migrate any custom properties from the media to the parent + migrateStyles() { + // Loop through values (as they are the keys when the object is spread 🤔) + Object.values({ ...this.media.style + }) // We're only fussed about Plyr specific properties + .filter(key => !is.empty(key) && is.string(key) && key.startsWith('--plyr')).forEach(key => { + // Set on the container + this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key)); // Clean up from media element + + this.media.style.removeProperty(key); + }); // Remove attribute if empty + + if (is.empty(this.media.style)) { + this.media.removeAttribute('style'); + } + } + + }; + + class Listeners { + constructor(_player) { + _defineProperty$1(this, "firstTouch", () => { + const { + player + } = this; + const { + elements + } = player; + player.touch = true; // Add touch class + + toggleClass(elements.container, player.config.classNames.isTouch, true); + }); + + _defineProperty$1(this, "setTabFocus", event => { + const { + player + } = this; + const { + elements + } = player; + clearTimeout(this.focusTimer); // Ignore any key other than tab + + if (event.type === 'keydown' && event.which !== 9) { + return; + } // Store reference to event timeStamp + + + if (event.type === 'keydown') { + this.lastKeyDown = event.timeStamp; + } // Remove current classes + + + const removeCurrent = () => { + const className = player.config.classNames.tabFocus; + const current = getElements.call(player, `.${className}`); + toggleClass(current, className, false); + }; // Determine if a key was pressed to trigger this event + + + const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20; // Ignore focus events if a key was pressed prior + + if (event.type === 'focus' && !wasKeyDown) { + return; + } // Remove all current + + + removeCurrent(); // Delay the adding of classname until the focus has changed + // This event fires before the focusin event + + if (event.type !== 'focusout') { + this.focusTimer = setTimeout(() => { + const focused = document.activeElement; // Ignore if current focus element isn't inside the player + + if (!elements.container.contains(focused)) { + return; + } + + toggleClass(document.activeElement, player.config.classNames.tabFocus, true); + }, 10); + } + }); + + _defineProperty$1(this, "global", (toggle = true) => { + const { + player + } = this; // Keyboard shortcuts + + if (player.config.keyboard.global) { + toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false); + } // Click anywhere closes menu + + + toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle); // Detect touch by events + + once.call(player, document.body, 'touchstart', this.firstTouch); // Tab focus detection + + toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true); + }); + + _defineProperty$1(this, "container", () => { + const { + player + } = this; + const { + config, + elements, + timers + } = player; // Keyboard shortcuts + + if (!config.keyboard.global && config.keyboard.focused) { + on.call(player, elements.container, 'keydown keyup', this.handleKey, false); + } // Toggle controls on mouse events and entering fullscreen + + + on.call(player, elements.container, 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen', event => { + const { + controls: controlsElement + } = elements; // Remove button states for fullscreen + + if (controlsElement && event.type === 'enterfullscreen') { + controlsElement.pressed = false; + controlsElement.hover = false; + } // Show, then hide after a timeout unless another control event occurs + + + const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type); + let delay = 0; + + if (show) { + ui.toggleControls.call(player, true); // Use longer timeout for touch devices + + delay = player.touch ? 3000 : 2000; + } // Clear timer + + + clearTimeout(timers.controls); // Set new timer to prevent flicker when seeking + + timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay); + }); // Set a gutter for Vimeo + + const setGutter = () => { + if (!player.isVimeo || player.config.vimeo.premium) { + return; + } + + const target = elements.wrapper; + const { + active + } = player.fullscreen; + const [videoWidth, videoHeight] = getAspectRatio.call(player); + const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`); // If not active, remove styles + + if (!active) { + if (useNativeAspectRatio) { + target.style.width = null; + target.style.height = null; + } else { + target.style.maxWidth = null; + target.style.margin = null; + } + + return; + } // Determine which dimension will overflow and constrain view + + + const [viewportWidth, viewportHeight] = getViewportSize(); + const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight; + + if (useNativeAspectRatio) { + target.style.width = overflow ? 'auto' : '100%'; + target.style.height = overflow ? '100%' : 'auto'; + } else { + target.style.maxWidth = overflow ? `${viewportHeight / videoHeight * videoWidth}px` : null; + target.style.margin = overflow ? '0 auto' : null; + } + }; // Handle resizing + + + const resized = () => { + clearTimeout(timers.resized); + timers.resized = setTimeout(setGutter, 50); + }; + + on.call(player, elements.container, 'enterfullscreen exitfullscreen', event => { + const { + target + } = player.fullscreen; // Ignore events not from target + + if (target !== elements.container) { + return; + } // If it's not an embed and no ratio specified + + + if (!player.isEmbed && is.empty(player.config.ratio)) { + return; + } // Set Vimeo gutter + + + setGutter(); // Watch for resizes + + const method = event.type === 'enterfullscreen' ? on : off; + method.call(player, window, 'resize', resized); + }); + }); + + _defineProperty$1(this, "media", () => { + const { + player + } = this; + const { + elements + } = player; // Time change on media + + on.call(player, player.media, 'timeupdate seeking seeked', event => controls.timeUpdate.call(player, event)); // Display duration + + on.call(player, player.media, 'durationchange loadeddata loadedmetadata', event => controls.durationUpdate.call(player, event)); // Handle the media finishing + + on.call(player, player.media, 'ended', () => { + // Show poster on end + if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) { + // Restart + player.restart(); // Call pause otherwise IE11 will start playing the video again + + player.pause(); + } + }); // Check for buffer progress + + on.call(player, player.media, 'progress playing seeking seeked', event => controls.updateProgress.call(player, event)); // Handle volume changes + + on.call(player, player.media, 'volumechange', event => controls.updateVolume.call(player, event)); // Handle play/pause + + on.call(player, player.media, 'playing play pause ended emptied timeupdate', event => ui.checkPlaying.call(player, event)); // Loading state + + on.call(player, player.media, 'waiting canplay seeked playing', event => ui.checkLoading.call(player, event)); // Click video + + if (player.supported.ui && player.config.clickToPlay && !player.isAudio) { + // Re-fetch the wrapper + const wrapper = getElement.call(player, `.${player.config.classNames.video}`); // Bail if there's no wrapper (this should never happen) + + if (!is.element(wrapper)) { + return; + } // On click play, pause or restart + + + on.call(player, elements.container, 'click', event => { + const targets = [elements.container, wrapper]; // Ignore if click if not container or in video wrapper + + if (!targets.includes(event.target) && !wrapper.contains(event.target)) { + return; + } // Touch devices will just show controls (if hidden) + + + if (player.touch && player.config.hideControls) { + return; + } + + if (player.ended) { + this.proxy(event, player.restart, 'restart'); + this.proxy(event, () => { + silencePromise(player.play()); + }, 'play'); + } else { + this.proxy(event, () => { + silencePromise(player.togglePlay()); + }, 'play'); + } + }); + } // Disable right click + + + if (player.supported.ui && player.config.disableContextMenu) { + on.call(player, elements.wrapper, 'contextmenu', event => { + event.preventDefault(); + }, false); + } // Volume change + + + on.call(player, player.media, 'volumechange', () => { + // Save to storage + player.storage.set({ + volume: player.volume, + muted: player.muted + }); + }); // Speed change + + on.call(player, player.media, 'ratechange', () => { + // Update UI + controls.updateSetting.call(player, 'speed'); // Save to storage + + player.storage.set({ + speed: player.speed + }); + }); // Quality change + + on.call(player, player.media, 'qualitychange', event => { + // Update UI + controls.updateSetting.call(player, 'quality', null, event.detail.quality); + }); // Update download link when ready and if quality changes + + on.call(player, player.media, 'ready qualitychange', () => { + controls.setDownloadUrl.call(player); + }); // Proxy events to container + // Bubble up key events for Edge + + const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' '); + on.call(player, player.media, proxyEvents, event => { + let { + detail = {} + } = event; // Get error details from media + + if (event.type === 'error') { + detail = player.media.error; + } + + triggerEvent.call(player, elements.container, event.type, true, detail); + }); + }); + + _defineProperty$1(this, "proxy", (event, defaultHandler, customHandlerKey) => { + const { + player + } = this; + const customHandler = player.config.listeners[customHandlerKey]; + const hasCustomHandler = is.function(customHandler); + let returned = true; // Execute custom handler + + if (hasCustomHandler) { + returned = customHandler.call(player, event); + } // Only call default handler if not prevented in custom handler + + + if (returned !== false && is.function(defaultHandler)) { + defaultHandler.call(player, event); + } + }); + + _defineProperty$1(this, "bind", (element, type, defaultHandler, customHandlerKey, passive = true) => { + const { + player + } = this; + const customHandler = player.config.listeners[customHandlerKey]; + const hasCustomHandler = is.function(customHandler); + on.call(player, element, type, event => this.proxy(event, defaultHandler, customHandlerKey), passive && !hasCustomHandler); + }); + + _defineProperty$1(this, "controls", () => { + const { + player + } = this; + const { + elements + } = player; // IE doesn't support input event, so we fallback to change + + const inputEvent = browser.isIE ? 'change' : 'input'; // Play/pause toggle + + if (elements.buttons.play) { + Array.from(elements.buttons.play).forEach(button => { + this.bind(button, 'click', () => { + silencePromise(player.togglePlay()); + }, 'play'); + }); + } // Pause + + + this.bind(elements.buttons.restart, 'click', player.restart, 'restart'); // Rewind + + this.bind(elements.buttons.rewind, 'click', () => { + // Record seek time so we can prevent hiding controls for a few seconds after rewind + player.lastSeekTime = Date.now(); + player.rewind(); + }, 'rewind'); // Rewind + + this.bind(elements.buttons.fastForward, 'click', () => { + // Record seek time so we can prevent hiding controls for a few seconds after fast forward + player.lastSeekTime = Date.now(); + player.forward(); + }, 'fastForward'); // Mute toggle + + this.bind(elements.buttons.mute, 'click', () => { + player.muted = !player.muted; + }, 'mute'); // Captions toggle + + this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions()); // Download + + this.bind(elements.buttons.download, 'click', () => { + triggerEvent.call(player, player.media, 'download'); + }, 'download'); // Fullscreen toggle + + this.bind(elements.buttons.fullscreen, 'click', () => { + player.fullscreen.toggle(); + }, 'fullscreen'); // Picture-in-Picture + + this.bind(elements.buttons.pip, 'click', () => { + player.pip = 'toggle'; + }, 'pip'); // Airplay + + this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay'); // Settings menu - click toggle + + this.bind(elements.buttons.settings, 'click', event => { + // Prevent the document click listener closing the menu + event.stopPropagation(); + event.preventDefault(); + controls.toggleMenu.call(player, event); + }, null, false); // Can't be passive as we're preventing default + // Settings menu - keyboard toggle + // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus + // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143 + + this.bind(elements.buttons.settings, 'keyup', event => { + const code = event.which; // We only care about space and return + + if (![13, 32].includes(code)) { + return; + } // Because return triggers a click anyway, all we need to do is set focus + + + if (code === 13) { + controls.focusFirstMenuItem.call(player, null, true); + return; + } // Prevent scroll + + + event.preventDefault(); // Prevent playing video (Firefox) + + event.stopPropagation(); // Toggle menu + + controls.toggleMenu.call(player, event); + }, null, false // Can't be passive as we're preventing default + ); // Escape closes menu + + this.bind(elements.settings.menu, 'keydown', event => { + if (event.which === 27) { + controls.toggleMenu.call(player, event); + } + }); // Set range input alternative "value", which matches the tooltip time (#954) + + this.bind(elements.inputs.seek, 'mousedown mousemove', event => { + const rect = elements.progress.getBoundingClientRect(); + const percent = 100 / rect.width * (event.pageX - rect.left); + event.currentTarget.setAttribute('seek-value', percent); + }); // Pause while seeking + + this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', event => { + const seek = event.currentTarget; + const code = event.keyCode ? event.keyCode : event.which; + const attribute = 'play-on-seeked'; + + if (is.keyboardEvent(event) && code !== 39 && code !== 37) { + return; + } // Record seek time so we can prevent hiding controls for a few seconds after seek + + + player.lastSeekTime = Date.now(); // Was playing before? + + const play = seek.hasAttribute(attribute); // Done seeking + + const done = ['mouseup', 'touchend', 'keyup'].includes(event.type); // If we're done seeking and it was playing, resume playback + + if (play && done) { + seek.removeAttribute(attribute); + silencePromise(player.play()); + } else if (!done && player.playing) { + seek.setAttribute(attribute, ''); + player.pause(); + } + }); // Fix range inputs on iOS + // Super weird iOS bug where after you interact with an <input type="range">, + // it takes over further interactions on the page. This is a hack + + if (browser.isIos) { + const inputs = getElements.call(player, 'input[type="range"]'); + Array.from(inputs).forEach(input => this.bind(input, inputEvent, event => repaint(event.target))); + } // Seek + + + this.bind(elements.inputs.seek, inputEvent, event => { + const seek = event.currentTarget; // If it exists, use seek-value instead of "value" for consistency with tooltip time (#954) + + let seekTo = seek.getAttribute('seek-value'); + + if (is.empty(seekTo)) { + seekTo = seek.value; + } + + seek.removeAttribute('seek-value'); + player.currentTime = seekTo / seek.max * player.duration; + }, 'seek'); // Seek tooltip + + this.bind(elements.progress, 'mouseenter mouseleave mousemove', event => 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 touchend 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 => { + this.bind(element, 'input', event => controls.updateRangeFill.call(player, event.target)); + }); + } // Current time invert + // Only if one time element is used for both currentTime and duration + + + if (player.config.toggleInvert && !is.element(elements.display.duration)) { + this.bind(elements.display.currentTime, 'click', () => { + // Do nothing if we're at the start + if (player.currentTime === 0) { + return; + } + + player.config.invertTime = !player.config.invertTime; + controls.timeUpdate.call(player); + }); + } // Volume + + + this.bind(elements.inputs.volume, inputEvent, event => { + player.volume = event.target.value; + }, 'volume'); // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting) + + this.bind(elements.controls, 'mouseenter mouseleave', event => { + elements.controls.hover = !player.touch && event.type === 'mouseenter'; + }); // Also update controls.hover state for any non-player children of fullscreen element (as above) + + if (elements.fullscreen) { + Array.from(elements.fullscreen.children).filter(c => !c.contains(elements.container)).forEach(child => { + this.bind(child, 'mouseenter mouseleave', event => { + if (elements.controls) { + elements.controls.hover = !player.touch && event.type === 'mouseenter'; + } + }); + }); + } // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting) + + + this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', event => { + elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type); + }); // Show controls when they receive focus (e.g., when using keyboard tab key) + + this.bind(elements.controls, 'focusin', () => { + const { + config, + timers + } = player; // Skip transition to prevent focus from scrolling the parent element + + toggleClass(elements.controls, config.classNames.noTransition, true); // Toggle + + ui.toggleControls.call(player, true); // Restore transition + + setTimeout(() => { + toggleClass(elements.controls, config.classNames.noTransition, false); + }, 0); // Delay a little more for mouse users + + const delay = this.touch ? 3000 : 4000; // Clear timer + + clearTimeout(timers.controls); // Hide again after delay + + timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay); + }); // Mouse wheel for volume + + this.bind(elements.inputs.volume, 'wheel', event => { + // Detect "natural" scroll - suppored on OS X Safari only + // Other browsers on OS X will be inverted until support improves + const inverted = event.webkitDirectionInvertedFromDevice; // Get delta from event. Invert if `inverted` is true + + const [x, y] = [event.deltaX, -event.deltaY].map(value => inverted ? -value : value); // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta) + + const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y); // Change the volume by 2% + + player.increaseVolume(direction / 50); // Don't break page scrolling at max and min + + const { + volume + } = player.media; + + if (direction === 1 && volume < 1 || direction === -1 && volume > 0) { + event.preventDefault(); + } + }, 'volume', false); + }); + + this.player = _player; + this.lastKey = null; + this.focusTimer = null; + this.lastKeyDown = null; + this.handleKey = this.handleKey.bind(this); + this.toggleMenu = this.toggleMenu.bind(this); + this.setTabFocus = this.setTabFocus.bind(this); + this.firstTouch = this.firstTouch.bind(this); + } // Handle key presses + + + handleKey(event) { + const { + player + } = this; + const { + elements + } = player; + const code = event.keyCode ? event.keyCode : event.which; + const pressed = event.type === 'keydown'; + const repeat = pressed && code === this.lastKey; // Bail if a modifier key is set + + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { + return; + } // If the event is bubbled from the media element + // Firefox doesn't get the keycode for whatever reason + + + if (!is.number(code)) { + return; + } // Seek by the number keys + + + const seekByKey = () => { + // Divide the max duration into 10th's and times by the number value + player.currentTime = player.duration / 10 * (code - 48); + }; // Handle the key on keydown + // Reset on keyup + + + if (pressed) { + // Check focused element + // and if the focused element is not editable (e.g. text input) + // and any that accept key input http://webaim.org/techniques/keyboard/ + const focused = document.activeElement; + + if (is.element(focused)) { + const { + editable + } = player.config.selectors; + const { + seek + } = elements.inputs; + + if (focused !== seek && matches(focused, editable)) { + return; + } + + if (event.which === 32 && matches(focused, 'button, [role^="menuitem"]')) { + return; + } + } // Which keycodes should we prevent default + + + const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79]; // If the code is found prevent default (e.g. prevent scrolling for arrows) + + if (preventDefault.includes(code)) { + event.preventDefault(); + event.stopPropagation(); + } + + switch (code) { + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + // 0-9 + if (!repeat) { + seekByKey(); + } + + break; + + case 32: + case 75: + // Space and K key + if (!repeat) { + silencePromise(player.togglePlay()); + } + + break; + + case 38: + // Arrow up + player.increaseVolume(0.1); + break; + + case 40: + // Arrow down + player.decreaseVolume(0.1); + break; + + case 77: + // M key + if (!repeat) { + player.muted = !player.muted; + } + + break; + + case 39: + // Arrow forward + player.forward(); + break; + + case 37: + // Arrow back + player.rewind(); + break; + + case 70: + // F key + player.fullscreen.toggle(); + break; + + case 67: + // C key + if (!repeat) { + player.toggleCaptions(); + } + + break; + + case 76: + // L key + player.loop = !player.loop; + break; + } // Escape is handle natively when in full screen + // So we only need to worry about non native + + + if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) { + player.fullscreen.toggle(); + } // Store last code for next cycle + + + this.lastKey = code; + } else { + this.lastKey = null; + } + } // Toggle menu + + + toggleMenu(event) { + controls.toggleMenu.call(this.player, event); + } // Device is touch enabled + + + } + + var loadjs_umd = createCommonjsModule(function (module, exports) { + (function (root, factory) { + { + module.exports = factory(); + } + })(commonjsGlobal, function () { + /** + * Global dependencies. + * @global {Object} document - DOM + */ + var devnull = function () {}, + bundleIdCache = {}, + bundleResultCache = {}, + bundleCallbackQueue = {}; + /** + * Subscribe to bundle load event. + * @param {string[]} bundleIds - Bundle ids + * @param {Function} callbackFn - The callback function + */ + + + function subscribe(bundleIds, callbackFn) { + // listify + bundleIds = bundleIds.push ? bundleIds : [bundleIds]; + var depsNotFound = [], + i = bundleIds.length, + numWaiting = i, + fn, + bundleId, + r, + q; // define callback function + + fn = function (bundleId, pathsNotFound) { + if (pathsNotFound.length) depsNotFound.push(bundleId); + numWaiting--; + if (!numWaiting) callbackFn(depsNotFound); + }; // register callback + + + while (i--) { + bundleId = bundleIds[i]; // execute callback if in result cache + + r = bundleResultCache[bundleId]; + + if (r) { + fn(bundleId, r); + continue; + } // add to callback queue + + + q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || []; + q.push(fn); + } + } + /** + * Publish bundle load event. + * @param {string} bundleId - Bundle id + * @param {string[]} pathsNotFound - List of files not found + */ + + + function publish(bundleId, pathsNotFound) { + // exit if id isn't defined + if (!bundleId) return; + var q = bundleCallbackQueue[bundleId]; // cache result + + bundleResultCache[bundleId] = pathsNotFound; // exit if queue is empty + + if (!q) return; // empty callback queue + + while (q.length) { + q[0](bundleId, pathsNotFound); + q.splice(0, 1); + } + } + /** + * Execute callbacks. + * @param {Object or Function} args - The callback args + * @param {string[]} depsNotFound - List of dependencies not found + */ + + + function executeCallbacks(args, depsNotFound) { + // accept function as argument + if (args.call) args = { + success: args + }; // success and error callbacks + + if (depsNotFound.length) (args.error || devnull)(depsNotFound);else (args.success || devnull)(args); + } + /** + * Load individual file. + * @param {string} path - The file path + * @param {Function} callbackFn - The callback function + */ + + + function loadFile(path, callbackFn, args, numTries) { + var doc = document, + async = args.async, + maxTries = (args.numRetries || 0) + 1, + beforeCallbackFn = args.before || devnull, + pathname = path.replace(/[\?|#].*$/, ''), + pathStripped = path.replace(/^(css|img)!/, ''), + isLegacyIECss, + e; + numTries = numTries || 0; + + if (/(^css!|\.css$)/.test(pathname)) { + // css + e = doc.createElement('link'); + e.rel = 'stylesheet'; + e.href = pathStripped; // tag IE9+ + + isLegacyIECss = 'hideFocus' in e; // use preload in IE Edge (to detect load errors) + + if (isLegacyIECss && e.relList) { + isLegacyIECss = 0; + e.rel = 'preload'; + e.as = 'style'; + } + } else if (/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(pathname)) { + // image + e = doc.createElement('img'); + e.src = pathStripped; + } else { + // javascript + e = doc.createElement('script'); + e.src = path; + e.async = async === undefined ? true : async; + } + + e.onload = e.onerror = e.onbeforeload = function (ev) { + var result = ev.type[0]; // treat empty stylesheets as failures to get around lack of onerror + // support in IE9-11 + + if (isLegacyIECss) { + try { + if (!e.sheet.cssText.length) result = 'e'; + } catch (x) { + // sheets objects created from load errors don't allow access to + // `cssText` (unless error is Code:18 SecurityError) + if (x.code != 18) result = 'e'; + } + } // handle retries in case of load failure + + + if (result == 'e') { + // increment counter + numTries += 1; // exit function and try again + + if (numTries < maxTries) { + return loadFile(path, callbackFn, args, numTries); + } + } else if (e.rel == 'preload' && e.as == 'style') { + // activate preloaded stylesheets + return e.rel = 'stylesheet'; // jshint ignore:line + } // execute callback + + + callbackFn(path, result, ev.defaultPrevented); + }; // add to document (unless callback returns `false`) + + + if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e); + } + /** + * Load multiple files. + * @param {string[]} paths - The file paths + * @param {Function} callbackFn - The callback function + */ + + + function loadFiles(paths, callbackFn, args) { + // listify paths + paths = paths.push ? paths : [paths]; + var numWaiting = paths.length, + x = numWaiting, + pathsNotFound = [], + fn, + i; // define callback function + + fn = function (path, result, defaultPrevented) { + // handle error + if (result == 'e') pathsNotFound.push(path); // handle beforeload event. If defaultPrevented then that means the load + // will be blocked (ex. Ghostery/ABP on Safari) + + if (result == 'b') { + if (defaultPrevented) pathsNotFound.push(path);else return; + } + + numWaiting--; + if (!numWaiting) callbackFn(pathsNotFound); + }; // load scripts + + + for (i = 0; i < x; i++) loadFile(paths[i], fn, args); + } + /** + * Initiate script load and register bundle. + * @param {(string|string[])} paths - The file paths + * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success + * callback or (3) object literal with success/error arguments, numRetries, + * etc. + * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object + * literal with success/error arguments, numRetries, etc. + */ + + + function loadjs(paths, arg1, arg2) { + var bundleId, args; // bundleId (if string) + + if (arg1 && arg1.trim) bundleId = arg1; // args (default is {}) + + args = (bundleId ? arg2 : arg1) || {}; // throw error if bundle is already defined + + if (bundleId) { + if (bundleId in bundleIdCache) { + throw "LoadJS"; + } else { + bundleIdCache[bundleId] = true; + } + } + + function loadFn(resolve, reject) { + loadFiles(paths, function (pathsNotFound) { + // execute callbacks + executeCallbacks(args, pathsNotFound); // resolve Promise + + if (resolve) { + executeCallbacks({ + success: resolve, + error: reject + }, pathsNotFound); + } // publish bundle load event + + + publish(bundleId, pathsNotFound); + }, args); + } + + if (args.returnPromise) return new Promise(loadFn);else loadFn(); + } + /** + * Execute callbacks when dependencies have been satisfied. + * @param {(string|string[])} deps - List of bundle ids + * @param {Object} args - success/error arguments + */ + + + loadjs.ready = function ready(deps, args) { + // subscribe to bundle load event + subscribe(deps, function (depsNotFound) { + // execute callbacks + executeCallbacks(args, depsNotFound); + }); + return loadjs; + }; + /** + * Manually satisfy bundle dependencies. + * @param {string} bundleId - The bundle id + */ + + + loadjs.done = function done(bundleId) { + publish(bundleId, []); + }; + /** + * Reset loadjs dependencies statuses + */ + + + loadjs.reset = function reset() { + bundleIdCache = {}; + bundleResultCache = {}; + bundleCallbackQueue = {}; + }; + /** + * Determine if bundle has already been defined + * @param String} bundleId - The bundle id + */ + + + loadjs.isDefined = function isDefined(bundleId) { + return bundleId in bundleIdCache; + }; // export + + + return loadjs; + }); + }); + + // ========================================================================== + function loadScript(url) { + return new Promise((resolve, reject) => { + loadjs_umd(url, { + success: resolve, + error: reject + }); + }); + } + + // ========================================================================== + + function parseId$1(url) { + if (is.empty(url)) { + return null; + } + + if (is.number(Number(url))) { + return url; + } + + const regex = /^.*(vimeo.com\/|video\/)(\d+).*/; + return url.match(regex) ? RegExp.$2 : url; + } // Try to extract a hash for private videos from the URL + + + function parseHash(url) { + /* This regex matches a hexadecimal hash if given in any of these forms: + * - [https://player.]vimeo.com/video/{id}/{hash}[?params] + * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms] + * - [https://player.]vimeo.com/video/{id}?[params]&h={hash} + * - video/{id}/{hash} + * If matched, the hash is available in the named group `hash` + */ + const regex = /^.*(?:vimeo.com\/|video\/)(?:\d+)(?:\?.*&*h=|\/)+(?<hash>[\d,a-f]+)/; + const found = url.match(regex); + return found ? found.groups.hash : null; + } // Set playback state and trigger change (only on actual change) + + + function assurePlaybackState$1(play) { + if (play && !this.embed.hasPlayed) { + this.embed.hasPlayed = true; + } + + if (this.media.paused === play) { + this.media.paused = !play; + triggerEvent.call(this, this.media, play ? 'play' : 'pause'); + } + } + + const vimeo = { + setup() { + const player = this; // Add embed class for responsive + + toggleClass(player.elements.wrapper, player.config.classNames.embed, true); // Set speed options from config + + player.options.speed = player.config.speed.options; // Set intial ratio + + setAspectRatio.call(player); // Load the SDK if not already + + if (!is.object(window.Vimeo)) { + loadScript(player.config.urls.vimeo.sdk).then(() => { + vimeo.ready.call(player); + }).catch(error => { + player.debug.warn('Vimeo SDK (player.js) failed to load', error); + }); + } else { + vimeo.ready.call(player); + } + }, + + // API Ready + ready() { + const player = this; + const config = player.config.vimeo; + const { + premium, + referrerPolicy, + ...frameParams + } = config; // Get the source URL or ID + + let source = player.media.getAttribute('src'); + let hash = ''; // Get from <div> if needed + + if (is.empty(source)) { + source = player.media.getAttribute(player.config.attributes.embed.id); // hash can also be set as attribute on the <div> + + hash = player.media.getAttribute(player.config.attributes.embed.hash); + } else { + hash = parseHash(source); + } + + const hashParam = hash ? { + h: hash + } : {}; // If the owner has a pro or premium account then we can hide controls etc + + if (premium) { + Object.assign(frameParams, { + controls: false, + sidedock: false + }); + } // Get Vimeo params for the iframe + + + const params = buildUrlParams({ + loop: player.config.loop.active, + autoplay: player.autoplay, + muted: player.muted, + gesture: 'media', + playsinline: !this.config.fullscreen.iosNative, + // hash has to be added to iframe-URL + ...hashParam, + ...frameParams + }); + const id = parseId$1(source); // Build an iframe + + const iframe = createElement('iframe'); + const src = format(player.config.urls.vimeo.iframe, id, params); + iframe.setAttribute('src', src); + iframe.setAttribute('allowfullscreen', ''); + iframe.setAttribute('allow', ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; ')); // Set the referrer policy if required + + if (!is.empty(referrerPolicy)) { + iframe.setAttribute('referrerPolicy', referrerPolicy); + } // Inject the package + + + if (premium || !config.customControls) { + iframe.setAttribute('data-poster', player.poster); + player.media = replaceElement(iframe, player.media); + } else { + const wrapper = createElement('div', { + class: player.config.classNames.embedContainer, + 'data-poster': player.poster + }); + wrapper.appendChild(iframe); + player.media = replaceElement(wrapper, player.media); + } // Get poster image + + + if (!config.customControls) { + fetch(format(player.config.urls.vimeo.api, src)).then(response => { + if (is.empty(response) || !response.thumbnail_url) { + return; + } // Set and show poster + + + ui.setPoster.call(player, response.thumbnail_url).catch(() => {}); + }); + } // Setup instance + // https://github.com/vimeo/player.js + + + player.embed = new window.Vimeo.Player(iframe, { + autopause: player.config.autopause, + muted: player.muted + }); + player.media.paused = true; + player.media.currentTime = 0; // Disable native text track rendering + + if (player.supported.ui) { + player.embed.disableTextTrack(); + } // Create a faux HTML5 API using the Vimeo API + + + player.media.play = () => { + assurePlaybackState$1.call(player, true); + return player.embed.play(); + }; + + player.media.pause = () => { + assurePlaybackState$1.call(player, false); + return player.embed.pause(); + }; + + player.media.stop = () => { + player.pause(); + player.currentTime = 0; + }; // Seeking + + + let { + currentTime + } = player.media; + Object.defineProperty(player.media, 'currentTime', { + get() { + return currentTime; + }, + + set(time) { + // Vimeo will automatically play on seek if the video hasn't been played before + // Get current paused state and volume etc + const { + embed, + media, + paused, + volume + } = player; + const restorePause = paused && !embed.hasPlayed; // Set seeking state and trigger event + + media.seeking = true; + triggerEvent.call(player, media, 'seeking'); // If paused, mute until seek is complete + + Promise.resolve(restorePause && embed.setVolume(0)) // Seek + .then(() => embed.setCurrentTime(time)) // Restore paused + .then(() => restorePause && embed.pause()) // Restore volume + .then(() => restorePause && embed.setVolume(volume)).catch(() => {// Do nothing + }); + } + + }); // Playback speed + + let speed = player.config.speed.selected; + Object.defineProperty(player.media, 'playbackRate', { + get() { + return speed; + }, + + set(input) { + player.embed.setPlaybackRate(input).then(() => { + speed = input; + triggerEvent.call(player, player.media, 'ratechange'); + }).catch(() => { + // Cannot set Playback Rate, Video is probably not on Pro account + player.options.speed = [1]; + }); + } + + }); // Volume + + let { + volume + } = player.config; + Object.defineProperty(player.media, 'volume', { + get() { + return volume; + }, + + set(input) { + player.embed.setVolume(input).then(() => { + volume = input; + triggerEvent.call(player, player.media, 'volumechange'); + }); + } + + }); // Muted + + let { + muted + } = player.config; + Object.defineProperty(player.media, 'muted', { + get() { + return muted; + }, + + set(input) { + const toggle = is.boolean(input) ? input : false; + player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => { + muted = toggle; + triggerEvent.call(player, player.media, 'volumechange'); + }); + } + + }); // Loop + + let { + loop + } = player.config; + Object.defineProperty(player.media, 'loop', { + get() { + return loop; + }, + + set(input) { + const toggle = is.boolean(input) ? input : player.config.loop.active; + player.embed.setLoop(toggle).then(() => { + loop = toggle; + }); + } + + }); // Source + + let currentSrc; + player.embed.getVideoUrl().then(value => { + currentSrc = value; + controls.setDownloadUrl.call(player); + }).catch(error => { + this.debug.warn(error); + }); + Object.defineProperty(player.media, 'currentSrc', { + get() { + return currentSrc; + } + + }); // Ended + + Object.defineProperty(player.media, 'ended', { + get() { + return player.currentTime === player.duration; + } + + }); // Set aspect ratio based on video size + + Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(dimensions => { + const [width, height] = dimensions; + player.embed.ratio = roundAspectRatio(width, height); + setAspectRatio.call(this); + }); // Set autopause + + player.embed.setAutopause(player.config.autopause).then(state => { + player.config.autopause = state; + }); // Get title + + player.embed.getVideoTitle().then(title => { + player.config.title = title; + ui.setTitle.call(this); + }); // Get current time + + player.embed.getCurrentTime().then(value => { + currentTime = value; + triggerEvent.call(player, player.media, 'timeupdate'); + }); // Get duration + + player.embed.getDuration().then(value => { + player.media.duration = value; + triggerEvent.call(player, player.media, 'durationchange'); + }); // Get captions + + player.embed.getTextTracks().then(tracks => { + player.media.textTracks = tracks; + captions.setup.call(player); + }); + player.embed.on('cuechange', ({ + cues = [] + }) => { + const strippedCues = cues.map(cue => stripHTML(cue.text)); + captions.updateCues.call(player, strippedCues); + }); + player.embed.on('loaded', () => { + // Assure state and events are updated on autoplay + player.embed.getPaused().then(paused => { + assurePlaybackState$1.call(player, !paused); + + if (!paused) { + triggerEvent.call(player, player.media, 'playing'); + } + }); + + if (is.element(player.embed.element) && player.supported.ui) { + const frame = player.embed.element; // Fix keyboard focus issues + // https://github.com/sampotts/plyr/issues/317 + + frame.setAttribute('tabindex', -1); + } + }); + player.embed.on('bufferstart', () => { + triggerEvent.call(player, player.media, 'waiting'); + }); + player.embed.on('bufferend', () => { + triggerEvent.call(player, player.media, 'playing'); + }); + player.embed.on('play', () => { + assurePlaybackState$1.call(player, true); + triggerEvent.call(player, player.media, 'playing'); + }); + player.embed.on('pause', () => { + assurePlaybackState$1.call(player, false); + }); + player.embed.on('timeupdate', data => { + player.media.seeking = false; + currentTime = data.seconds; + triggerEvent.call(player, player.media, 'timeupdate'); + }); + player.embed.on('progress', data => { + player.media.buffered = data.percent; + triggerEvent.call(player, player.media, 'progress'); // Check all loaded + + if (parseInt(data.percent, 10) === 1) { + triggerEvent.call(player, player.media, 'canplaythrough'); + } // Get duration as if we do it before load, it gives an incorrect value + // https://github.com/sampotts/plyr/issues/891 + + + player.embed.getDuration().then(value => { + if (value !== player.media.duration) { + player.media.duration = value; + triggerEvent.call(player, player.media, 'durationchange'); + } + }); + }); + player.embed.on('seeked', () => { + player.media.seeking = false; + triggerEvent.call(player, player.media, 'seeked'); + }); + player.embed.on('ended', () => { + player.media.paused = true; + triggerEvent.call(player, player.media, 'ended'); + }); + player.embed.on('error', detail => { + player.media.error = detail; + triggerEvent.call(player, player.media, 'error'); + }); // Rebuild UI + + if (config.customControls) { + setTimeout(() => ui.build.call(player), 0); + } + } + + }; + + // ========================================================================== + + function parseId(url) { + if (is.empty(url)) { + return null; + } + + const regex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/; + return url.match(regex) ? RegExp.$2 : url; + } // Set playback state and trigger change (only on actual change) + + + function assurePlaybackState(play) { + if (play && !this.embed.hasPlayed) { + this.embed.hasPlayed = true; + } + + if (this.media.paused === play) { + this.media.paused = !play; + triggerEvent.call(this, this.media, play ? 'play' : 'pause'); + } + } + + function getHost(config) { + if (config.noCookie) { + return 'https://www.youtube-nocookie.com'; + } + + if (window.location.protocol === 'http:') { + return 'http://www.youtube.com'; + } // Use YouTube's default + + + return undefined; + } + + const youtube = { + setup() { + // Add embed class for responsive + toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Setup API + + if (is.object(window.YT) && is.function(window.YT.Player)) { + youtube.ready.call(this); + } else { + // Reference current global callback + const callback = window.onYouTubeIframeAPIReady; // Set callback to process queue + + window.onYouTubeIframeAPIReady = () => { + // Call global callback if set + if (is.function(callback)) { + callback(); + } + + youtube.ready.call(this); + }; // Load the SDK + + + loadScript(this.config.urls.youtube.sdk).catch(error => { + this.debug.warn('YouTube API failed to load', error); + }); + } + }, + + // Get the media title + getTitle(videoId) { + const url = format(this.config.urls.youtube.api, videoId); + fetch(url).then(data => { + if (is.object(data)) { + const { + title, + height, + width + } = data; // Set title + + this.config.title = title; + ui.setTitle.call(this); // Set aspect ratio + + this.embed.ratio = roundAspectRatio(width, height); + } + + setAspectRatio.call(this); + }).catch(() => { + // Set aspect ratio + setAspectRatio.call(this); + }); + }, + + // API ready + ready() { + const player = this; + const config = player.config.youtube; // Ignore already setup (race condition) + + const currentId = player.media && player.media.getAttribute('id'); + + if (!is.empty(currentId) && currentId.startsWith('youtube-')) { + return; + } // Get the source URL or ID + + + let source = player.media.getAttribute('src'); // Get from <div> if needed + + if (is.empty(source)) { + source = player.media.getAttribute(this.config.attributes.embed.id); + } // Replace the <iframe> with a <div> due to YouTube API issues + + + const videoId = parseId(source); + const id = generateId(player.provider); // Replace media element + + const container = createElement('div', { + id, + 'data-poster': config.customControls ? player.poster : undefined + }); + player.media = replaceElement(container, player.media); // Only load the poster when using custom controls + + if (config.customControls) { + const posterSrc = s => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`; // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide) + + + loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded + .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3 + .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists + .then(image => ui.setPoster.call(player, image.src)).then(src => { + // If the image is padded, use background-size "cover" instead (like youtube does too with their posters) + if (!src.includes('maxres')) { + player.elements.poster.style.backgroundSize = 'cover'; + } + }).catch(() => {}); + } // Setup instance + // https://developers.google.com/youtube/iframe_api_reference + + + player.embed = new window.YT.Player(player.media, { + videoId, + host: getHost(config), + playerVars: extend({}, { + // Autoplay + autoplay: player.config.autoplay ? 1 : 0, + // iframe interface language + hl: player.config.hl, + // Only show controls if not fully supported or opted out + controls: player.supported.ui && config.customControls ? 0 : 1, + // Disable keyboard as we handle it + disablekb: 1, + // Allow iOS inline playback + playsinline: !player.config.fullscreen.iosNative ? 1 : 0, + // 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 + if (!player.media.error) { + const code = event.data; // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError + + const message = { + 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.', + 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.', + 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.', + 101: 'The owner of the requested video does not allow it to be played in embedded players.', + 150: 'The owner of the requested video does not allow it to be played in embedded players.' + }[code] || 'An unknown error occured'; + player.media.error = { + code, + message + }; + triggerEvent.call(player, player.media, 'error'); + } + }, + + onPlaybackRateChange(event) { + // Get the instance + const instance = event.target; // Get current speed + + player.media.playbackRate = instance.getPlaybackRate(); + triggerEvent.call(player, player.media, 'ratechange'); + }, + + onReady(event) { + // Bail if onReady has already been called. See issue #1108 + if (is.function(player.media.play)) { + return; + } // Get the instance + + + const instance = event.target; // Get the title + + youtube.getTitle.call(player, videoId); // Create a faux HTML5 API using the YouTube API + + player.media.play = () => { + assurePlaybackState.call(player, true); + instance.playVideo(); + }; + + player.media.pause = () => { + assurePlaybackState.call(player, false); + instance.pauseVideo(); + }; + + player.media.stop = () => { + instance.stopVideo(); + }; + + player.media.duration = instance.getDuration(); + player.media.paused = true; // Seeking + + player.media.currentTime = 0; + Object.defineProperty(player.media, 'currentTime', { + get() { + return Number(instance.getCurrentTime()); + }, + + set(time) { + // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet). + if (player.paused && !player.embed.hasPlayed) { + player.embed.mute(); + } // Set seeking state and trigger event + + + player.media.seeking = true; + triggerEvent.call(player, player.media, 'seeking'); // Seek after events sent + + instance.seekTo(time); + } + + }); // Playback speed + + Object.defineProperty(player.media, 'playbackRate', { + get() { + return instance.getPlaybackRate(); + }, + + set(input) { + instance.setPlaybackRate(input); + } + + }); // Volume + + let { + volume + } = player.config; + Object.defineProperty(player.media, 'volume', { + get() { + return volume; + }, + + set(input) { + volume = input; + instance.setVolume(volume * 100); + triggerEvent.call(player, player.media, 'volumechange'); + } + + }); // Muted + + let { + muted + } = player.config; + Object.defineProperty(player.media, 'muted', { + get() { + return muted; + }, + + set(input) { + const toggle = is.boolean(input) ? input : muted; + muted = toggle; + instance[toggle ? 'mute' : 'unMute'](); + instance.setVolume(volume * 100); + triggerEvent.call(player, player.media, 'volumechange'); + } + + }); // Source + + Object.defineProperty(player.media, 'currentSrc', { + get() { + return instance.getVideoUrl(); + } + + }); // Ended + + Object.defineProperty(player.media, 'ended', { + get() { + return player.currentTime === player.duration; + } + + }); // Get available speeds + + const speeds = instance.getAvailablePlaybackRates(); // Filter based on config + + player.options.speed = speeds.filter(s => player.config.speed.options.includes(s)); // Set the tabindex to avoid focus entering iframe + + if (player.supported.ui && config.customControls) { + player.media.setAttribute('tabindex', -1); + } + + triggerEvent.call(player, player.media, 'timeupdate'); + triggerEvent.call(player, player.media, 'durationchange'); // Reset timer + + clearInterval(player.timers.buffering); // Setup buffering + + player.timers.buffering = setInterval(() => { + // Get loaded % from YouTube + player.media.buffered = instance.getVideoLoadedFraction(); // Trigger progress only when we actually buffer something + + if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) { + triggerEvent.call(player, player.media, 'progress'); + } // Set last buffer point + + + player.media.lastBuffered = player.media.buffered; // Bail if we're at 100% + + if (player.media.buffered === 1) { + clearInterval(player.timers.buffering); // Trigger event + + triggerEvent.call(player, player.media, 'canplaythrough'); + } + }, 200); // Rebuild UI + + if (config.customControls) { + setTimeout(() => ui.build.call(player), 50); + } + }, + + onStateChange(event) { + // Get the instance + const instance = event.target; // Reset timer + + clearInterval(player.timers.playing); + const seeked = player.media.seeking && [1, 2].includes(event.data); + + if (seeked) { + // Unset seeking and fire seeked event + player.media.seeking = false; + triggerEvent.call(player, player.media, 'seeked'); + } // Handle events + // -1 Unstarted + // 0 Ended + // 1 Playing + // 2 Paused + // 3 Buffering + // 5 Video cued + + + switch (event.data) { + case -1: + // Update scrubber + triggerEvent.call(player, player.media, 'timeupdate'); // Get loaded % from YouTube + + player.media.buffered = instance.getVideoLoadedFraction(); + triggerEvent.call(player, player.media, 'progress'); + break; + + case 0: + assurePlaybackState.call(player, false); // YouTube doesn't support loop for a single video, so mimick it. + + if (player.media.loop) { + // YouTube needs a call to `stopVideo` before playing again + instance.stopVideo(); + instance.playVideo(); + } else { + triggerEvent.call(player, player.media, 'ended'); + } + + break; + + case 1: + // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet) + if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) { + player.media.pause(); + } else { + assurePlaybackState.call(player, true); + triggerEvent.call(player, player.media, 'playing'); // Poll to get playback progress + + player.timers.playing = setInterval(() => { + triggerEvent.call(player, player.media, 'timeupdate'); + }, 50); // Check duration again due to YouTube bug + // https://github.com/sampotts/plyr/issues/374 + // https://code.google.com/p/gdata-issues/issues/detail?id=8690 + + if (player.media.duration !== instance.getDuration()) { + player.media.duration = instance.getDuration(); + triggerEvent.call(player, player.media, 'durationchange'); + } + } + + break; + + case 2: + // Restore audio (YouTube starts playing on seek if the video hasn't been played yet) + if (!player.muted) { + player.embed.unMute(); + } + + assurePlaybackState.call(player, false); + break; + + case 3: + // Trigger waiting event to add loading classes to container as the video buffers. + triggerEvent.call(player, player.media, 'waiting'); + break; + } + + triggerEvent.call(player, player.elements.container, 'statechange', false, { + code: event.data + }); + } + + } + }); + } + + }; + + // ========================================================================== + const media = { + // Setup media + setup() { + // If there's no media, bail + if (!this.media) { + this.debug.warn('No media element found!'); + return; + } // Add type class + + + toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true); // Add provider class + + toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true); // Add video class for embeds + // This will require changes if audio embeds are added + + if (this.isEmbed) { + toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true); + } // Inject the player wrapper + + + if (this.isVideo) { + // Create the wrapper div + this.elements.wrapper = createElement('div', { + class: this.config.classNames.video + }); // Wrap the video in a container + + wrap(this.media, this.elements.wrapper); // Poster image container + + this.elements.poster = createElement('div', { + class: this.config.classNames.poster + }); + this.elements.wrapper.appendChild(this.elements.poster); + } + + if (this.isHTML5) { + html5.setup.call(this); + } else if (this.isYouTube) { + youtube.setup.call(this); + } else if (this.isVimeo) { + vimeo.setup.call(this); + } + } + + }; + + const destroy = instance => { + // Destroy our adsManager + if (instance.manager) { + instance.manager.destroy(); + } // Destroy our adsManager + + + if (instance.elements.displayContainer) { + instance.elements.displayContainer.destroy(); + } + + instance.elements.container.remove(); + }; + + class Ads { + /** + * Ads constructor. + * @param {Object} player + * @return {Ads} + */ + constructor(player) { + _defineProperty$1(this, "load", () => { + if (!this.enabled) { + return; + } // Check if the Google IMA3 SDK is loaded or load it ourselves + + + if (!is.object(window.google) || !is.object(window.google.ima)) { + loadScript(this.player.config.urls.googleIMA.sdk).then(() => { + this.ready(); + }).catch(() => { + // Script failed to load or is blocked + this.trigger('error', new Error('Google IMA SDK failed to load')); + }); + } else { + this.ready(); + } + }); + + _defineProperty$1(this, "ready", () => { + // Double check we're enabled + if (!this.enabled) { + destroy(this); + } // Start ticking our safety timer. If the whole advertisement + // thing doesn't resolve within our set time; we bail + + + this.startSafetyTimer(12000, 'ready()'); // Clear the safety timer + + this.managerPromise.then(() => { + this.clearSafetyTimer('onAdsManagerLoaded()'); + }); // Set listeners on the Plyr instance + + this.listeners(); // Setup the IMA SDK + + this.setupIMA(); + }); + + _defineProperty$1(this, "setupIMA", () => { + // Create the container for our advertisements + this.elements.container = createElement('div', { + class: this.player.config.classNames.ads + }); + this.player.elements.container.appendChild(this.elements.container); // So we can run VPAID2 + + google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED); // Set language + + google.ima.settings.setLocale(this.player.config.ads.language); // 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); // Create ads loader + + this.loader = new google.ima.AdsLoader(this.elements.displayContainer); // Listen and respond to ads loaded and error events + + this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false); + this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false); // Request video ads to be pre-loaded + + this.requestAds(); + }); + + _defineProperty$1(this, "requestAds", () => { + const { + container + } = this.player.elements; + + try { + // Request video ads + const request = new google.ima.AdsRequest(); + request.adTagUrl = this.tagUrl; // Specify the linear and nonlinear slot sizes. This helps the SDK + // to select the correct creative if multiple are returned + + request.linearAdSlotWidth = container.offsetWidth; + request.linearAdSlotHeight = container.offsetHeight; + request.nonLinearAdSlotWidth = container.offsetWidth; + request.nonLinearAdSlotHeight = container.offsetHeight; // We only overlay ads as we only support video. + + request.forceNonLinearFullSlot = false; // Mute based on current state + + request.setAdWillPlayMuted(!this.player.muted); + this.loader.requestAds(request); + } catch (error) { + this.onAdError(error); + } + }); + + _defineProperty$1(this, "pollCountdown", (start = false) => { + if (!start) { + clearInterval(this.countdownTimer); + this.elements.container.removeAttribute('data-badge-text'); + return; + } + + const update = () => { + const time = formatTime(Math.max(this.manager.getRemainingTime(), 0)); + const label = `${i18n.get('advertisement', this.player.config)} - ${time}`; + this.elements.container.setAttribute('data-badge-text', label); + }; + + this.countdownTimer = setInterval(update, 100); + }); + + _defineProperty$1(this, "onAdsManagerLoaded", event => { + // Load could occur after a source change (race condition) + if (!this.enabled) { + return; + } // Get the ads manager + + + const settings = new google.ima.AdsRenderingSettings(); // Tell the SDK to save and restore content video state on our behalf + + settings.restoreCustomPlaybackStateOnAdBreakComplete = true; + settings.enablePreloading = true; // The SDK is polling currentTime on the contentPlayback. And needs a duration + // so it can determine when to start the mid- and post-roll + + this.manager = event.getAdsManager(this.player, settings); // Get the cue points for any mid-rolls by filtering out the pre- and post-roll + + this.cuePoints = this.manager.getCuePoints(); // Add listeners to the required events + // Advertisement error events + + this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error)); // Advertisement regular events + + Object.keys(google.ima.AdEvent.Type).forEach(type => { + this.manager.addEventListener(google.ima.AdEvent.Type[type], e => this.onAdEvent(e)); + }); // Resolve our adsManager + + this.trigger('loaded'); + }); + + _defineProperty$1(this, "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); + } + } + }); + } + }); + + _defineProperty$1(this, "onAdEvent", event => { + const { + container + } = this.player.elements; // 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 => { + triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`); + }; // Bubble the event + + + dispatchEvent(event.type); + + switch (event.type) { + case google.ima.AdEvent.Type.LOADED: + // This is the first event sent for an ad - it is possible to determine whether the + // ad is a video ad or an overlay + this.trigger('loaded'); // Start countdown + + this.pollCountdown(true); + + if (!ad.isLinear()) { + // Position AdDisplayContainer correctly for overlay + ad.width = container.offsetWidth; + ad.height = container.offsetHeight; + } // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex()); + // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset()); + + + break; + + case google.ima.AdEvent.Type.STARTED: + // Set volume to match player + this.manager.setVolume(this.player.volume); + break; + + case google.ima.AdEvent.Type.ALL_ADS_COMPLETED: + // All ads for the current videos are done. We can now request new advertisements + // in case the video is re-played + // TODO: Example for what happens when a next video in a playlist would be loaded. + // So here we load a new video when all ads are done. + // Then we load new ads within a new adsManager. When the video + // Is started - after - the ads are loaded, then we get ads. + // You can also easily test cancelling and reloading by running + // player.ads.cancel() and player.ads.play from the console I guess. + // this.player.source = { + // type: 'video', + // title: 'View From A Blue Moon', + // sources: [{ + // src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type: + // 'video/mp4', }], poster: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks: + // [ { kind: 'captions', label: 'English', srclang: 'en', src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt', + // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ], + // }; + // TODO: So there is still this thing where a video should only be allowed to start + // playing when the IMA SDK is ready or has failed + if (this.player.ended) { + this.loadAds(); + } else { + // The SDK won't allow new ads to be called without receiving a contentComplete() + this.loader.contentComplete(); + } + + break; + + case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED: + // This event indicates the ad has started - the video player can adjust the UI, + // for example display a pause button and remaining time. Fired when content should + // be paused. This usually happens right before an ad is about to cover the content + this.pauseContent(); + break; + + case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED: + // This event indicates the ad has finished - the video player can perform + // appropriate UI actions, such as removing the timer for remaining time detection. + // Fired when content should be resumed. This usually happens when an ad finishes + // or collapses + this.pollCountdown(); + this.resumeContent(); + break; + + case google.ima.AdEvent.Type.LOG: + if (adData.adError) { + this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`); + } + + break; + } + }); + + _defineProperty$1(this, "onAdError", event => { + this.cancel(); + this.player.debug.warn('Ads error', event); + }); + + _defineProperty$1(this, "listeners", () => { + const { + container + } = this.player.elements; + let time; + this.player.on('canplay', () => { + this.addCuePoints(); + }); + this.player.on('ended', () => { + this.loader.contentComplete(); + }); + this.player.on('timeupdate', () => { + time = this.player.currentTime; + }); + this.player.on('seeked', () => { + const seekedTime = this.player.currentTime; + + if (is.empty(this.cuePoints)) { + return; + } + + this.cuePoints.forEach((cuePoint, index) => { + if (time < cuePoint && cuePoint < seekedTime) { + this.manager.discardAdBreak(); + this.cuePoints.splice(index, 1); + } + }); + }); // Listen to the resizing of the window. And resize ad accordingly + // TODO: eventually implement ResizeObserver + + window.addEventListener('resize', () => { + if (this.manager) { + this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); + } + }); + }); + + _defineProperty$1(this, "play", () => { + const { + container + } = this.player.elements; + + if (!this.managerPromise) { + this.resumeContent(); + } // Play the requested advertisement whenever the adsManager is ready + + + this.managerPromise.then(() => { + // Set volume to match player + this.manager.setVolume(this.player.volume); // Initialize the container. Must be done via a user action on mobile devices + + this.elements.displayContainer.initialize(); + + try { + if (!this.initialized) { + // Initialize the ads manager. Ad rules playlist will start at this time + this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will + // start at this time; the call will be ignored for ad rules + + this.manager.start(); + } + + this.initialized = true; + } catch (adError) { + // An error may be thrown if there was a problem with the + // VAST response + this.onAdError(adError); + } + }).catch(() => {}); + }); + + _defineProperty$1(this, "resumeContent", () => { + // Hide the advertisement container + this.elements.container.style.zIndex = ''; // Ad is stopped + + this.playing = false; // Play video + + silencePromise(this.player.media.play()); + }); + + _defineProperty$1(this, "pauseContent", () => { + // Show the advertisement container + this.elements.container.style.zIndex = 3; // Ad is playing + + this.playing = true; // Pause our video. + + this.player.media.pause(); + }); + + _defineProperty$1(this, "cancel", () => { + // Pause our video + if (this.initialized) { + this.resumeContent(); + } // Tell our instance that we're done for now + + + this.trigger('error'); // Re-create our adsManager + + this.loadAds(); + }); + + _defineProperty$1(this, "loadAds", () => { + // Tell our adsManager to go bye bye + this.managerPromise.then(() => { + // Destroy our adsManager + if (this.manager) { + this.manager.destroy(); + } // Re-set our adsManager promises + + + this.managerPromise = new Promise(resolve => { + this.on('loaded', resolve); + this.player.debug.log(this.manager); + }); // Now that the manager has been destroyed set it to also be un-initialized + + this.initialized = false; // Now request some new advertisements + + this.requestAds(); + }).catch(() => {}); + }); + + _defineProperty$1(this, "trigger", (event, ...args) => { + const handlers = this.events[event]; + + if (is.array(handlers)) { + handlers.forEach(handler => { + if (is.function(handler)) { + handler.apply(this, args); + } + }); + } + }); + + _defineProperty$1(this, "on", (event, callback) => { + if (!is.array(this.events[event])) { + this.events[event] = []; + } + + this.events[event].push(callback); + return this; + }); + + _defineProperty$1(this, "startSafetyTimer", (time, from) => { + this.player.debug.log(`Safety timer invoked from: ${from}`); + this.safetyTimer = setTimeout(() => { + this.cancel(); + this.clearSafetyTimer('startSafetyTimer()'); + }, time); + }); + + _defineProperty$1(this, "clearSafetyTimer", from => { + if (!is.nullOrUndefined(this.safetyTimer)) { + this.player.debug.log(`Safety timer cleared from: ${from}`); + clearTimeout(this.safetyTimer); + this.safetyTimer = null; + } + }); + + this.player = player; + this.config = player.config.ads; + this.playing = false; + this.initialized = false; + this.elements = { + container: null, + displayContainer: null + }; + this.manager = null; + this.loader = null; + this.cuePoints = null; + this.events = {}; + this.safetyTimer = null; + this.countdownTimer = null; // Setup a promise to resolve when the IMA manager is ready + + this.managerPromise = new Promise((resolve, reject) => { + // The ad is loaded and ready + this.on('loaded', resolve); // Ads failed + + this.on('error', reject); + }); + this.load(); + } + + get enabled() { + const { + config + } = this; + return this.player.isHTML5 && this.player.isVideo && config.enabled && (!is.empty(config.publisherId) || is.url(config.tagUrl)); + } + /** + * Load the IMA SDK + */ + + + // 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', + AV_URL: window.location.hostname, + cb: Date.now(), + AV_WIDTH: 640, + AV_HEIGHT: 480, + AV_CDIM2: config.publisherId + }; + const base = 'https://go.aniview.com/api/adserver6/vast/'; + return `${base}?${buildUrlParams(params)}`; + } + /** + * In order for the SDK to display ads for our video, we need to tell it where to put them, + * so here we define our ad container. This div is set up to render on top of the video player. + * Using the code below, we tell the SDK to render ads within that div. We also provide a + * handle to the content video player - the SDK will poll the current time of our player to + * properly place mid-rolls. After we create the ad display container, we initialize it. On + * mobile devices, this initialization is done as the result of a user action. + */ + + + } + + 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] || 0) * 60 * 60 + Number(matchTimes[2]) * 60 + Number(matchTimes[3]) + Number(`0.${matchTimes[4]}`); + result.endTime = Number(matchTimes[6] || 0) * 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 + */ + + + const fitRatio = (ratio, outer) => { + const targetRatio = outer.width / outer.height; + const result = {}; + + if (ratio > targetRatio) { + result.width = outer.width; + result.height = 1 / ratio * outer.width; + } else { + result.height = outer.height; + result.width = ratio * outer.height; + } + + return result; + }; + + class PreviewThumbnails { + /** + * PreviewThumbnails constructor. + * @param {Plyr} player + * @return {PreviewThumbnails} + */ + constructor(player) { + _defineProperty$1(this, "load", () => { + // Toggle the regular seek tooltip + if (this.player.elements.display.seekTooltip) { + this.player.elements.display.seekTooltip.hidden = this.enabled; + } + + if (!this.enabled) { + return; + } + + this.getThumbnails().then(() => { + if (!this.enabled) { + return; + } // Render DOM elements + + + this.render(); // Check to see if thumb container size was specified manually in CSS + + this.determineContainerAutoSizing(); + this.loaded = true; + }); + }); + + _defineProperty$1(this, "getThumbnails", () => { + return new Promise(resolve => { + const { + src + } = this.player.config.previewThumbnails; + + if (is.empty(src)) { + throw new Error('Missing previewThumbnails.src config attribute'); + } // Resolve promise + + + const sortAndResolve = () => { + // 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(); + }; // Via callback() + + + if (is.function(src)) { + src(thumbnails => { + this.thumbnails = thumbnails; + sortAndResolve(); + }); + } // VTT urls + else { + // 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)); // Resolve + + Promise.all(promises).then(sortAndResolve); + } + }); + }); + + _defineProperty$1(this, "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 the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file + + if (!thumbnail.frames[0].text.startsWith('/') && !thumbnail.frames[0].text.startsWith('http://') && !thumbnail.frames[0].text.startsWith('https://')) { + 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; + }); + }); + }); + + _defineProperty$1(this, "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(); + }); + + _defineProperty$1(this, "endMove", () => { + this.toggleThumbContainer(false, true); + }); + + _defineProperty$1(this, "startScrubbing", event => { + // Only act on left mouse button (0), or touch device (event.button does not exist or is false) + if (is.nullOrUndefined(event.button) || 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(); + } + } + }); + + _defineProperty$1(this, "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); + } + }); + } + }); + + _defineProperty$1(this, "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; + }); + }); + + _defineProperty$1(this, "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 + + if (is.element(this.player.elements.progress)) { + 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); + }); + + _defineProperty$1(this, "destroy", () => { + if (this.elements.thumb.container) { + this.elements.thumb.container.remove(); + } + + if (this.elements.scrubbing.container) { + this.elements.scrubbing.container.remove(); + } + }); + + _defineProperty$1(this, "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); + } + }); + + _defineProperty$1(this, "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); + } + }); + + _defineProperty$1(this, "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)); + }); + + _defineProperty$1(this, "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 + // eslint-disable-next-line no-param-reassign + 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); + } + }); + }); + + _defineProperty$1(this, "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); + }); + }); + + _defineProperty$1(this, "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); + } + } + }); + + _defineProperty$1(this, "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; + } + }); + + _defineProperty$1(this, "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; + } + }); + + _defineProperty$1(this, "determineContainerAutoSizing", () => { + if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) { + // This will prevent auto sizing in this.setThumbContainerSizeAndPos() + this.sizeSpecifiedInCSS = true; + } + }); + + _defineProperty$1(this, "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`; + } else if (this.elements.thumb.imageContainer.clientHeight > 20 && this.elements.thumb.imageContainer.clientWidth < 20) { + const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio); + this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`; + } else if (this.elements.thumb.imageContainer.clientHeight < 20 && this.elements.thumb.imageContainer.clientWidth > 20) { + const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio); + this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`; + } + + this.setThumbContainerPos(); + }); + + _defineProperty$1(this, "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`; + }); + + _defineProperty$1(this, "setScrubbingContainerSize", () => { + const { + width, + height + } = fitRatio(this.thumbAspectRatio, { + width: this.player.media.clientWidth, + height: this.player.media.clientHeight + }); + this.elements.scrubbing.container.style.width = `${width}px`; + this.elements.scrubbing.container.style.height = `${height}px`; + }); + + _defineProperty$1(this, "setImageSizeAndOffset", (previewImage, frame) => { + if (!this.usingSprites) { + return; + } // Find difference between height and preview container height + + + const multiplier = this.thumbContainerHeight / frame.h; // eslint-disable-next-line no-param-reassign + + previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.left = `-${frame.x * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.top = `-${frame.y * multiplier}px`; + }); + + 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; + } + + 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) { + const { + height + } = fitRatio(this.thumbAspectRatio, { + width: this.player.media.clientWidth, + height: this.player.media.clientHeight + }); + return height; + } // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset) + + + if (this.sizeSpecifiedInCSS) { + return this.elements.thumb.imageContainer.clientHeight; + } + + 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; + } + } + + } + + // ========================================================================== + const source = { + // Add elements to HTML5 media (source, tracks, etc) + insertElements(type, attributes) { + if (is.string(attributes)) { + insertElement(type, this.media, { + src: attributes + }); + } else if (is.array(attributes)) { + attributes.forEach(attribute => { + insertElement(type, this.media, attribute); + }); + } + }, + + // Update source + // Sources are not checked for support so be careful + change(input) { + if (!getDeep(input, 'sources.length')) { + this.debug.warn('Invalid source format'); + return; + } // Cancel current network requests + + + html5.cancelRequests.call(this); // Destroy instance and re-setup + + this.destroy.call(this, () => { + // Reset quality options + this.options.quality = []; // Remove elements + + removeElement(this.media); + this.media = null; // Reset class name + + if (is.element(this.elements.container)) { + this.elements.container.removeAttribute('class'); + } // Set the type and provider + + + const { + sources, + type + } = input; + const [{ + provider = providers.html5, + src + }] = sources; + const tagName = provider === 'html5' ? type : 'div'; + const attributes = provider === 'html5' ? {} : { + src + }; + Object.assign(this, { + provider, + type, + // Check for support + supported: support.check(type, provider, this.config.playsinline), + // Create new element + media: createElement(tagName, attributes) + }); // Inject the new element + + this.elements.container.appendChild(this.media); // Autoplay the new source? + + if (is.boolean(input.autoplay)) { + this.config.autoplay = input.autoplay; + } // Set attributes for audio and video + + + if (this.isHTML5) { + if (this.config.crossorigin) { + this.media.setAttribute('crossorigin', ''); + } + + if (this.config.autoplay) { + this.media.setAttribute('autoplay', ''); + } + + if (!is.empty(input.poster)) { + this.poster = input.poster; + } + + if (this.config.loop.active) { + this.media.setAttribute('loop', ''); + } + + if (this.config.muted) { + this.media.setAttribute('muted', ''); + } + + if (this.config.playsinline) { + this.media.setAttribute('playsinline', ''); + } + } // Restore class hook + + + ui.addStyleHook.call(this); // Set new sources for html5 + + if (this.isHTML5) { + source.insertElements.call(this, 'source', sources); + } // Set video title + + + this.config.title = input.title; // Set up from scratch + + media.setup.call(this); // HTML5 stuff + + if (this.isHTML5) { + // Setup captions + if (Object.keys(input).includes('tracks')) { + source.insertElements.call(this, 'track', input.tracks); + } + } // If HTML5 or embed but not fully supported, setupInterface and call ready now + + + if (this.isHTML5 || this.isEmbed && !this.supported.ui) { + // Setup interface + ui.build.call(this); + } // Load HTML5 sources + + + if (this.isHTML5) { + this.media.load(); + } // Update previewThumbnails config & reload plugin + + + if (!is.empty(input.previewThumbnails)) { + Object.assign(this.config.previewThumbnails, input.previewThumbnails); // Cleanup previewThumbnails plugin if it was loaded + + if (this.previewThumbnails && this.previewThumbnails.loaded) { + this.previewThumbnails.destroy(); + this.previewThumbnails = null; + } // Create new instance if it is still enabled + + + if (this.config.previewThumbnails.enabled) { + this.previewThumbnails = new PreviewThumbnails(this); + } + } // Update the fullscreen support + + + this.fullscreen.update(); + }, true); + } + + }; + + /** + * Returns a number whose value is limited to the given range. + * + * Example: limit the output of this computation to between 0 and 255 + * (x * 255).clamp(0, 255) + * + * @param {Number} input + * @param {Number} min The lower boundary of the output range + * @param {Number} max The upper boundary of the output range + * @returns A number in the range [min, max] + * @type Number + */ + function clamp(input = 0, min = 0, max = 255) { + return Math.min(Math.max(input, min), max); + } + + // TODO: Use a WeakMap for private globals + // const globals = new WeakMap(); + // Plyr instance + + class Plyr { + constructor(target, options) { + _defineProperty$1(this, "play", () => { + if (!is.function(this.media.play)) { + return null; + } // Intecept play with ads + + + if (this.ads && this.ads.enabled) { + this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play())); + } // Return the promise (for HTML5) + + + return this.media.play(); + }); + + _defineProperty$1(this, "pause", () => { + if (!this.playing || !is.function(this.media.pause)) { + return null; + } + + return this.media.pause(); + }); + + _defineProperty$1(this, "togglePlay", input => { + // Toggle based on current state if nothing passed + const toggle = is.boolean(input) ? input : !this.playing; + + if (toggle) { + return this.play(); + } + + return this.pause(); + }); + + _defineProperty$1(this, "stop", () => { + if (this.isHTML5) { + this.pause(); + this.restart(); + } else if (is.function(this.media.stop)) { + this.media.stop(); + } + }); + + _defineProperty$1(this, "restart", () => { + this.currentTime = 0; + }); + + _defineProperty$1(this, "rewind", seekTime => { + this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime; + }); + + _defineProperty$1(this, "forward", seekTime => { + this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime; + }); + + _defineProperty$1(this, "increaseVolume", step => { + const volume = this.media.muted ? 0 : this.volume; + this.volume = volume + (is.number(step) ? step : 0); + }); + + _defineProperty$1(this, "decreaseVolume", step => { + this.increaseVolume(-step); + }); + + _defineProperty$1(this, "airplay", () => { + // Show dialog if supported + if (support.airplay) { + this.media.webkitShowPlaybackTargetPicker(); + } + }); + + _defineProperty$1(this, "toggleControls", toggle => { + // Don't toggle if missing UI support or if it's audio + if (this.supported.ui && !this.isAudio) { + // Get state before change + const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls); // Negate the argument if not undefined since adding the class to hides the controls + + const force = typeof toggle === 'undefined' ? undefined : !toggle; // Apply and get updated state + + const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force); // Close menu + + if (hiding && is.array(this.config.controls) && this.config.controls.includes('settings') && !is.empty(this.config.settings)) { + controls.toggleMenu.call(this, false); + } // Trigger event on change + + + if (hiding !== isHidden) { + const eventName = hiding ? 'controlshidden' : 'controlsshown'; + triggerEvent.call(this, this.media, eventName); + } + + return !hiding; + } + + return false; + }); + + _defineProperty$1(this, "on", (event, callback) => { + on.call(this, this.elements.container, event, callback); + }); + + _defineProperty$1(this, "once", (event, callback) => { + once.call(this, this.elements.container, event, callback); + }); + + _defineProperty$1(this, "off", (event, callback) => { + off(this.elements.container, event, callback); + }); + + _defineProperty$1(this, "destroy", (callback, soft = false) => { + if (!this.ready) { + return; + } + + const done = () => { + // Reset overflow (incase destroyed while in fullscreen) + document.body.style.overflow = ''; // GC for embed + + this.embed = null; // If it's a soft destroy, make minimal changes + + if (soft) { + if (Object.keys(this.elements).length) { + // Remove elements + removeElement(this.elements.buttons.play); + removeElement(this.elements.captions); + removeElement(this.elements.controls); + removeElement(this.elements.wrapper); // Clear for GC + + this.elements.buttons.play = null; + this.elements.captions = null; + this.elements.controls = null; + this.elements.wrapper = null; + } // Callback + + + if (is.function(callback)) { + callback(); + } + } else { + // Unbind listeners + unbindListeners.call(this); // Cancel current network requests + + html5.cancelRequests.call(this); // Replace the container with the original element provided + + replaceElement(this.elements.original, this.elements.container); // Event + + triggerEvent.call(this, this.elements.original, 'destroyed', true); // Callback + + if (is.function(callback)) { + callback.call(this.elements.original); + } // Reset state + + + this.ready = false; // Clear for garbage collection + + setTimeout(() => { + this.elements = null; + this.media = null; + }, 200); + } + }; // Stop playback + + + this.stop(); // Clear timeouts + + clearTimeout(this.timers.loading); + clearTimeout(this.timers.controls); + clearTimeout(this.timers.resized); // Provider specific stuff + + if (this.isHTML5) { + // Restore native video controls + ui.toggleNativeControls.call(this, true); // Clean up + + done(); + } else if (this.isYouTube) { + // Clear timers + clearInterval(this.timers.buffering); + clearInterval(this.timers.playing); // Destroy YouTube API + + if (this.embed !== null && is.function(this.embed.destroy)) { + this.embed.destroy(); + } // Clean up + + + done(); + } else if (this.isVimeo) { + // Destroy Vimeo API + // then clean up (wait, to prevent postmessage errors) + if (this.embed !== null) { + this.embed.unload().then(done); + } // Vimeo does not always return + + + setTimeout(done, 200); + } + }); + + _defineProperty$1(this, "supports", type => support.mime.call(this, type)); + + this.timers = {}; // State + + this.ready = false; + this.loading = false; + this.failed = false; // Touch device + + this.touch = support.touch; // Set the media element + + this.media = target; // String selector passed + + if (is.string(this.media)) { + this.media = document.querySelectorAll(this.media); + } // jQuery, NodeList or Array passed, use first element + + + if (window.jQuery && this.media instanceof jQuery || is.nodeList(this.media) || is.array(this.media)) { + // eslint-disable-next-line + this.media = this.media[0]; + } // Set config + + + this.config = extend({}, defaults, Plyr.defaults, options || {}, (() => { + try { + return JSON.parse(this.media.getAttribute('data-plyr-config')); + } catch (_) { + return {}; + } + })()); // Elements cache + + this.elements = { + container: null, + fullscreen: null, + captions: null, + buttons: {}, + display: {}, + progress: {}, + inputs: {}, + settings: { + popup: null, + menu: null, + panels: {}, + buttons: {} + } + }; // Captions + + this.captions = { + active: null, + currentTrack: -1, + meta: new WeakMap() + }; // Fullscreen + + this.fullscreen = { + active: false + }; // Options + + this.options = { + speed: [], + quality: [] + }; // Debugging + // TODO: move to globals + + this.debug = new Console(this.config.debug); // Log config options and support + + this.debug.log('Config', this.config); + this.debug.log('Support', support); // We need an element to setup + + if (is.nullOrUndefined(this.media) || !is.element(this.media)) { + this.debug.error('Setup failed: no suitable element passed'); + return; + } // Bail if the element is initialized + + + if (this.media.plyr) { + this.debug.warn('Target already setup'); + return; + } // Bail if not enabled + + + if (!this.config.enabled) { + this.debug.error('Setup failed: disabled by config'); + return; + } // Bail if disabled or no basic support + // You may want to disable certain UAs etc + + + if (!support.check().api) { + this.debug.error('Setup failed: no support'); + return; + } // Cache original element state for .destroy() + + + const clone = this.media.cloneNode(true); + clone.autoplay = false; + this.elements.original = clone; // Set media type based on tag or data attribute + // Supported: video, audio, vimeo, youtube + + const _type = this.media.tagName.toLowerCase(); // Embed properties + + + let iframe = null; + let url = null; // Different setup based on type + + switch (_type) { + case 'div': + // Find the frame + iframe = this.media.querySelector('iframe'); // <iframe> type + + if (is.element(iframe)) { + // Detect provider + url = parseUrl(iframe.getAttribute('src')); + this.provider = getProviderByUrl(url.toString()); // Rework elements + + this.elements.container = this.media; + this.media = iframe; // Reset classname + + this.elements.container.className = ''; // Get attributes from URL and set config + + if (url.search.length) { + const truthy = ['1', 'true']; + + if (truthy.includes(url.searchParams.get('autoplay'))) { + this.config.autoplay = true; + } + + if (truthy.includes(url.searchParams.get('loop'))) { + this.config.loop.active = true; + } // TODO: replace fullscreen.iosNative with this playsinline config option + // YouTube requires the playsinline in the URL + + + if (this.isYouTube) { + this.config.playsinline = truthy.includes(url.searchParams.get('playsinline')); + this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language? + } else { + this.config.playsinline = true; + } + } + } else { + // <div> with attributes + this.provider = this.media.getAttribute(this.config.attributes.embed.provider); // Remove attribute + + this.media.removeAttribute(this.config.attributes.embed.provider); + } // Unsupported or missing provider + + + if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) { + this.debug.error('Setup failed: Invalid provider'); + return; + } // Audio will come later for external providers + + + this.type = types.video; + break; + + case 'video': + case 'audio': + this.type = _type; + this.provider = providers.html5; // Get config from attributes + + if (this.media.hasAttribute('crossorigin')) { + this.config.crossorigin = true; + } + + if (this.media.hasAttribute('autoplay')) { + this.config.autoplay = true; + } + + if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) { + this.config.playsinline = true; + } + + if (this.media.hasAttribute('muted')) { + this.config.muted = true; + } + + if (this.media.hasAttribute('loop')) { + this.config.loop.active = true; + } + + break; + + default: + this.debug.error('Setup failed: unsupported type'); + return; + } // Check for support again but with type + + + this.supported = support.check(this.type, this.provider, this.config.playsinline); // If no support for even API, bail + + if (!this.supported.api) { + this.debug.error('Setup failed: no support'); + return; + } + + this.eventListeners = []; // Create listeners + + this.listeners = new Listeners(this); // Setup local storage for user settings + + this.storage = new Storage(this); // Store reference + + this.media.plyr = this; // Wrap media + + if (!is.element(this.elements.container)) { + this.elements.container = createElement('div', { + tabindex: 0 + }); + wrap(this.media, this.elements.container); + } // Migrate custom properties from media to container (so they work 😉) + + + ui.migrateStyles.call(this); // Add style hook + + ui.addStyleHook.call(this); // Setup media + + media.setup.call(this); // Listen for events if debugging + + if (this.config.debug) { + on.call(this, this.elements.container, this.config.events.join(' '), event => { + this.debug.log(`event: ${event.type}`); + }); + } // Setup fullscreen + + + this.fullscreen = new Fullscreen(this); // Setup interface + // If embed but not fully supported, build interface now to avoid flash of controls + + if (this.isHTML5 || this.isEmbed && !this.supported.ui) { + ui.build.call(this); + } // Container listeners + + + this.listeners.container(); // Global listeners + + this.listeners.global(); // Setup ads if provided + + if (this.config.ads.enabled) { + this.ads = new Ads(this); + } // Autoplay if required + + + if (this.isHTML5 && this.config.autoplay) { + this.once('canplay', () => silencePromise(this.play())); + } // 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); + } + } // --------------------------------------- + // API + // --------------------------------------- + + /** + * Types and provider helpers + */ + + + get isHTML5() { + return this.provider === providers.html5; + } + + get isEmbed() { + return this.isYouTube || this.isVimeo; + } + + get isYouTube() { + return this.provider === providers.youtube; + } + + get isVimeo() { + return this.provider === providers.vimeo; + } + + get isVideo() { + return this.type === types.video; + } + + get isAudio() { + return this.type === types.audio; + } + /** + * Play the media, or play the advertisement (if they are not blocked) + */ + + + /** + * Get playing state + */ + get playing() { + return Boolean(this.ready && !this.paused && !this.ended); + } + /** + * Get paused state + */ + + + get paused() { + return Boolean(this.media.paused); + } + /** + * Get stopped state + */ + + + get stopped() { + return Boolean(this.paused && this.currentTime === 0); + } + /** + * Get ended state + */ + + + get ended() { + return Boolean(this.media.ended); + } + /** + * Toggle playback based on current status + * @param {Boolean} input + */ + + + /** + * Seek to a time + * @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 + if (!this.duration) { + return; + } // Validate input + + + const inputIsValid = is.number(input) && input > 0; // Set + + this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0; // Logging + + this.debug.log(`Seeking to ${this.currentTime} seconds`); + } + /** + * Get current time + */ + + + get currentTime() { + return Number(this.media.currentTime); + } + /** + * Get buffered + */ + + + get buffered() { + const { + buffered + } = this.media; // YouTube / Vimeo return a float between 0-1 + + if (is.number(buffered)) { + return buffered; + } // HTML5 + // TODO: Handle buffered chunks of the media + // (i.e. seek to another section buffers only that section) + + + if (buffered && buffered.length && this.duration > 0) { + return buffered.end(0) / this.duration; + } + + return 0; + } + /** + * Get seeking status + */ + + + get seeking() { + return Boolean(this.media.seeking); + } + /** + * Get the duration of the current media + */ + + + get duration() { + // Faux duration set via config + const fauxDuration = parseFloat(this.config.duration); // Media duration can be NaN or Infinity before the media has loaded + + const realDuration = (this.media || {}).duration; + const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration; // If config duration is funky, use regular duration + + return fauxDuration || duration; + } + /** + * 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 + */ + + + set volume(value) { + let volume = value; + const max = 1; + const min = 0; + + if (is.string(volume)) { + volume = Number(volume); + } // Load volume from storage if no value specified + + + if (!is.number(volume)) { + volume = this.storage.get('volume'); + } // Use config if all else fails + + + if (!is.number(volume)) { + ({ + volume + } = this.config); + } // Maximum is volumeMax + + + if (volume > max) { + volume = max; + } // Minimum is volumeMin + + + if (volume < min) { + volume = min; + } // Update config + + + this.config.volume = volume; // Set the player volume + + this.media.volume = volume; // If muted, and we're increasing volume manually, reset muted state + + if (!is.empty(value) && this.muted && volume > 0) { + this.muted = false; + } + } + /** + * Get the current player volume + */ + + + get volume() { + return Number(this.media.volume); + } + /** + * Increase volume + * @param {Boolean} step - How much to decrease by (between 0 and 1) + */ + + + /** + * Set muted state + * @param {Boolean} mute + */ + set muted(mute) { + let toggle = mute; // Load muted state from storage + + if (!is.boolean(toggle)) { + toggle = this.storage.get('muted'); + } // Use config if all else fails + + + if (!is.boolean(toggle)) { + toggle = this.config.muted; + } // Update config + + + this.config.muted = toggle; // Set mute on the player + + this.media.muted = toggle; + } + /** + * Get current muted state + */ + + + get muted() { + return Boolean(this.media.muted); + } + /** + * Check if the media has audio + */ + + + get hasAudio() { + // Assume yes for all non HTML5 (as we can't tell...) + if (!this.isHTML5) { + return true; + } + + if (this.isAudio) { + return true; + } // Get audio tracks + + + return Boolean(this.media.mozHasAudio) || Boolean(this.media.webkitAudioDecodedByteCount) || Boolean(this.media.audioTracks && this.media.audioTracks.length); + } + /** + * Set playback speed + * @param {Number} speed - the speed of playback (0.5-2.0) + */ + + + set speed(input) { + let speed = null; + + if (is.number(input)) { + speed = input; + } + + if (!is.number(speed)) { + speed = this.storage.get('speed'); + } + + if (!is.number(speed)) { + speed = this.config.speed.selected; + } // Clamp to min/max + + + const { + minimumSpeed: min, + maximumSpeed: max + } = this; + speed = clamp(speed, min, max); // Update config + + this.config.speed.selected = speed; // Set media speed + + setTimeout(() => { + if (this.media) { + this.media.playbackRate = speed; + } + }, 0); + } + /** + * Get current playback speed + */ + + + get speed() { + return Number(this.media.playbackRate); + } + /** + * Get the minimum allowed speed + */ + + + get minimumSpeed() { + if (this.isYouTube) { + // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate + return Math.min(...this.options.speed); + } + + if (this.isVimeo) { + // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror + return 0.5; + } // https://stackoverflow.com/a/32320020/1191319 + + + return 0.0625; + } + /** + * Get the maximum allowed speed + */ + + + get maximumSpeed() { + if (this.isYouTube) { + // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate + return Math.max(...this.options.speed); + } + + if (this.isVimeo) { + // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror + return 2; + } // https://stackoverflow.com/a/32320020/1191319 + + + return 16; + } + /** + * Set playback quality + * Currently HTML5 & YouTube only + * @param {Number} input - Quality level + */ + + + set quality(input) { + const config = this.config.quality; + const options = this.options.quality; + + if (!options.length) { + return; + } + + let quality = [!is.empty(input) && Number(input), this.storage.get('quality'), config.selected, config.default].find(is.number); + let updateStorage = true; + + if (!options.includes(quality)) { + const value = closest(options, quality); + this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`); + quality = value; // Don't update storage if quality is not supported + + updateStorage = false; + } // Update config + + + config.selected = quality; // Set quality + + this.media.quality = quality; // Save to storage + + if (updateStorage) { + this.storage.set({ + quality + }); + } + } + /** + * Get current quality level + */ + + + get quality() { + return this.media.quality; + } + /** + * 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 + */ + + + set loop(input) { + const toggle = is.boolean(input) ? input : this.config.loop.active; + this.config.loop.active = toggle; + this.media.loop = toggle; // Set default to be a true toggle + + /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle'; + switch (type) { + case 'start': + if (this.config.loop.end && this.config.loop.end <= this.currentTime) { + this.config.loop.end = null; + } + this.config.loop.start = this.currentTime; + // this.config.loop.indicator.start = this.elements.display.played.value; + break; + case 'end': + if (this.config.loop.start >= this.currentTime) { + return this; + } + this.config.loop.end = this.currentTime; + // this.config.loop.indicator.end = this.elements.display.played.value; + break; + case 'all': + this.config.loop.start = 0; + this.config.loop.end = this.duration - 2; + this.config.loop.indicator.start = 0; + this.config.loop.indicator.end = 100; + break; + case 'toggle': + if (this.config.loop.active) { + this.config.loop.start = 0; + this.config.loop.end = null; + } else { + this.config.loop.start = 0; + this.config.loop.end = this.duration - 2; + } + break; + default: + this.config.loop.start = 0; + this.config.loop.end = null; + break; + } */ + } + /** + * Get current loop state + */ + + + get loop() { + return Boolean(this.media.loop); + } + /** + * Set new media source + * @param {Object} input - The new source object (see docs) + */ + + + set source(input) { + source.change.call(this, input); + } + /** + * Get current source + */ + + + get source() { + return this.media.currentSrc; + } + /** + * Get a download URL (either source or custom) + */ + + + get download() { + const { + download + } = this.config.urls; + return is.url(download) ? download : this.source; + } + /** + * Set the download URL + */ + + + set download(input) { + if (!is.url(input)) { + return; + } + + this.config.urls.download = input; + controls.setDownloadUrl.call(this); + } + /** + * Set the poster image for a video + * @param {String} input - the URL for the new poster image + */ + + + set poster(input) { + if (!this.isVideo) { + this.debug.warn('Poster can only be set for video'); + return; + } + + ui.setPoster.call(this, input, false).catch(() => {}); + } + /** + * Get the current poster image + */ + + + get poster() { + if (!this.isVideo) { + return null; + } + + return this.media.getAttribute('poster') || this.media.getAttribute('data-poster'); + } + /** + * Get the current aspect ratio in use + */ + + + get ratio() { + if (!this.isVideo) { + return null; + } + + const ratio = reduceAspectRatio(getAspectRatio.call(this)); + return is.array(ratio) ? ratio.join(':') : ratio; + } + /** + * Set video aspect ratio + */ + + + set ratio(input) { + if (!this.isVideo) { + this.debug.warn('Aspect ratio can only be set for video'); + return; + } + + if (!is.string(input) || !validateAspectRatio(input)) { + this.debug.error(`Invalid aspect ratio specified (${input})`); + return; + } + + this.config.ratio = reduceAspectRatio(input); + setAspectRatio.call(this); + } + /** + * Set the autoplay state + * @param {Boolean} input - Whether to autoplay or not + */ + + + set autoplay(input) { + const toggle = is.boolean(input) ? input : this.config.autoplay; + this.config.autoplay = toggle; + } + /** + * Get the current autoplay state + */ + + + get autoplay() { + return Boolean(this.config.autoplay); + } + /** + * Toggle captions + * @param {Boolean} input - Whether to enable captions + */ + + + toggleCaptions(input) { + captions.toggle.call(this, input, false); + } + /** + * Set the caption track by index + * @param {Number} - Caption index + */ + + + set currentTrack(input) { + captions.set.call(this, input, false); + captions.setup(); + } + /** + * Get the current caption track index (-1 if disabled) + */ + + + get currentTrack() { + const { + toggled, + currentTrack + } = this.captions; + return toggled ? currentTrack : -1; + } + /** + * 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) + */ + + + set language(input) { + captions.setLanguage.call(this, input, false); + } + /** + * Get the current track's language + */ + + + get language() { + return (captions.getCurrentTrack.call(this) || {}).language; + } + /** + * Toggle picture-in-picture playback on WebKit/MacOS + * TODO: update player with state, support, enabled + * TODO: detect outside changes + */ + + + set pip(input) { + // Bail if no support + if (!support.pip) { + return; + } // Toggle based on current state if not passed + + + const toggle = is.boolean(input) ? input : !this.pip; // Toggle based on current state + // Safari + + if (is.function(this.media.webkitSetPresentationMode)) { + this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive); + } // Chrome + + + if (is.function(this.media.requestPictureInPicture)) { + if (!this.pip && toggle) { + this.media.requestPictureInPicture(); + } else if (this.pip && !toggle) { + document.exitPictureInPicture(); + } + } + } + /** + * Get the current picture-in-picture state + */ + + + get pip() { + if (!support.pip) { + return null; + } // Safari + + + if (!is.empty(this.media.webkitPresentationMode)) { + return this.media.webkitPresentationMode === pip.active; + } // Chrome + + + return this.media === document.pictureInPictureElement; + } + /** + * Sets the preview thubmnails for the current source + */ + + + setPreviewThumbnails(thumbnailSource) { + if (this.previewThumbnails && this.previewThumbnails.loaded) { + this.previewThumbnails.destroy(); + this.previewThumbnails = null; + } + + Object.assign(this.config.previewThumbnails, thumbnailSource); // Create new instance if it is still enabled + + if (this.config.previewThumbnails.enabled) { + this.previewThumbnails = new PreviewThumbnails(this); + } + } + /** + * Trigger the airplay dialog + * TODO: update player with state, support, enabled + */ + + + /** + * Check for support + * @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); + } + /** + * Load an SVG sprite into the page + * @param {String} url - URL for the SVG sprite + * @param {String} [id] - Unique ID + */ + + + static loadSprite(url, id) { + return loadSprite(url, id); + } + /** + * Setup multiple instances + * @param {*} selector + * @param {Object} options + */ + + + static setup(selector, options = {}) { + let targets = null; + + if (is.string(selector)) { + targets = Array.from(document.querySelectorAll(selector)); + } else if (is.nodeList(selector)) { + targets = Array.from(selector); + } else if (is.array(selector)) { + targets = selector.filter(is.element); + } + + if (is.empty(targets)) { + return null; + } + + return targets.map(t => new Plyr(t, options)); + } + + } + + Plyr.defaults = cloneDeep(defaults); + + // ========================================================================== + + return Plyr; + +})); diff --git a/extlib/plyr/plyr.polyfilled.min.js b/extlib/plyr/plyr.polyfilled.min.js new file mode 100644 index 00000000..80d6d574 --- /dev/null +++ b/extlib/plyr/plyr.polyfilled.min.js @@ -0,0 +1,2 @@ +"object"==typeof navigator&&function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Plyr",t):(e="undefined"!=typeof globalThis?globalThis:e||self).Plyr=t()}(this,(function(){"use strict";!function(){if("undefined"!=typeof window)try{var e=new window.CustomEvent("test",{cancelable:!0});if(e.preventDefault(),!0!==e.defaultPrevented)throw new Error("Could not prevent default")}catch(e){var t=function(e,t){var i,s;return(t=t||{}).bubbles=!!t.bubbles,t.cancelable=!!t.cancelable,(i=document.createEvent("CustomEvent")).initCustomEvent(e,t.bubbles,t.cancelable,t.detail),s=i.preventDefault,i.preventDefault=function(){s.call(this);try{Object.defineProperty(this,"defaultPrevented",{get:function(){return!0}})}catch(e){this.defaultPrevented=!0}},i};t.prototype=window.Event.prototype,window.CustomEvent=t}}();var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function i(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}function s(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function n(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function a(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?n(Object(i),!0).forEach((function(t){s(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}!function(e){var t=function(){try{return!!Symbol.iterator}catch(e){return!1}}(),i=function(e){var i={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return t&&(i[Symbol.iterator]=function(){return i}),i},s=function(e){return encodeURIComponent(e).replace(/%20/g,"+")},n=function(e){return decodeURIComponent(String(e).replace(/\+/g," "))};(function(){try{var t=e.URLSearchParams;return"a=1"===new t("?a=1").toString()&&"function"==typeof t.prototype.set&&"function"==typeof t.prototype.entries}catch(e){return!1}})()||function(){var n=function(e){Object.defineProperty(this,"_entries",{writable:!0,value:{}});var t=typeof e;if("undefined"===t);else if("string"===t)""!==e&&this._fromString(e);else if(e instanceof n){var i=this;e.forEach((function(e,t){i.append(t,e)}))}else{if(null===e||"object"!==t)throw new TypeError("Unsupported input's type for URLSearchParams");if("[object Array]"===Object.prototype.toString.call(e))for(var s=0;s<e.length;s++){var a=e[s];if("[object Array]"!==Object.prototype.toString.call(a)&&2===a.length)throw new TypeError("Expected [string, any] as entry at index "+s+" of URLSearchParams's input");this.append(a[0],a[1])}else for(var r in e)e.hasOwnProperty(r)&&this.append(r,e[r])}},a=n.prototype;a.append=function(e,t){e in this._entries?this._entries[e].push(String(t)):this._entries[e]=[String(t)]},a.delete=function(e){delete this._entries[e]},a.get=function(e){return e in this._entries?this._entries[e][0]:null},a.getAll=function(e){return e in this._entries?this._entries[e].slice(0):[]},a.has=function(e){return e in this._entries},a.set=function(e,t){this._entries[e]=[String(t)]},a.forEach=function(e,t){var i;for(var s in this._entries)if(this._entries.hasOwnProperty(s)){i=this._entries[s];for(var n=0;n<i.length;n++)e.call(t,i[n],s,this)}},a.keys=function(){var e=[];return this.forEach((function(t,i){e.push(i)})),i(e)},a.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),i(e)},a.entries=function(){var e=[];return this.forEach((function(t,i){e.push([i,t])})),i(e)},t&&(a[Symbol.iterator]=a.entries),a.toString=function(){var e=[];return this.forEach((function(t,i){e.push(s(i)+"="+s(t))})),e.join("&")},e.URLSearchParams=n}();var a=e.URLSearchParams.prototype;"function"!=typeof a.sort&&(a.sort=function(){var e=this,t=[];this.forEach((function(i,s){t.push([s,i]),e._entries||e.delete(s)})),t.sort((function(e,t){return e[0]<t[0]?-1:e[0]>t[0]?1:0})),e._entries&&(e._entries={});for(var i=0;i<t.length;i++)this.append(t[i][0],t[i][1])}),"function"!=typeof a._fromString&&Object.defineProperty(a,"_fromString",{enumerable:!1,configurable:!1,writable:!1,value:function(e){if(this._entries)this._entries={};else{var t=[];this.forEach((function(e,i){t.push(i)}));for(var i=0;i<t.length;i++)this.delete(t[i])}var s,a=(e=e.replace(/^\?/,"")).split("&");for(i=0;i<a.length;i++)s=a[i].split("="),this.append(n(s[0]),s.length>1?n(s[1]):"")}})}(void 0!==e?e:"undefined"!=typeof window?window:"undefined"!=typeof self?self:e),function(e){if(function(){try{var t=new e.URL("b","http://a");return t.pathname="c d","http://a/c%20d"===t.href&&t.searchParams}catch(e){return!1}}()||function(){var t=e.URL,i=function(t,i){"string"!=typeof t&&(t=String(t)),i&&"string"!=typeof i&&(i=String(i));var s,n=document;if(i&&(void 0===e.location||i!==e.location.href)){i=i.toLowerCase(),(s=(n=document.implementation.createHTMLDocument("")).createElement("base")).href=i,n.head.appendChild(s);try{if(0!==s.href.indexOf(i))throw new Error(s.href)}catch(e){throw new Error("URL unable to set base "+i+" due to "+e)}}var a=n.createElement("a");a.href=t,s&&(n.body.appendChild(a),a.href=a.href);var r=n.createElement("input");if(r.type="url",r.value=t,":"===a.protocol||!/:/.test(a.href)||!r.checkValidity()&&!i)throw new TypeError("Invalid URL");Object.defineProperty(this,"_anchorElement",{value:a});var o=new e.URLSearchParams(this.search),l=!0,c=!0,h=this;["append","delete","set"].forEach((function(e){var t=o[e];o[e]=function(){t.apply(o,arguments),l&&(c=!1,h.search=o.toString(),c=!0)}})),Object.defineProperty(this,"searchParams",{value:o,enumerable:!0});var u=void 0;Object.defineProperty(this,"_updateSearchParams",{enumerable:!1,configurable:!1,writable:!1,value:function(){this.search!==u&&(u=this.search,c&&(l=!1,this.searchParams._fromString(this.search),l=!0))}})},s=i.prototype;["hash","host","hostname","port","protocol"].forEach((function(e){!function(e){Object.defineProperty(s,e,{get:function(){return this._anchorElement[e]},set:function(t){this._anchorElement[e]=t},enumerable:!0})}(e)})),Object.defineProperty(s,"search",{get:function(){return this._anchorElement.search},set:function(e){this._anchorElement.search=e,this._updateSearchParams()},enumerable:!0}),Object.defineProperties(s,{toString:{get:function(){var e=this;return function(){return e.href}}},href:{get:function(){return this._anchorElement.href.replace(/\?$/,"")},set:function(e){this._anchorElement.href=e,this._updateSearchParams()},enumerable:!0},pathname:{get:function(){return this._anchorElement.pathname.replace(/(^\/?)/,"/")},set:function(e){this._anchorElement.pathname=e},enumerable:!0},origin:{get:function(){var e={"http:":80,"https:":443,"ftp:":21}[this._anchorElement.protocol],t=this._anchorElement.port!=e&&""!==this._anchorElement.port;return this._anchorElement.protocol+"//"+this._anchorElement.hostname+(t?":"+this._anchorElement.port:"")},enumerable:!0},password:{get:function(){return""},set:function(e){},enumerable:!0},username:{get:function(){return""},set:function(e){},enumerable:!0}}),i.createObjectURL=function(e){return t.createObjectURL.apply(t,arguments)},i.revokeObjectURL=function(e){return t.revokeObjectURL.apply(t,arguments)},e.URL=i}(),void 0!==e.location&&!("origin"in e.location)){var t=function(){return e.location.protocol+"//"+e.location.hostname+(e.location.port?":"+e.location.port:"")};try{Object.defineProperty(e.location,"origin",{get:t,enumerable:!0})}catch(i){setInterval((function(){e.location.origin=t()}),100)}}}(void 0!==e?e:"undefined"!=typeof window?window:"undefined"!=typeof self?self:e);var r={addCSS:!0,thumbWidth:15,watch:!0};function o(e,t){return function(){return Array.from(document.querySelectorAll(t)).includes(this)}.call(e,t)}var l=function(e){return null!=e?e.constructor:null},c=function(e,t){return!!(e&&t&&e instanceof t)},h=function(e){return null==e},u=function(e){return l(e)===Object},d=function(e){return l(e)===String},p=function(e){return Array.isArray(e)},m=function(e){return c(e,NodeList)},g=d,f=p,b=m,y=function(e){return c(e,Element)},v=function(e){return c(e,Event)},w=function(e){return h(e)||(d(e)||p(e)||m(e))&&!e.length||u(e)&&!Object.keys(e).length};function T(e,t){if(1>t){var i=function(e){var t="".concat(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0}(t);return parseFloat(e.toFixed(i))}return Math.round(e/t)*t}var k=function(){function e(t,i){(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),y(t)?this.element=t:g(t)&&(this.element=document.querySelector(t)),y(this.element)&&w(this.element.rangeTouch)&&(this.config=a({},r,{},i),this.init())}return function(e,t,s){t&&i(e.prototype,t),s&&i(e,s)}(e,[{key:"init",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect="none",this.element.style.webKitUserSelect="none",this.element.style.touchAction="manipulation"),this.listeners(!0),this.element.rangeTouch=this)}},{key:"destroy",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect="",this.element.style.webKitUserSelect="",this.element.style.touchAction=""),this.listeners(!1),this.element.rangeTouch=null)}},{key:"listeners",value:function(e){var t=this,i=e?"addEventListener":"removeEventListener";["touchstart","touchmove","touchend"].forEach((function(e){t.element[i](e,(function(e){return t.set(e)}),!1)}))}},{key:"get",value:function(t){if(!e.enabled||!v(t))return null;var i,s=t.target,n=t.changedTouches[0],a=parseFloat(s.getAttribute("min"))||0,r=parseFloat(s.getAttribute("max"))||100,o=parseFloat(s.getAttribute("step"))||1,l=s.getBoundingClientRect(),c=100/l.width*(this.config.thumbWidth/2)/100;return 0>(i=100/l.width*(n.clientX-l.left))?i=0:100<i&&(i=100),50>i?i-=(100-2*i)*c:50<i&&(i+=2*(i-50)*c),a+T(i/100*(r-a),o)}},{key:"set",value:function(t){e.enabled&&v(t)&&!t.target.disabled&&(t.preventDefault(),t.target.value=this.get(t),function(e,t){if(e&&t){var i=new Event(t,{bubbles:!0});e.dispatchEvent(i)}}(t.target,"touchend"===t.type?"change":"input"))}}],[{key:"setup",value:function(t){var i=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},s=null;if(w(t)||g(t)?s=Array.from(document.querySelectorAll(g(t)?t:'input[type="range"]')):y(t)?s=[t]:b(t)?s=Array.from(t):f(t)&&(s=t.filter(y)),w(s))return null;var n=a({},r,{},i);if(g(t)&&n.watch){var l=new MutationObserver((function(i){Array.from(i).forEach((function(i){Array.from(i.addedNodes).forEach((function(i){y(i)&&o(i,t)&&new e(i,n)}))}))}));l.observe(document.body,{childList:!0,subtree:!0})}return s.map((function(t){return new e(t,i)}))}},{key:"enabled",get:function(){return"ontouchstart"in document.documentElement}}]),e}();const C=e=>null!=e?e.constructor:null,E=(e,t)=>Boolean(e&&t&&e instanceof t),S=e=>null==e,P=e=>C(e)===Object,A=e=>C(e)===String,x=e=>C(e)===Function,N=e=>Array.isArray(e),M=e=>E(e,NodeList),_=e=>S(e)||(A(e)||N(e)||M(e))&&!e.length||P(e)&&!Object.keys(e).length;var L=S,I=P,$=e=>C(e)===Number&&!Number.isNaN(e),O=A,j=e=>C(e)===Boolean,R=x,q=N,D=M,H=e=>null!==e&&"object"==typeof e&&1===e.nodeType&&"object"==typeof e.style&&"object"==typeof e.ownerDocument,F=e=>E(e,Event),V=e=>E(e,KeyboardEvent),U=e=>E(e,TextTrack)||!S(e)&&A(e.kind),B=e=>E(e,Promise)&&x(e.then),W=e=>{if(E(e,window.URL))return!0;if(!A(e))return!1;let t=e;e.startsWith("http://")&&e.startsWith("https://")||(t=`http://${e}`);try{return!_(new URL(t).hostname)}catch(e){return!1}},z=_;const K=(()=>{const e=document.createElement("span"),t={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},i=Object.keys(t).find((t=>void 0!==e.style[t]));return!!O(i)&&t[i]})();function Y(e,t){setTimeout((()=>{try{e.hidden=!0,e.offsetHeight,e.hidden=!1}catch(e){}}),t)}const Q={isIE:Boolean(window.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:"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1||/(iPad|iPhone|iPod)/gi.test(navigator.platform)};function X(e,t){return t.split(".").reduce(((e,t)=>e&&e[t]),e)}function J(e={},...t){if(!t.length)return e;const i=t.shift();return I(i)?(Object.keys(i).forEach((t=>{I(i[t])?(Object.keys(e).includes(t)||Object.assign(e,{[t]:{}}),J(e[t],i[t])):Object.assign(e,{[t]:i[t]})})),J(e,...t)):e}function G(e,t){const i=e.length?e:[e];Array.from(i).reverse().forEach(((e,i)=>{const s=i>0?t.cloneNode(!0):t,n=e.parentNode,a=e.nextSibling;s.appendChild(e),a?n.insertBefore(s,a):n.appendChild(s)}))}function Z(e,t){H(e)&&!z(t)&&Object.entries(t).filter((([,e])=>!L(e))).forEach((([t,i])=>e.setAttribute(t,i)))}function ee(e,t,i){const s=document.createElement(e);return I(t)&&Z(s,t),O(i)&&(s.innerText=i),s}function te(e,t,i,s){H(t)&&t.appendChild(ee(e,i,s))}function ie(e){D(e)||q(e)?Array.from(e).forEach(ie):H(e)&&H(e.parentNode)&&e.parentNode.removeChild(e)}function se(e){if(!H(e))return;let{length:t}=e.childNodes;for(;t>0;)e.removeChild(e.lastChild),t-=1}function ne(e,t){return H(t)&&H(t.parentNode)&&H(e)?(t.parentNode.replaceChild(e,t),e):null}function ae(e,t){if(!O(e)||z(e))return{};const i={},s=J({},t);return e.split(",").forEach((e=>{const t=e.trim(),n=t.replace(".",""),a=t.replace(/[[\]]/g,"").split("="),[r]=a,o=a.length>1?a[1].replace(/["']/g,""):"";switch(t.charAt(0)){case".":O(s.class)?i.class=`${s.class} ${n}`:i.class=n;break;case"#":i.id=t.replace("#","");break;case"[":i[r]=o}})),J(s,i)}function re(e,t){if(!H(e))return;let i=t;j(i)||(i=!e.hidden),e.hidden=i}function oe(e,t,i){if(D(e))return Array.from(e).map((e=>oe(e,t,i)));if(H(e)){let s="toggle";return void 0!==i&&(s=i?"add":"remove"),e.classList[s](t),e.classList.contains(t)}return!1}function le(e,t){return H(e)&&e.classList.contains(t)}function ce(e,t){const{prototype:i}=Element;return(i.matches||i.webkitMatchesSelector||i.mozMatchesSelector||i.msMatchesSelector||function(){return Array.from(document.querySelectorAll(t)).includes(this)}).call(e,t)}function he(e){return this.elements.container.querySelectorAll(e)}function ue(e){return this.elements.container.querySelector(e)}function de(e=null,t=!1){H(e)&&(e.focus({preventScroll:!0}),t&&oe(e,this.config.classNames.tabFocus))}const pe={"audio/ogg":"vorbis","audio/wav":"1","video/webm":"vp8, vorbis","video/mp4":"avc1.42E01E, mp4a.40.2","video/ogg":"theora"},me={audio:"canPlayType"in document.createElement("audio"),video:"canPlayType"in document.createElement("video"),check(e,t,i){const s=Q.isIPhone&&i&&me.playsinline,n=me[e]||"html5"!==t;return{api:n,ui:n&&me.rangeInput&&("video"!==e||!Q.isIPhone||s)}},pip:!(Q.isIPhone||!R(ee("video").webkitSetPresentationMode)&&(!document.pictureInPictureEnabled||ee("video").disablePictureInPicture)),airplay:R(window.WebKitPlaybackTargetAvailabilityEvent),playsinline:"playsInline"in document.createElement("video"),mime(e){if(z(e))return!1;const[t]=e.split("/");let i=e;if(!this.isHTML5||t!==this.type)return!1;Object.keys(pe).includes(i)&&(i+=`; codecs="${pe[e]}"`);try{return Boolean(i&&this.media.canPlayType(i).replace(/no/,""))}catch(e){return!1}},textTracks:"textTracks"in document.createElement("video"),rangeInput:(()=>{const e=document.createElement("input");return e.type="range","range"===e.type})(),touch:"ontouchstart"in document.documentElement,transitions:!1!==K,reducedMotion:"matchMedia"in window&&window.matchMedia("(prefers-reduced-motion)").matches},ge=(()=>{let e=!1;try{const t=Object.defineProperty({},"passive",{get:()=>(e=!0,null)});window.addEventListener("test",null,t),window.removeEventListener("test",null,t)}catch(e){}return e})();function fe(e,t,i,s=!1,n=!0,a=!1){if(!e||!("addEventListener"in e)||z(t)||!R(i))return;const r=t.split(" ");let o=a;ge&&(o={passive:n,capture:a}),r.forEach((t=>{this&&this.eventListeners&&s&&this.eventListeners.push({element:e,type:t,callback:i,options:o}),e[s?"addEventListener":"removeEventListener"](t,i,o)}))}function be(e,t="",i,s=!0,n=!1){fe.call(this,e,t,i,!0,s,n)}function ye(e,t="",i,s=!0,n=!1){fe.call(this,e,t,i,!1,s,n)}function ve(e,t="",i,s=!0,n=!1){const a=(...r)=>{ye(e,t,a,s,n),i.apply(this,r)};fe.call(this,e,t,a,!0,s,n)}function we(e,t="",i=!1,s={}){if(!H(e)||z(t))return;const n=new CustomEvent(t,{bubbles:i,detail:{...s,plyr:this}});e.dispatchEvent(n)}function Te(){this&&this.eventListeners&&(this.eventListeners.forEach((e=>{const{element:t,type:i,callback:s,options:n}=e;t.removeEventListener(i,s,n)})),this.eventListeners=[])}function ke(){return new Promise((e=>this.ready?setTimeout(e,0):be.call(this,this.elements.container,"ready",e))).then((()=>{}))}function Ce(e){B(e)&&e.then(null,(()=>{}))}function Ee(e){return q(e)?e.filter(((t,i)=>e.indexOf(t)===i)):e}function Se(e,t){return q(e)&&e.length?e.reduce(((e,i)=>Math.abs(i-t)<Math.abs(e-t)?i:e)):null}function Pe(e){return!(!window||!window.CSS)&&window.CSS.supports(e)}const Ae=[[1,1],[4,3],[3,4],[5,4],[4,5],[3,2],[2,3],[16,10],[10,16],[16,9],[9,16],[21,9],[9,21],[32,9],[9,32]].reduce(((e,[t,i])=>({...e,[t/i]:[t,i]})),{});function xe(e){if(!(q(e)||O(e)&&e.includes(":")))return!1;return(q(e)?e:e.split(":")).map(Number).every($)}function Ne(e){if(!q(e)||!e.every($))return null;const[t,i]=e,s=(e,t)=>0===t?e:s(t,e%t),n=s(t,i);return[t/n,i/n]}function Me(e){const t=e=>xe(e)?e.split(":").map(Number):null;let i=t(e);if(null===i&&(i=t(this.config.ratio)),null===i&&!z(this.embed)&&q(this.embed.ratio)&&({ratio:i}=this.embed),null===i&&this.isHTML5){const{videoWidth:e,videoHeight:t}=this.media;i=[e,t]}return Ne(i)}function _e(e){if(!this.isVideo)return{};const{wrapper:t}=this.elements,i=Me.call(this,e);if(!q(i))return{};const[s,n]=Ne(i),a=100/s*n;if(Pe(`aspect-ratio: ${s}/${n}`)?t.style.aspectRatio=`${s}/${n}`:t.style.paddingBottom=`${a}%`,this.isVimeo&&!this.config.vimeo.premium&&this.supported.ui){const e=100/this.media.offsetWidth*parseInt(window.getComputedStyle(this.media).paddingBottom,10),i=(e-a)/(e/50);this.fullscreen.active?t.style.paddingBottom=null:this.media.style.transform=`translateY(-${i}%)`}else this.isHTML5&&t.classList.add(this.config.classNames.videoFixedRatio);return{padding:a,ratio:i}}function Le(e,t,i=.05){const s=e/t,n=Se(Object.keys(Ae),s);return Math.abs(n-s)<=i?Ae[n]:[e,t]}const Ie={getSources(){if(!this.isHTML5)return[];return Array.from(this.media.querySelectorAll("source")).filter((e=>{const t=e.getAttribute("type");return!!z(t)||me.mime.call(this,t)}))},getQualityOptions(){return this.config.quality.forced?this.config.quality.options:Ie.getSources.call(this).map((e=>Number(e.getAttribute("data-res")))).filter(Boolean)},setup(){if(!this.isHTML5)return;const e=this;e.options.speed=e.config.speed.options,z(this.config.ratio)||_e.call(e),Object.defineProperty(e.media,"quality",{get(){const t=Ie.getSources.call(e).find((t=>t.getAttribute("src")===e.source));return t&&Number(t.getAttribute("data-res"))},set(t){if(e.quality!==t){if(e.config.quality.forced&&R(e.config.quality.onChange))e.config.quality.onChange(t);else{const i=Ie.getSources.call(e).find((e=>Number(e.getAttribute("data-res"))===t));if(!i)return;const{currentTime:s,paused:n,preload:a,readyState:r,playbackRate:o}=e.media;e.media.src=i.getAttribute("src"),("none"!==a||r)&&(e.once("loadedmetadata",(()=>{e.speed=o,e.currentTime=s,n||Ce(e.play())})),e.media.load())}we.call(e,e.media,"qualitychange",!1,{quality:t})}}})},cancelRequests(){this.isHTML5&&(ie(Ie.getSources.call(this)),this.media.setAttribute("src",this.config.blankVideo),this.media.load(),this.debug.log("Cancelled network requests"))}};function $e(e,...t){return z(e)?e:e.toString().replace(/{(\d+)}/g,((e,i)=>t[i].toString()))}const Oe=(e="",t="",i="")=>e.replace(new RegExp(t.toString().replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1"),"g"),i.toString()),je=(e="")=>e.toString().replace(/\w\S*/g,(e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()));function Re(e=""){let t=e.toString();return t=function(e=""){let t=e.toString();return t=Oe(t,"-"," "),t=Oe(t,"_"," "),t=je(t),Oe(t," ","")}(t),t.charAt(0).toLowerCase()+t.slice(1)}function qe(e){const t=document.createElement("div");return t.appendChild(e),t.innerHTML}const De={pip:"PIP",airplay:"AirPlay",html5:"HTML5",vimeo:"Vimeo",youtube:"YouTube"},He={get(e="",t={}){if(z(e)||z(t))return"";let i=X(t.i18n,e);if(z(i))return Object.keys(De).includes(e)?De[e]:"";const s={"{seektime}":t.seekTime,"{title}":t.title};return Object.entries(s).forEach((([e,t])=>{i=Oe(i,e,t)})),i}};class Fe{constructor(e){t(this,"get",(e=>{if(!Fe.supported||!this.enabled)return null;const t=window.localStorage.getItem(this.key);if(z(t))return null;const i=JSON.parse(t);return O(e)&&e.length?i[e]:i})),t(this,"set",(e=>{if(!Fe.supported||!this.enabled)return;if(!I(e))return;let t=this.get();z(t)&&(t={}),J(t,e);try{window.localStorage.setItem(this.key,JSON.stringify(t))}catch(e){}})),this.enabled=e.config.storage.enabled,this.key=e.config.storage.key}static get supported(){try{if(!("localStorage"in window))return!1;const e="___test";return window.localStorage.setItem(e,e),window.localStorage.removeItem(e),!0}catch(e){return!1}}}function Ve(e,t="text"){return new Promise(((i,s)=>{try{const s=new XMLHttpRequest;if(!("withCredentials"in s))return;s.addEventListener("load",(()=>{if("text"===t)try{i(JSON.parse(s.responseText))}catch(e){i(s.responseText)}else i(s.response)})),s.addEventListener("error",(()=>{throw new Error(s.status)})),s.open("GET",e,!0),s.responseType=t,s.send()}catch(e){s(e)}}))}function Ue(e,t){if(!O(e))return;const i=O(t);let s=!1;const n=()=>null!==document.getElementById(t),a=(e,t)=>{e.innerHTML=t,i&&n()||document.body.insertAdjacentElement("afterbegin",e)};if(!i||!n()){const n=Fe.supported,r=document.createElement("div");if(r.setAttribute("hidden",""),i&&r.setAttribute("id",t),n){const e=window.localStorage.getItem(`cache-${t}`);if(s=null!==e,s){const t=JSON.parse(e);a(r,t.content)}}Ve(e).then((e=>{if(!z(e)){if(n)try{window.localStorage.setItem(`cache-${t}`,JSON.stringify({content:e}))}catch(e){}a(r,e)}})).catch((()=>{}))}}const Be=e=>Math.trunc(e/60/60%60,10);function We(e=0,t=!1,i=!1){if(!$(e))return We(void 0,t,i);const s=e=>`0${e}`.slice(-2);let n=Be(e);const a=(r=e,Math.trunc(r/60%60,10));var r;const o=(e=>Math.trunc(e%60,10))(e);return n=t||n>0?`${n}:`:"",`${i&&e>0?"-":""}${n}${s(a)}:${s(o)}`}const ze={getIconUrl(){const e=new URL(this.config.iconUrl,window.location),t=window.location.host?window.location.host:window.top.location.host,i=e.host!==t||Q.isIE&&!window.svg4everybody;return{url:this.config.iconUrl,cors:i}},findElements(){try{return this.elements.controls=ue.call(this,this.config.selectors.controls.wrapper),this.elements.buttons={play:he.call(this,this.config.selectors.buttons.play),pause:ue.call(this,this.config.selectors.buttons.pause),restart:ue.call(this,this.config.selectors.buttons.restart),rewind:ue.call(this,this.config.selectors.buttons.rewind),fastForward:ue.call(this,this.config.selectors.buttons.fastForward),mute:ue.call(this,this.config.selectors.buttons.mute),pip:ue.call(this,this.config.selectors.buttons.pip),airplay:ue.call(this,this.config.selectors.buttons.airplay),settings:ue.call(this,this.config.selectors.buttons.settings),captions:ue.call(this,this.config.selectors.buttons.captions),fullscreen:ue.call(this,this.config.selectors.buttons.fullscreen)},this.elements.progress=ue.call(this,this.config.selectors.progress),this.elements.inputs={seek:ue.call(this,this.config.selectors.inputs.seek),volume:ue.call(this,this.config.selectors.inputs.volume)},this.elements.display={buffer:ue.call(this,this.config.selectors.display.buffer),currentTime:ue.call(this,this.config.selectors.display.currentTime),duration:ue.call(this,this.config.selectors.display.duration)},H(this.elements.progress)&&(this.elements.display.seekTooltip=this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`)),!0}catch(e){return this.debug.warn("It looks like there is a problem with your custom controls HTML",e),this.toggleNativeControls(!0),!1}},createIcon(e,t){const i="http://www.w3.org/2000/svg",s=ze.getIconUrl.call(this),n=`${s.cors?"":s.url}#${this.config.iconPrefix}`,a=document.createElementNS(i,"svg");Z(a,J(t,{"aria-hidden":"true",focusable:"false"}));const r=document.createElementNS(i,"use"),o=`${n}-${e}`;return"href"in r&&r.setAttributeNS("http://www.w3.org/1999/xlink","href",o),r.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",o),a.appendChild(r),a},createLabel(e,t={}){const i=He.get(e,this.config);return ee("span",{...t,class:[t.class,this.config.classNames.hidden].filter(Boolean).join(" ")},i)},createBadge(e){if(z(e))return null;const t=ee("span",{class:this.config.classNames.menu.value});return t.appendChild(ee("span",{class:this.config.classNames.menu.badge},e)),t},createButton(e,t){const i=J({},t);let s=Re(e);const n={element:"button",toggle:!1,label:null,icon:null,labelPressed:null,iconPressed:null};switch(["element","icon","label"].forEach((e=>{Object.keys(i).includes(e)&&(n[e]=i[e],delete i[e])})),"button"!==n.element||Object.keys(i).includes("type")||(i.type="button"),Object.keys(i).includes("class")?i.class.split(" ").some((e=>e===this.config.classNames.control))||J(i,{class:`${i.class} ${this.config.classNames.control}`}):i.class=this.config.classNames.control,e){case"play":n.toggle=!0,n.label="play",n.labelPressed="pause",n.icon="play",n.iconPressed="pause";break;case"mute":n.toggle=!0,n.label="mute",n.labelPressed="unmute",n.icon="volume",n.iconPressed="muted";break;case"captions":n.toggle=!0,n.label="enableCaptions",n.labelPressed="disableCaptions",n.icon="captions-off",n.iconPressed="captions-on";break;case"fullscreen":n.toggle=!0,n.label="enterFullscreen",n.labelPressed="exitFullscreen",n.icon="enter-fullscreen",n.iconPressed="exit-fullscreen";break;case"play-large":i.class+=` ${this.config.classNames.control}--overlaid`,s="play",n.label="play",n.icon="play";break;default:z(n.label)&&(n.label=s),z(n.icon)&&(n.icon=e)}const a=ee(n.element);return n.toggle?(a.appendChild(ze.createIcon.call(this,n.iconPressed,{class:"icon--pressed"})),a.appendChild(ze.createIcon.call(this,n.icon,{class:"icon--not-pressed"})),a.appendChild(ze.createLabel.call(this,n.labelPressed,{class:"label--pressed"})),a.appendChild(ze.createLabel.call(this,n.label,{class:"label--not-pressed"}))):(a.appendChild(ze.createIcon.call(this,n.icon)),a.appendChild(ze.createLabel.call(this,n.label))),J(i,ae(this.config.selectors.buttons[s],i)),Z(a,i),"play"===s?(q(this.elements.buttons[s])||(this.elements.buttons[s]=[]),this.elements.buttons[s].push(a)):this.elements.buttons[s]=a,a},createRange(e,t){const i=ee("input",J(ae(this.config.selectors.inputs[e]),{type:"range",min:0,max:100,step:.01,value:0,autocomplete:"off",role:"slider","aria-label":He.get(e,this.config),"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":0},t));return this.elements.inputs[e]=i,ze.updateRangeFill.call(this,i),k.setup(i),i},createProgress(e,t){const i=ee("progress",J(ae(this.config.selectors.display[e]),{min:0,max:100,value:0,role:"progressbar","aria-hidden":!0},t));if("volume"!==e){i.appendChild(ee("span",null,"0"));const t={played:"played",buffer:"buffered"}[e],s=t?He.get(t,this.config):"";i.innerText=`% ${s.toLowerCase()}`}return this.elements.display[e]=i,i},createTime(e,t){const i=ae(this.config.selectors.display[e],t),s=ee("div",J(i,{class:`${i.class?i.class:""} ${this.config.classNames.display.time} `.trim(),"aria-label":He.get(e,this.config)}),"00:00");return this.elements.display[e]=s,s},bindMenuItemShortcuts(e,t){be.call(this,e,"keydown keyup",(i=>{if(![32,38,39,40].includes(i.which))return;if(i.preventDefault(),i.stopPropagation(),"keydown"===i.type)return;const s=ce(e,'[role="menuitemradio"]');if(!s&&[32,39].includes(i.which))ze.showMenuPanel.call(this,t,!0);else{let t;32!==i.which&&(40===i.which||s&&39===i.which?(t=e.nextElementSibling,H(t)||(t=e.parentNode.firstElementChild)):(t=e.previousElementSibling,H(t)||(t=e.parentNode.lastElementChild)),de.call(this,t,!0))}}),!1),be.call(this,e,"keyup",(e=>{13===e.which&&ze.focusFirstMenuItem.call(this,null,!0)}))},createMenuItem({value:e,list:t,type:i,title:s,badge:n=null,checked:a=!1}){const r=ae(this.config.selectors.inputs[i]),o=ee("button",J(r,{type:"button",role:"menuitemradio",class:`${this.config.classNames.control} ${r.class?r.class:""}`.trim(),"aria-checked":a,value:e})),l=ee("span");l.innerHTML=s,H(n)&&l.appendChild(n),o.appendChild(l),Object.defineProperty(o,"checked",{enumerable:!0,get:()=>"true"===o.getAttribute("aria-checked"),set(e){e&&Array.from(o.parentNode.children).filter((e=>ce(e,'[role="menuitemradio"]'))).forEach((e=>e.setAttribute("aria-checked","false"))),o.setAttribute("aria-checked",e?"true":"false")}}),this.listeners.bind(o,"click keyup",(t=>{if(!V(t)||32===t.which){switch(t.preventDefault(),t.stopPropagation(),o.checked=!0,i){case"language":this.currentTrack=Number(e);break;case"quality":this.quality=e;break;case"speed":this.speed=parseFloat(e)}ze.showMenuPanel.call(this,"home",V(t))}}),i,!1),ze.bindMenuItemShortcuts.call(this,o,i),t.appendChild(o)},formatTime(e=0,t=!1){if(!$(e))return e;return We(e,Be(this.duration)>0,t)},updateTimeDisplay(e=null,t=0,i=!1){H(e)&&$(t)&&(e.innerText=ze.formatTime(t,i))},updateVolume(){this.supported.ui&&(H(this.elements.inputs.volume)&&ze.setRange.call(this,this.elements.inputs.volume,this.muted?0:this.volume),H(this.elements.buttons.mute)&&(this.elements.buttons.mute.pressed=this.muted||0===this.volume))},setRange(e,t=0){H(e)&&(e.value=t,ze.updateRangeFill.call(this,e))},updateProgress(e){if(!this.supported.ui||!F(e))return;let t=0;const i=(e,t)=>{const i=$(t)?t:0,s=H(e)?e:this.elements.display.buffer;if(H(s)){s.value=i;const e=s.getElementsByTagName("span")[0];H(e)&&(e.childNodes[0].nodeValue=i)}};if(e)switch(e.type){case"timeupdate":case"seeking":case"seeked":s=this.currentTime,n=this.duration,t=0===s||0===n||Number.isNaN(s)||Number.isNaN(n)?0:(s/n*100).toFixed(2),"timeupdate"===e.type&&ze.setRange.call(this,this.elements.inputs.seek,t);break;case"playing":case"progress":i(this.elements.display.buffer,100*this.buffered)}var s,n},updateRangeFill(e){const t=F(e)?e.target:e;if(H(t)&&"range"===t.getAttribute("type")){if(ce(t,this.config.selectors.inputs.seek)){t.setAttribute("aria-valuenow",this.currentTime);const e=ze.formatTime(this.currentTime),i=ze.formatTime(this.duration),s=He.get("seekLabel",this.config);t.setAttribute("aria-valuetext",s.replace("{currentTime}",e).replace("{duration}",i))}else if(ce(t,this.config.selectors.inputs.volume)){const e=100*t.value;t.setAttribute("aria-valuenow",e),t.setAttribute("aria-valuetext",`${e.toFixed(1)}%`)}else t.setAttribute("aria-valuenow",t.value);Q.isWebkit&&t.style.setProperty("--value",t.value/t.max*100+"%")}},updateSeekTooltip(e){if(!this.config.tooltips.seek||!H(this.elements.inputs.seek)||!H(this.elements.display.seekTooltip)||0===this.duration)return;const t=`${this.config.classNames.tooltip}--visible`,i=e=>oe(this.elements.display.seekTooltip,t,e);if(this.touch)return void i(!1);let s=0;const n=this.elements.progress.getBoundingClientRect();if(F(e))s=100/n.width*(e.pageX-n.left);else{if(!le(this.elements.display.seekTooltip,t))return;s=parseFloat(this.elements.display.seekTooltip.style.left,10)}s<0?s=0:s>100&&(s=100),ze.updateTimeDisplay.call(this,this.elements.display.seekTooltip,this.duration/100*s),this.elements.display.seekTooltip.style.left=`${s}%`,F(e)&&["mouseenter","mouseleave"].includes(e.type)&&i("mouseenter"===e.type)},timeUpdate(e){const t=!H(this.elements.display.duration)&&this.config.invertTime;ze.updateTimeDisplay.call(this,this.elements.display.currentTime,t?this.duration-this.currentTime:this.currentTime,t),e&&"timeupdate"===e.type&&this.media.seeking||ze.updateProgress.call(this,e)},durationUpdate(){if(!this.supported.ui||!this.config.invertTime&&this.currentTime)return;if(this.duration>=2**32)return re(this.elements.display.currentTime,!0),void re(this.elements.progress,!0);H(this.elements.inputs.seek)&&this.elements.inputs.seek.setAttribute("aria-valuemax",this.duration);const e=H(this.elements.display.duration);!e&&this.config.displayDuration&&this.paused&&ze.updateTimeDisplay.call(this,this.elements.display.currentTime,this.duration),e&&ze.updateTimeDisplay.call(this,this.elements.display.duration,this.duration),ze.updateSeekTooltip.call(this)},toggleMenuButton(e,t){re(this.elements.settings.buttons[e],!t)},updateSetting(e,t,i){const s=this.elements.settings.panels[e];let n=null,a=t;if("captions"===e)n=this.currentTrack;else{if(n=z(i)?this[e]:i,z(n)&&(n=this.config[e].default),!z(this.options[e])&&!this.options[e].includes(n))return void this.debug.warn(`Unsupported value of '${n}' for ${e}`);if(!this.config[e].options.includes(n))return void this.debug.warn(`Disabled value of '${n}' for ${e}`)}if(H(a)||(a=s&&s.querySelector('[role="menu"]')),!H(a))return;this.elements.settings.buttons[e].querySelector(`.${this.config.classNames.menu.value}`).innerHTML=ze.getLabel.call(this,e,n);const r=a&&a.querySelector(`[value="${n}"]`);H(r)&&(r.checked=!0)},getLabel(e,t){switch(e){case"speed":return 1===t?He.get("normal",this.config):`${t}×`;case"quality":if($(t)){const e=He.get(`qualityLabel.${t}`,this.config);return e.length?e:`${t}p`}return je(t);case"captions":return Qe.getLabel.call(this);default:return null}},setQualityMenu(e){if(!H(this.elements.settings.panels.quality))return;const t="quality",i=this.elements.settings.panels.quality.querySelector('[role="menu"]');q(e)&&(this.options.quality=Ee(e).filter((e=>this.config.quality.options.includes(e))));const s=!z(this.options.quality)&&this.options.quality.length>1;if(ze.toggleMenuButton.call(this,t,s),se(i),ze.checkMenu.call(this),!s)return;const n=e=>{const t=He.get(`qualityBadge.${e}`,this.config);return t.length?ze.createBadge.call(this,t):null};this.options.quality.sort(((e,t)=>{const i=this.config.quality.options;return i.indexOf(e)>i.indexOf(t)?1:-1})).forEach((e=>{ze.createMenuItem.call(this,{value:e,list:i,type:t,title:ze.getLabel.call(this,"quality",e),badge:n(e)})})),ze.updateSetting.call(this,t,i)},setCaptionsMenu(){if(!H(this.elements.settings.panels.captions))return;const e="captions",t=this.elements.settings.panels.captions.querySelector('[role="menu"]'),i=Qe.getTracks.call(this),s=Boolean(i.length);if(ze.toggleMenuButton.call(this,e,s),se(t),ze.checkMenu.call(this),!s)return;const n=i.map(((e,i)=>({value:i,checked:this.captions.toggled&&this.currentTrack===i,title:Qe.getLabel.call(this,e),badge:e.language&&ze.createBadge.call(this,e.language.toUpperCase()),list:t,type:"language"})));n.unshift({value:-1,checked:!this.captions.toggled,title:He.get("disabled",this.config),list:t,type:"language"}),n.forEach(ze.createMenuItem.bind(this)),ze.updateSetting.call(this,e,t)},setSpeedMenu(){if(!H(this.elements.settings.panels.speed))return;const e="speed",t=this.elements.settings.panels.speed.querySelector('[role="menu"]');this.options.speed=this.options.speed.filter((e=>e>=this.minimumSpeed&&e<=this.maximumSpeed));const i=!z(this.options.speed)&&this.options.speed.length>1;ze.toggleMenuButton.call(this,e,i),se(t),ze.checkMenu.call(this),i&&(this.options.speed.forEach((i=>{ze.createMenuItem.call(this,{value:i,list:t,type:e,title:ze.getLabel.call(this,"speed",i)})})),ze.updateSetting.call(this,e,t))},checkMenu(){const{buttons:e}=this.elements.settings,t=!z(e)&&Object.values(e).some((e=>!e.hidden));re(this.elements.settings.menu,!t)},focusFirstMenuItem(e,t=!1){if(this.elements.settings.popup.hidden)return;let i=e;H(i)||(i=Object.values(this.elements.settings.panels).find((e=>!e.hidden)));const s=i.querySelector('[role^="menuitem"]');de.call(this,s,t)},toggleMenu(e){const{popup:t}=this.elements.settings,i=this.elements.buttons.settings;if(!H(t)||!H(i))return;const{hidden:s}=t;let n=s;if(j(e))n=e;else if(V(e)&&27===e.which)n=!1;else if(F(e)){const s=R(e.composedPath)?e.composedPath()[0]:e.target,a=t.contains(s);if(a||!a&&e.target!==i&&n)return}i.setAttribute("aria-expanded",n),re(t,!n),oe(this.elements.container,this.config.classNames.menu.open,n),n&&V(e)?ze.focusFirstMenuItem.call(this,null,!0):n||s||de.call(this,i,V(e))},getMenuSize(e){const t=e.cloneNode(!0);t.style.position="absolute",t.style.opacity=0,t.removeAttribute("hidden"),e.parentNode.appendChild(t);const i=t.scrollWidth,s=t.scrollHeight;return ie(t),{width:i,height:s}},showMenuPanel(e="",t=!1){const i=this.elements.container.querySelector(`#plyr-settings-${this.id}-${e}`);if(!H(i))return;const s=i.parentNode,n=Array.from(s.children).find((e=>!e.hidden));if(me.transitions&&!me.reducedMotion){s.style.width=`${n.scrollWidth}px`,s.style.height=`${n.scrollHeight}px`;const e=ze.getMenuSize.call(this,i),t=e=>{e.target===s&&["width","height"].includes(e.propertyName)&&(s.style.width="",s.style.height="",ye.call(this,s,K,t))};be.call(this,s,K,t),s.style.width=`${e.width}px`,s.style.height=`${e.height}px`}re(n,!0),re(i,!1),ze.focusFirstMenuItem.call(this,i,t)},setDownloadUrl(){const e=this.elements.buttons.download;H(e)&&e.setAttribute("href",this.download)},create(e){const{bindMenuItemShortcuts:t,createButton:i,createProgress:s,createRange:n,createTime:a,setQualityMenu:r,setSpeedMenu:o,showMenuPanel:l}=ze;this.elements.controls=null,q(this.config.controls)&&this.config.controls.includes("play-large")&&this.elements.container.appendChild(i.call(this,"play-large"));const c=ee("div",ae(this.config.selectors.controls.wrapper));this.elements.controls=c;const h={class:"plyr__controls__item"};return Ee(q(this.config.controls)?this.config.controls:[]).forEach((r=>{if("restart"===r&&c.appendChild(i.call(this,"restart",h)),"rewind"===r&&c.appendChild(i.call(this,"rewind",h)),"play"===r&&c.appendChild(i.call(this,"play",h)),"fast-forward"===r&&c.appendChild(i.call(this,"fast-forward",h)),"progress"===r){const t=ee("div",{class:`${h.class} plyr__progress__container`}),i=ee("div",ae(this.config.selectors.progress));if(i.appendChild(n.call(this,"seek",{id:`plyr-seek-${e.id}`})),i.appendChild(s.call(this,"buffer")),this.config.tooltips.seek){const e=ee("span",{class:this.config.classNames.tooltip},"00:00");i.appendChild(e),this.elements.display.seekTooltip=e}this.elements.progress=i,t.appendChild(this.elements.progress),c.appendChild(t)}if("current-time"===r&&c.appendChild(a.call(this,"currentTime",h)),"duration"===r&&c.appendChild(a.call(this,"duration",h)),"mute"===r||"volume"===r){let{volume:t}=this.elements;if(H(t)&&c.contains(t)||(t=ee("div",J({},h,{class:`${h.class} plyr__volume`.trim()})),this.elements.volume=t,c.appendChild(t)),"mute"===r&&t.appendChild(i.call(this,"mute")),"volume"===r&&!Q.isIos){const i={max:1,step:.05,value:this.config.volume};t.appendChild(n.call(this,"volume",J(i,{id:`plyr-volume-${e.id}`})))}}if("captions"===r&&c.appendChild(i.call(this,"captions",h)),"settings"===r&&!z(this.config.settings)){const s=ee("div",J({},h,{class:`${h.class} plyr__menu`.trim(),hidden:""}));s.appendChild(i.call(this,"settings",{"aria-haspopup":!0,"aria-controls":`plyr-settings-${e.id}`,"aria-expanded":!1}));const n=ee("div",{class:"plyr__menu__container",id:`plyr-settings-${e.id}`,hidden:""}),a=ee("div"),r=ee("div",{id:`plyr-settings-${e.id}-home`}),o=ee("div",{role:"menu"});r.appendChild(o),a.appendChild(r),this.elements.settings.panels.home=r,this.config.settings.forEach((i=>{const s=ee("button",J(ae(this.config.selectors.buttons.settings),{type:"button",class:`${this.config.classNames.control} ${this.config.classNames.control}--forward`,role:"menuitem","aria-haspopup":!0,hidden:""}));t.call(this,s,i),be.call(this,s,"click",(()=>{l.call(this,i,!1)}));const n=ee("span",null,He.get(i,this.config)),r=ee("span",{class:this.config.classNames.menu.value});r.innerHTML=e[i],n.appendChild(r),s.appendChild(n),o.appendChild(s);const c=ee("div",{id:`plyr-settings-${e.id}-${i}`,hidden:""}),h=ee("button",{type:"button",class:`${this.config.classNames.control} ${this.config.classNames.control}--back`});h.appendChild(ee("span",{"aria-hidden":!0},He.get(i,this.config))),h.appendChild(ee("span",{class:this.config.classNames.hidden},He.get("menuBack",this.config))),be.call(this,c,"keydown",(e=>{37===e.which&&(e.preventDefault(),e.stopPropagation(),l.call(this,"home",!0))}),!1),be.call(this,h,"click",(()=>{l.call(this,"home",!1)})),c.appendChild(h),c.appendChild(ee("div",{role:"menu"})),a.appendChild(c),this.elements.settings.buttons[i]=s,this.elements.settings.panels[i]=c})),n.appendChild(a),s.appendChild(n),c.appendChild(s),this.elements.settings.popup=n,this.elements.settings.menu=s}if("pip"===r&&me.pip&&c.appendChild(i.call(this,"pip",h)),"airplay"===r&&me.airplay&&c.appendChild(i.call(this,"airplay",h)),"download"===r){const e=J({},h,{element:"a",href:this.download,target:"_blank"});this.isHTML5&&(e.download="");const{download:t}=this.config.urls;!W(t)&&this.isEmbed&&J(e,{icon:`logo-${this.provider}`,label:this.provider}),c.appendChild(i.call(this,"download",e))}"fullscreen"===r&&c.appendChild(i.call(this,"fullscreen",h))})),this.isHTML5&&r.call(this,Ie.getQualityOptions.call(this)),o.call(this),c},inject(){if(this.config.loadSprite){const e=ze.getIconUrl.call(this);e.cors&&Ue(e.url,"sprite-plyr")}this.id=Math.floor(1e4*Math.random());let e=null;this.elements.controls=null;const t={id:this.id,seektime:this.config.seekTime,title:this.config.title};let i=!0;R(this.config.controls)&&(this.config.controls=this.config.controls.call(this,t)),this.config.controls||(this.config.controls=[]),H(this.config.controls)||O(this.config.controls)?e=this.config.controls:(e=ze.create.call(this,{id:this.id,seektime:this.config.seekTime,speed:this.speed,quality:this.quality,captions:Qe.getLabel.call(this)}),i=!1);let s;i&&O(this.config.controls)&&(e=(e=>{let i=e;return Object.entries(t).forEach((([e,t])=>{i=Oe(i,`{${e}}`,t)})),i})(e)),O(this.config.selectors.controls.container)&&(s=document.querySelector(this.config.selectors.controls.container)),H(s)||(s=this.elements.container);if(s[H(e)?"insertAdjacentElement":"insertAdjacentHTML"]("afterbegin",e),H(this.elements.controls)||ze.findElements.call(this),!z(this.elements.buttons)){const e=e=>{const t=this.config.classNames.controlPressed;Object.defineProperty(e,"pressed",{enumerable:!0,get:()=>le(e,t),set(i=!1){oe(e,t,i)}})};Object.values(this.elements.buttons).filter(Boolean).forEach((t=>{q(t)||D(t)?Array.from(t).filter(Boolean).forEach(e):e(t)}))}if(Q.isEdge&&Y(s),this.config.tooltips.controls){const{classNames:e,selectors:t}=this.config,i=`${t.controls.wrapper} ${t.labels} .${e.hidden}`,s=he.call(this,i);Array.from(s).forEach((e=>{oe(e,this.config.classNames.hidden,!1),oe(e,this.config.classNames.tooltip,!0)}))}}};function Ke(e,t=!0){let i=e;if(t){const e=document.createElement("a");e.href=i,i=e.href}try{return new URL(i)}catch(e){return null}}function Ye(e){const t=new URLSearchParams;return I(e)&&Object.entries(e).forEach((([e,i])=>{t.set(e,i)})),t}const Qe={setup(){if(!this.supported.ui)return;if(!this.isVideo||this.isYouTube||this.isHTML5&&!me.textTracks)return void(q(this.config.controls)&&this.config.controls.includes("settings")&&this.config.settings.includes("captions")&&ze.setCaptionsMenu.call(this));var e,t;if(H(this.elements.captions)||(this.elements.captions=ee("div",ae(this.config.selectors.captions)),e=this.elements.captions,t=this.elements.wrapper,H(e)&&H(t)&&t.parentNode.insertBefore(e,t.nextSibling)),Q.isIE&&window.URL){const e=this.media.querySelectorAll("track");Array.from(e).forEach((e=>{const t=e.getAttribute("src"),i=Ke(t);null!==i&&i.hostname!==window.location.href.hostname&&["http:","https:"].includes(i.protocol)&&Ve(t,"blob").then((t=>{e.setAttribute("src",window.URL.createObjectURL(t))})).catch((()=>{ie(e)}))}))}const i=Ee((navigator.languages||[navigator.language||navigator.userLanguage||"en"]).map((e=>e.split("-")[0])));let s=(this.storage.get("language")||this.config.captions.language||"auto").toLowerCase();"auto"===s&&([s]=i);let n=this.storage.get("captions");if(j(n)||({active:n}=this.config.captions),Object.assign(this.captions,{toggled:!1,active:n,language:s,languages:i}),this.isHTML5){const e=this.config.captions.update?"addtrack removetrack":"removetrack";be.call(this,this.media.textTracks,e,Qe.update.bind(this))}setTimeout(Qe.update.bind(this),0)},update(){const e=Qe.getTracks.call(this,!0),{active:t,language:i,meta:s,currentTrackNode:n}=this.captions,a=Boolean(e.find((e=>e.language===i)));this.isHTML5&&this.isVideo&&e.filter((e=>!s.get(e))).forEach((e=>{this.debug.log("Track added",e),s.set(e,{default:"showing"===e.mode}),"showing"===e.mode&&(e.mode="hidden"),be.call(this,e,"cuechange",(()=>Qe.updateCues.call(this)))})),(a&&this.language!==i||!e.includes(n))&&(Qe.setLanguage.call(this,i),Qe.toggle.call(this,t&&a)),this.elements&&oe(this.elements.container,this.config.classNames.captions.enabled,!z(e)),q(this.config.controls)&&this.config.controls.includes("settings")&&this.config.settings.includes("captions")&&ze.setCaptionsMenu.call(this)},toggle(e,t=!0){if(!this.supported.ui)return;const{toggled:i}=this.captions,s=this.config.classNames.captions.active,n=L(e)?!i:e;if(n!==i){if(t||(this.captions.active=n,this.storage.set({captions:n})),!this.language&&n&&!t){const e=Qe.getTracks.call(this),t=Qe.findTrack.call(this,[this.captions.language,...this.captions.languages],!0);return this.captions.language=t.language,void Qe.set.call(this,e.indexOf(t))}this.elements.buttons.captions&&(this.elements.buttons.captions.pressed=n),oe(this.elements.container,s,n),this.captions.toggled=n,ze.updateSetting.call(this,"captions"),we.call(this,this.media,n?"captionsenabled":"captionsdisabled")}setTimeout((()=>{n&&this.captions.toggled&&(this.captions.currentTrackNode.mode="hidden")}))},set(e,t=!0){const i=Qe.getTracks.call(this);if(-1!==e)if($(e))if(e in i){if(this.captions.currentTrack!==e){this.captions.currentTrack=e;const s=i[e],{language:n}=s||{};this.captions.currentTrackNode=s,ze.updateSetting.call(this,"captions"),t||(this.captions.language=n,this.storage.set({language:n})),this.isVimeo&&this.embed.enableTextTrack(n),we.call(this,this.media,"languagechange")}Qe.toggle.call(this,!0,t),this.isHTML5&&this.isVideo&&Qe.updateCues.call(this)}else this.debug.warn("Track not found",e);else this.debug.warn("Invalid caption argument",e);else Qe.toggle.call(this,!1,t)},setLanguage(e,t=!0){if(!O(e))return void this.debug.warn("Invalid language argument",e);const i=e.toLowerCase();this.captions.language=i;const s=Qe.getTracks.call(this),n=Qe.findTrack.call(this,[i]);Qe.set.call(this,s.indexOf(n),t)},getTracks(e=!1){return Array.from((this.media||{}).textTracks||[]).filter((t=>!this.isHTML5||e||this.captions.meta.has(t))).filter((e=>["captions","subtitles"].includes(e.kind)))},findTrack(e,t=!1){const i=Qe.getTracks.call(this),s=e=>Number((this.captions.meta.get(e)||{}).default),n=Array.from(i).sort(((e,t)=>s(t)-s(e)));let a;return e.every((e=>(a=n.find((t=>t.language===e)),!a))),a||(t?n[0]:void 0)},getCurrentTrack(){return Qe.getTracks.call(this)[this.currentTrack]},getLabel(e){let t=e;return!U(t)&&me.textTracks&&this.captions.toggled&&(t=Qe.getCurrentTrack.call(this)),U(t)?z(t.label)?z(t.language)?He.get("enabled",this.config):e.language.toUpperCase():t.label:He.get("disabled",this.config)},updateCues(e){if(!this.supported.ui)return;if(!H(this.elements.captions))return void this.debug.warn("No captions element to render to");if(!L(e)&&!Array.isArray(e))return void this.debug.warn("updateCues: Invalid input",e);let t=e;if(!t){const e=Qe.getCurrentTrack.call(this);t=Array.from((e||{}).activeCues||[]).map((e=>e.getCueAsHTML())).map(qe)}const i=t.map((e=>e.trim())).join("\n");if(i!==this.elements.captions.innerHTML){se(this.elements.captions);const e=ee("span",ae(this.config.selectors.caption));e.innerHTML=i,this.elements.captions.appendChild(e),we.call(this,this.media,"cuechange")}}},Xe={enabled:!0,title:"",debug:!1,autoplay:!1,autopause:!0,playsinline:!0,seekTime:10,volume:1,muted:!1,duration:null,displayDuration:!0,invertTime:!0,toggleInvert:!0,ratio:null,clickToPlay:!0,hideControls:!0,resetOnEnd:!1,disableContextMenu:!0,loadSprite:!0,iconPrefix:"plyr",iconUrl:"https://cdn.plyr.io/3.6.12/plyr.svg",blankVideo:"https://cdn.plyr.io/static/blank.mp4",quality:{default:576,options:[4320,2880,2160,1440,1080,720,576,480,360,240],forced:!1,onChange:null},loop:{active:!1},speed:{selected:1,options:[.5,.75,1,1.25,1.5,1.75,2,4]},keyboard:{focused:!0,global:!1},tooltips:{controls:!1,seek:!0},captions:{active:!1,language:"auto",update:!1},fullscreen:{enabled:!0,fallback:!0,iosNative:!1},storage:{enabled:!0,key:"plyr"},controls:["play-large","play","progress","current-time","mute","volume","captions","settings","pip","airplay","fullscreen"],settings:["captions","quality","speed"],i18n:{restart:"Restart",rewind:"Rewind {seektime}s",play:"Play",pause:"Pause",fastForward:"Forward {seektime}s",seek:"Seek",seekLabel:"{currentTime} of {duration}",played:"Played",buffered:"Buffered",currentTime:"Current time",duration:"Duration",volume:"Volume",mute:"Mute",unmute:"Unmute",enableCaptions:"Enable captions",disableCaptions:"Disable captions",download:"Download",enterFullscreen:"Enter fullscreen",exitFullscreen:"Exit fullscreen",frameTitle:"Player for {title}",captions:"Captions",settings:"Settings",pip:"PIP",menuBack:"Go back to previous menu",speed:"Speed",normal:"Normal",quality:"Quality",loop:"Loop",start:"Start",end:"End",all:"All",reset:"Reset",disabled:"Disabled",enabled:"Enabled",advertisement:"Ad",qualityBadge:{2160:"4K",1440:"HD",1080:"HD",720:"HD",576:"SD",480:"SD"}},urls:{download:null,vimeo:{sdk:"https://player.vimeo.com/api/player.js",iframe:"https://player.vimeo.com/video/{0}?{1}",api:"https://vimeo.com/api/oembed.json?url={0}"},youtube:{sdk:"https://www.youtube.com/iframe_api",api:"https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}"},googleIMA:{sdk:"https://imasdk.googleapis.com/js/sdkloader/ima3.js"}},listeners:{seek:null,play:null,pause:null,restart:null,rewind:null,fastForward:null,mute:null,volume:null,captions:null,download:null,fullscreen:null,pip:null,airplay:null,speed:null,quality:null,loop:null,language:null},events:["ended","progress","stalled","playing","waiting","canplay","canplaythrough","loadstart","loadeddata","loadedmetadata","timeupdate","volumechange","play","pause","error","seeking","seeked","emptied","ratechange","cuechange","download","enterfullscreen","exitfullscreen","captionsenabled","captionsdisabled","languagechange","controlshidden","controlsshown","ready","statechange","qualitychange","adsloaded","adscontentpause","adscontentresume","adstarted","adsmidpoint","adscomplete","adsallcomplete","adsimpression","adsclick"],selectors:{editable:"input, textarea, select, [contenteditable]",container:".plyr",controls:{container:null,wrapper:".plyr__controls"},labels:"[data-plyr]",buttons:{play:'[data-plyr="play"]',pause:'[data-plyr="pause"]',restart:'[data-plyr="restart"]',rewind:'[data-plyr="rewind"]',fastForward:'[data-plyr="fast-forward"]',mute:'[data-plyr="mute"]',captions:'[data-plyr="captions"]',download:'[data-plyr="download"]',fullscreen:'[data-plyr="fullscreen"]',pip:'[data-plyr="pip"]',airplay:'[data-plyr="airplay"]',settings:'[data-plyr="settings"]',loop:'[data-plyr="loop"]'},inputs:{seek:'[data-plyr="seek"]',volume:'[data-plyr="volume"]',speed:'[data-plyr="speed"]',language:'[data-plyr="language"]',quality:'[data-plyr="quality"]'},display:{currentTime:".plyr__time--current",duration:".plyr__time--duration",buffer:".plyr__progress__buffer",loop:".plyr__progress__loop",volume:".plyr__volume--display"},progress:".plyr__progress",captions:".plyr__captions",caption:".plyr__caption"},classNames:{type:"plyr--{0}",provider:"plyr--{0}",video:"plyr__video-wrapper",embed:"plyr__video-embed",videoFixedRatio:"plyr__video-wrapper--fixed-ratio",embedContainer:"plyr__video-embed__container",poster:"plyr__poster",posterEnabled:"plyr__poster-enabled",ads:"plyr__ads",control:"plyr__control",controlPressed:"plyr__control--pressed",playing:"plyr--playing",paused:"plyr--paused",stopped:"plyr--stopped",loading:"plyr--loading",hover:"plyr--hover",tooltip:"plyr__tooltip",cues:"plyr__cues",hidden:"plyr__sr-only",hideControls:"plyr--hide-controls",isIos:"plyr--is-ios",isTouch:"plyr--is-touch",uiSupported:"plyr--full-ui",noTransition:"plyr--no-transition",display:{time:"plyr__time"},menu:{value:"plyr__menu__value",badge:"plyr__badge",open:"plyr--menu-open"},captions:{enabled:"plyr--captions-enabled",active:"plyr--captions-active"},fullscreen:{enabled:"plyr--fullscreen-enabled",fallback:"plyr--fullscreen-fallback"},pip:{supported:"plyr--pip-supported",active:"plyr--pip-active"},airplay:{supported:"plyr--airplay-supported",active:"plyr--airplay-active"},tabFocus:"plyr__tab-focus",previewThumbnails:{thumbContainer:"plyr__preview-thumb",thumbContainerShown:"plyr__preview-thumb--is-shown",imageContainer:"plyr__preview-thumb__image-container",timeContainer:"plyr__preview-thumb__time-container",scrubbingContainer:"plyr__preview-scrubbing",scrubbingContainerShown:"plyr__preview-scrubbing--is-shown"}},attributes:{embed:{provider:"data-plyr-provider",id:"data-plyr-embed-id",hash:"data-plyr-embed-hash"}},ads:{enabled:!1,publisherId:"",tagUrl:""},previewThumbnails:{enabled:!1,src:""},vimeo:{byline:!1,portrait:!1,title:!1,speed:!0,transparent:!1,customControls:!0,referrerPolicy:null,premium:!1},youtube:{rel:0,showinfo:0,iv_load_policy:3,modestbranding:1,customControls:!0,noCookie:!1}},Je="picture-in-picture",Ge="inline",Ze={html5:"html5",youtube:"youtube",vimeo:"vimeo"},et="audio",tt="video";const it=()=>{};class st{constructor(e=!1){this.enabled=window.console&&e,this.enabled&&this.log("Debugging enabled")}get log(){return this.enabled?Function.prototype.bind.call(console.log,console):it}get warn(){return this.enabled?Function.prototype.bind.call(console.warn,console):it}get error(){return this.enabled?Function.prototype.bind.call(console.error,console):it}}class nt{constructor(e){t(this,"onChange",(()=>{if(!this.enabled)return;const e=this.player.elements.buttons.fullscreen;H(e)&&(e.pressed=this.active);const t=this.target===this.player.media?this.target:this.player.elements.container;we.call(this.player,t,this.active?"enterfullscreen":"exitfullscreen",!0)})),t(this,"toggleFallback",((e=!1)=>{if(e?this.scrollPosition={x:window.scrollX||0,y:window.scrollY||0}:window.scrollTo(this.scrollPosition.x,this.scrollPosition.y),document.body.style.overflow=e?"hidden":"",oe(this.target,this.player.config.classNames.fullscreen.fallback,e),Q.isIos){let t=document.head.querySelector('meta[name="viewport"]');const i="viewport-fit=cover";t||(t=document.createElement("meta"),t.setAttribute("name","viewport"));const s=O(t.content)&&t.content.includes(i);e?(this.cleanupViewport=!s,s||(t.content+=`,${i}`)):this.cleanupViewport&&(t.content=t.content.split(",").filter((e=>e.trim()!==i)).join(","))}this.onChange()})),t(this,"trapFocus",(e=>{if(Q.isIos||!this.active||"Tab"!==e.key||9!==e.keyCode)return;const t=document.activeElement,i=he.call(this.player,"a[href], button:not(:disabled), input:not(:disabled), [tabindex]"),[s]=i,n=i[i.length-1];t!==n||e.shiftKey?t===s&&e.shiftKey&&(n.focus(),e.preventDefault()):(s.focus(),e.preventDefault())})),t(this,"update",(()=>{if(this.enabled){let e;e=this.forceFallback?"Fallback (forced)":nt.native?"Native":"Fallback",this.player.debug.log(`${e} fullscreen enabled`)}else this.player.debug.log("Fullscreen not supported and fallback disabled");oe(this.player.elements.container,this.player.config.classNames.fullscreen.enabled,this.enabled)})),t(this,"enter",(()=>{this.enabled&&(Q.isIos&&this.player.config.fullscreen.iosNative?this.player.isVimeo?this.player.embed.requestFullscreen():this.target.webkitEnterFullscreen():!nt.native||this.forceFallback?this.toggleFallback(!0):this.prefix?z(this.prefix)||this.target[`${this.prefix}Request${this.property}`]():this.target.requestFullscreen({navigationUI:"hide"}))})),t(this,"exit",(()=>{if(this.enabled)if(Q.isIos&&this.player.config.fullscreen.iosNative)this.target.webkitExitFullscreen(),Ce(this.player.play());else if(!nt.native||this.forceFallback)this.toggleFallback(!1);else if(this.prefix){if(!z(this.prefix)){const e="moz"===this.prefix?"Cancel":"Exit";document[`${this.prefix}${e}${this.property}`]()}}else(document.cancelFullScreen||document.exitFullscreen).call(document)})),t(this,"toggle",(()=>{this.active?this.exit():this.enter()})),this.player=e,this.prefix=nt.prefix,this.property=nt.property,this.scrollPosition={x:0,y:0},this.forceFallback="force"===e.config.fullscreen.fallback,this.player.elements.fullscreen=e.config.fullscreen.container&&function(e,t){const{prototype:i}=Element;return(i.closest||function(){let e=this;do{if(ce.matches(e,t))return e;e=e.parentElement||e.parentNode}while(null!==e&&1===e.nodeType);return null}).call(e,t)}(this.player.elements.container,e.config.fullscreen.container),be.call(this.player,document,"ms"===this.prefix?"MSFullscreenChange":`${this.prefix}fullscreenchange`,(()=>{this.onChange()})),be.call(this.player,this.player.elements.container,"dblclick",(e=>{H(this.player.elements.controls)&&this.player.elements.controls.contains(e.target)||this.player.listeners.proxy(e,this.toggle,"fullscreen")})),be.call(this,this.player.elements.container,"keydown",(e=>this.trapFocus(e))),this.update()}static get native(){return!!(document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled)}get usingNative(){return nt.native&&!this.forceFallback}static get prefix(){if(R(document.exitFullscreen))return"";let e="";return["webkit","moz","ms"].some((t=>!(!R(document[`${t}ExitFullscreen`])&&!R(document[`${t}CancelFullScreen`]))&&(e=t,!0))),e}static get property(){return"moz"===this.prefix?"FullScreen":"Fullscreen"}get enabled(){return(nt.native||this.player.config.fullscreen.fallback)&&this.player.config.fullscreen.enabled&&this.player.supported.ui&&this.player.isVideo}get active(){if(!this.enabled)return!1;if(!nt.native||this.forceFallback)return le(this.target,this.player.config.classNames.fullscreen.fallback);const e=this.prefix?this.target.getRootNode()[`${this.prefix}${this.property}Element`]:this.target.getRootNode().fullscreenElement;return e&&e.shadowRoot?e===this.target.getRootNode().host:e===this.target}get target(){return Q.isIos&&this.player.config.fullscreen.iosNative?this.player.media:this.player.elements.fullscreen||this.player.elements.container}}function at(e,t=1){return new Promise(((i,s)=>{const n=new Image,a=()=>{delete n.onload,delete n.onerror,(n.naturalWidth>=t?i:s)(n)};Object.assign(n,{onload:a,onerror:a,src:e})}))}const rt={addStyleHook(){oe(this.elements.container,this.config.selectors.container.replace(".",""),!0),oe(this.elements.container,this.config.classNames.uiSupported,this.supported.ui)},toggleNativeControls(e=!1){e&&this.isHTML5?this.media.setAttribute("controls",""):this.media.removeAttribute("controls")},build(){if(this.listeners.media(),!this.supported.ui)return this.debug.warn(`Basic support only for ${this.provider} ${this.type}`),void rt.toggleNativeControls.call(this,!0);H(this.elements.controls)||(ze.inject.call(this),this.listeners.controls()),rt.toggleNativeControls.call(this),this.isHTML5&&Qe.setup.call(this),this.volume=null,this.muted=null,this.loop=null,this.quality=null,this.speed=null,ze.updateVolume.call(this),ze.timeUpdate.call(this),ze.durationUpdate.call(this),rt.checkPlaying.call(this),oe(this.elements.container,this.config.classNames.pip.supported,me.pip&&this.isHTML5&&this.isVideo),oe(this.elements.container,this.config.classNames.airplay.supported,me.airplay&&this.isHTML5),oe(this.elements.container,this.config.classNames.isIos,Q.isIos),oe(this.elements.container,this.config.classNames.isTouch,this.touch),this.ready=!0,setTimeout((()=>{we.call(this,this.media,"ready")}),0),rt.setTitle.call(this),this.poster&&rt.setPoster.call(this,this.poster,!1).catch((()=>{})),this.config.duration&&ze.durationUpdate.call(this)},setTitle(){let e=He.get("play",this.config);if(O(this.config.title)&&!z(this.config.title)&&(e+=`, ${this.config.title}`),Array.from(this.elements.buttons.play||[]).forEach((t=>{t.setAttribute("aria-label",e)})),this.isEmbed){const e=ue.call(this,"iframe");if(!H(e))return;const t=z(this.config.title)?"video":this.config.title,i=He.get("frameTitle",this.config);e.setAttribute("title",i.replace("{title}",t))}},togglePoster(e){oe(this.elements.container,this.config.classNames.posterEnabled,e)},setPoster(e,t=!0){return t&&this.poster?Promise.reject(new Error("Poster already set")):(this.media.setAttribute("data-poster",e),this.elements.poster.removeAttribute("hidden"),ke.call(this).then((()=>at(e))).catch((t=>{throw e===this.poster&&rt.togglePoster.call(this,!1),t})).then((()=>{if(e!==this.poster)throw new Error("setPoster cancelled by later call to setPoster")})).then((()=>(Object.assign(this.elements.poster.style,{backgroundImage:`url('${e}')`,backgroundSize:""}),rt.togglePoster.call(this,!0),e))))},checkPlaying(e){oe(this.elements.container,this.config.classNames.playing,this.playing),oe(this.elements.container,this.config.classNames.paused,this.paused),oe(this.elements.container,this.config.classNames.stopped,this.stopped),Array.from(this.elements.buttons.play||[]).forEach((e=>{Object.assign(e,{pressed:this.playing}),e.setAttribute("aria-label",He.get(this.playing?"pause":"play",this.config))})),F(e)&&"timeupdate"===e.type||rt.toggleControls.call(this)},checkLoading(e){this.loading=["stalled","waiting"].includes(e.type),clearTimeout(this.timers.loading),this.timers.loading=setTimeout((()=>{oe(this.elements.container,this.config.classNames.loading,this.loading),rt.toggleControls.call(this)}),this.loading?250:0)},toggleControls(e){const{controls:t}=this.elements;if(t&&this.config.hideControls){const i=this.touch&&this.lastSeekTime+2e3>Date.now();this.toggleControls(Boolean(e||this.loading||this.paused||t.pressed||t.hover||i))}},migrateStyles(){Object.values({...this.media.style}).filter((e=>!z(e)&&O(e)&&e.startsWith("--plyr"))).forEach((e=>{this.elements.container.style.setProperty(e,this.media.style.getPropertyValue(e)),this.media.style.removeProperty(e)})),z(this.media.style)&&this.media.removeAttribute("style")}};class ot{constructor(e){t(this,"firstTouch",(()=>{const{player:e}=this,{elements:t}=e;e.touch=!0,oe(t.container,e.config.classNames.isTouch,!0)})),t(this,"setTabFocus",(e=>{const{player:t}=this,{elements:i}=t;if(clearTimeout(this.focusTimer),"keydown"===e.type&&9!==e.which)return;"keydown"===e.type&&(this.lastKeyDown=e.timeStamp);const s=e.timeStamp-this.lastKeyDown<=20;("focus"!==e.type||s)&&((()=>{const e=t.config.classNames.tabFocus;oe(he.call(t,`.${e}`),e,!1)})(),"focusout"!==e.type&&(this.focusTimer=setTimeout((()=>{const e=document.activeElement;i.container.contains(e)&&oe(document.activeElement,t.config.classNames.tabFocus,!0)}),10)))})),t(this,"global",((e=!0)=>{const{player:t}=this;t.config.keyboard.global&&fe.call(t,window,"keydown keyup",this.handleKey,e,!1),fe.call(t,document.body,"click",this.toggleMenu,e),ve.call(t,document.body,"touchstart",this.firstTouch),fe.call(t,document.body,"keydown focus blur focusout",this.setTabFocus,e,!1,!0)})),t(this,"container",(()=>{const{player:e}=this,{config:t,elements:i,timers:s}=e;!t.keyboard.global&&t.keyboard.focused&&be.call(e,i.container,"keydown keyup",this.handleKey,!1),be.call(e,i.container,"mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen",(t=>{const{controls:n}=i;n&&"enterfullscreen"===t.type&&(n.pressed=!1,n.hover=!1);let a=0;["touchstart","touchmove","mousemove"].includes(t.type)&&(rt.toggleControls.call(e,!0),a=e.touch?3e3:2e3),clearTimeout(s.controls),s.controls=setTimeout((()=>rt.toggleControls.call(e,!1)),a)}));const n=()=>{if(!e.isVimeo||e.config.vimeo.premium)return;const t=i.wrapper,{active:s}=e.fullscreen,[n,a]=Me.call(e),r=Pe(`aspect-ratio: ${n} / ${a}`);if(!s)return void(r?(t.style.width=null,t.style.height=null):(t.style.maxWidth=null,t.style.margin=null));const[o,l]=[Math.max(document.documentElement.clientWidth||0,window.innerWidth||0),Math.max(document.documentElement.clientHeight||0,window.innerHeight||0)],c=o/l>n/a;r?(t.style.width=c?"auto":"100%",t.style.height=c?"100%":"auto"):(t.style.maxWidth=c?l/a*n+"px":null,t.style.margin=c?"0 auto":null)},a=()=>{clearTimeout(s.resized),s.resized=setTimeout(n,50)};be.call(e,i.container,"enterfullscreen exitfullscreen",(t=>{const{target:s}=e.fullscreen;if(s!==i.container)return;if(!e.isEmbed&&z(e.config.ratio))return;n();("enterfullscreen"===t.type?be:ye).call(e,window,"resize",a)}))})),t(this,"media",(()=>{const{player:e}=this,{elements:t}=e;if(be.call(e,e.media,"timeupdate seeking seeked",(t=>ze.timeUpdate.call(e,t))),be.call(e,e.media,"durationchange loadeddata loadedmetadata",(t=>ze.durationUpdate.call(e,t))),be.call(e,e.media,"ended",(()=>{e.isHTML5&&e.isVideo&&e.config.resetOnEnd&&(e.restart(),e.pause())})),be.call(e,e.media,"progress playing seeking seeked",(t=>ze.updateProgress.call(e,t))),be.call(e,e.media,"volumechange",(t=>ze.updateVolume.call(e,t))),be.call(e,e.media,"playing play pause ended emptied timeupdate",(t=>rt.checkPlaying.call(e,t))),be.call(e,e.media,"waiting canplay seeked playing",(t=>rt.checkLoading.call(e,t))),e.supported.ui&&e.config.clickToPlay&&!e.isAudio){const i=ue.call(e,`.${e.config.classNames.video}`);if(!H(i))return;be.call(e,t.container,"click",(s=>{([t.container,i].includes(s.target)||i.contains(s.target))&&(e.touch&&e.config.hideControls||(e.ended?(this.proxy(s,e.restart,"restart"),this.proxy(s,(()=>{Ce(e.play())}),"play")):this.proxy(s,(()=>{Ce(e.togglePlay())}),"play")))}))}e.supported.ui&&e.config.disableContextMenu&&be.call(e,t.wrapper,"contextmenu",(e=>{e.preventDefault()}),!1),be.call(e,e.media,"volumechange",(()=>{e.storage.set({volume:e.volume,muted:e.muted})})),be.call(e,e.media,"ratechange",(()=>{ze.updateSetting.call(e,"speed"),e.storage.set({speed:e.speed})})),be.call(e,e.media,"qualitychange",(t=>{ze.updateSetting.call(e,"quality",null,t.detail.quality)})),be.call(e,e.media,"ready qualitychange",(()=>{ze.setDownloadUrl.call(e)}));const i=e.config.events.concat(["keyup","keydown"]).join(" ");be.call(e,e.media,i,(i=>{let{detail:s={}}=i;"error"===i.type&&(s=e.media.error),we.call(e,t.container,i.type,!0,s)}))})),t(this,"proxy",((e,t,i)=>{const{player:s}=this,n=s.config.listeners[i];let a=!0;R(n)&&(a=n.call(s,e)),!1!==a&&R(t)&&t.call(s,e)})),t(this,"bind",((e,t,i,s,n=!0)=>{const{player:a}=this,r=a.config.listeners[s],o=R(r);be.call(a,e,t,(e=>this.proxy(e,i,s)),n&&!o)})),t(this,"controls",(()=>{const{player:e}=this,{elements:t}=e,i=Q.isIE?"change":"input";if(t.buttons.play&&Array.from(t.buttons.play).forEach((t=>{this.bind(t,"click",(()=>{Ce(e.togglePlay())}),"play")})),this.bind(t.buttons.restart,"click",e.restart,"restart"),this.bind(t.buttons.rewind,"click",(()=>{e.lastSeekTime=Date.now(),e.rewind()}),"rewind"),this.bind(t.buttons.fastForward,"click",(()=>{e.lastSeekTime=Date.now(),e.forward()}),"fastForward"),this.bind(t.buttons.mute,"click",(()=>{e.muted=!e.muted}),"mute"),this.bind(t.buttons.captions,"click",(()=>e.toggleCaptions())),this.bind(t.buttons.download,"click",(()=>{we.call(e,e.media,"download")}),"download"),this.bind(t.buttons.fullscreen,"click",(()=>{e.fullscreen.toggle()}),"fullscreen"),this.bind(t.buttons.pip,"click",(()=>{e.pip="toggle"}),"pip"),this.bind(t.buttons.airplay,"click",e.airplay,"airplay"),this.bind(t.buttons.settings,"click",(t=>{t.stopPropagation(),t.preventDefault(),ze.toggleMenu.call(e,t)}),null,!1),this.bind(t.buttons.settings,"keyup",(t=>{const i=t.which;[13,32].includes(i)&&(13!==i?(t.preventDefault(),t.stopPropagation(),ze.toggleMenu.call(e,t)):ze.focusFirstMenuItem.call(e,null,!0))}),null,!1),this.bind(t.settings.menu,"keydown",(t=>{27===t.which&&ze.toggleMenu.call(e,t)})),this.bind(t.inputs.seek,"mousedown mousemove",(e=>{const i=t.progress.getBoundingClientRect(),s=100/i.width*(e.pageX-i.left);e.currentTarget.setAttribute("seek-value",s)})),this.bind(t.inputs.seek,"mousedown mouseup keydown keyup touchstart touchend",(t=>{const i=t.currentTarget,s=t.keyCode?t.keyCode:t.which,n="play-on-seeked";if(V(t)&&39!==s&&37!==s)return;e.lastSeekTime=Date.now();const a=i.hasAttribute(n),r=["mouseup","touchend","keyup"].includes(t.type);a&&r?(i.removeAttribute(n),Ce(e.play())):!r&&e.playing&&(i.setAttribute(n,""),e.pause())})),Q.isIos){const t=he.call(e,'input[type="range"]');Array.from(t).forEach((e=>this.bind(e,i,(e=>Y(e.target)))))}this.bind(t.inputs.seek,i,(t=>{const i=t.currentTarget;let s=i.getAttribute("seek-value");z(s)&&(s=i.value),i.removeAttribute("seek-value"),e.currentTime=s/i.max*e.duration}),"seek"),this.bind(t.progress,"mouseenter mouseleave mousemove",(t=>ze.updateSeekTooltip.call(e,t))),this.bind(t.progress,"mousemove touchmove",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.startMove(t)})),this.bind(t.progress,"mouseleave touchend click",(()=>{const{previewThumbnails:t}=e;t&&t.loaded&&t.endMove(!1,!0)})),this.bind(t.progress,"mousedown touchstart",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.startScrubbing(t)})),this.bind(t.progress,"mouseup touchend",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.endScrubbing(t)})),Q.isWebkit&&Array.from(he.call(e,'input[type="range"]')).forEach((t=>{this.bind(t,"input",(t=>ze.updateRangeFill.call(e,t.target)))})),e.config.toggleInvert&&!H(t.display.duration)&&this.bind(t.display.currentTime,"click",(()=>{0!==e.currentTime&&(e.config.invertTime=!e.config.invertTime,ze.timeUpdate.call(e))})),this.bind(t.inputs.volume,i,(t=>{e.volume=t.target.value}),"volume"),this.bind(t.controls,"mouseenter mouseleave",(i=>{t.controls.hover=!e.touch&&"mouseenter"===i.type})),t.fullscreen&&Array.from(t.fullscreen.children).filter((e=>!e.contains(t.container))).forEach((i=>{this.bind(i,"mouseenter mouseleave",(i=>{t.controls&&(t.controls.hover=!e.touch&&"mouseenter"===i.type)}))})),this.bind(t.controls,"mousedown mouseup touchstart touchend touchcancel",(e=>{t.controls.pressed=["mousedown","touchstart"].includes(e.type)})),this.bind(t.controls,"focusin",(()=>{const{config:i,timers:s}=e;oe(t.controls,i.classNames.noTransition,!0),rt.toggleControls.call(e,!0),setTimeout((()=>{oe(t.controls,i.classNames.noTransition,!1)}),0);const n=this.touch?3e3:4e3;clearTimeout(s.controls),s.controls=setTimeout((()=>rt.toggleControls.call(e,!1)),n)})),this.bind(t.inputs.volume,"wheel",(t=>{const i=t.webkitDirectionInvertedFromDevice,[s,n]=[t.deltaX,-t.deltaY].map((e=>i?-e:e)),a=Math.sign(Math.abs(s)>Math.abs(n)?s:n);e.increaseVolume(a/50);const{volume:r}=e.media;(1===a&&r<1||-1===a&&r>0)&&t.preventDefault()}),"volume",!1)})),this.player=e,this.lastKey=null,this.focusTimer=null,this.lastKeyDown=null,this.handleKey=this.handleKey.bind(this),this.toggleMenu=this.toggleMenu.bind(this),this.setTabFocus=this.setTabFocus.bind(this),this.firstTouch=this.firstTouch.bind(this)}handleKey(e){const{player:t}=this,{elements:i}=t,s=e.keyCode?e.keyCode:e.which,n="keydown"===e.type,a=n&&s===this.lastKey;if(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;if(!$(s))return;if(n){const n=document.activeElement;if(H(n)){const{editable:s}=t.config.selectors,{seek:a}=i.inputs;if(n!==a&&ce(n,s))return;if(32===e.which&&ce(n,'button, [role^="menuitem"]'))return}switch([32,37,38,39,40,48,49,50,51,52,53,54,56,57,67,70,73,75,76,77,79].includes(s)&&(e.preventDefault(),e.stopPropagation()),s){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:a||(t.currentTime=t.duration/10*(s-48));break;case 32:case 75:a||Ce(t.togglePlay());break;case 38:t.increaseVolume(.1);break;case 40:t.decreaseVolume(.1);break;case 77:a||(t.muted=!t.muted);break;case 39:t.forward();break;case 37:t.rewind();break;case 70:t.fullscreen.toggle();break;case 67:a||t.toggleCaptions();break;case 76:t.loop=!t.loop}27===s&&!t.fullscreen.usingNative&&t.fullscreen.active&&t.fullscreen.toggle(),this.lastKey=s}else this.lastKey=null}toggleMenu(e){ze.toggleMenu.call(this.player,e)}}var lt=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e,t){e.exports=function(){var e=function(){},t={},i={},s={};function n(e,t){e=e.push?e:[e];var n,a,r,o=[],l=e.length,c=l;for(n=function(e,i){i.length&&o.push(e),--c||t(o)};l--;)a=e[l],(r=i[a])?n(a,r):(s[a]=s[a]||[]).push(n)}function a(e,t){if(e){var n=s[e];if(i[e]=t,n)for(;n.length;)n[0](e,t),n.splice(0,1)}}function r(t,i){t.call&&(t={success:t}),i.length?(t.error||e)(i):(t.success||e)(t)}function o(t,i,s,n){var a,r,l=document,c=s.async,h=(s.numRetries||0)+1,u=s.before||e,d=t.replace(/[\?|#].*$/,""),p=t.replace(/^(css|img)!/,"");n=n||0,/(^css!|\.css$)/.test(d)?((r=l.createElement("link")).rel="stylesheet",r.href=p,(a="hideFocus"in r)&&r.relList&&(a=0,r.rel="preload",r.as="style")):/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(d)?(r=l.createElement("img")).src=p:((r=l.createElement("script")).src=t,r.async=void 0===c||c),r.onload=r.onerror=r.onbeforeload=function(e){var l=e.type[0];if(a)try{r.sheet.cssText.length||(l="e")}catch(e){18!=e.code&&(l="e")}if("e"==l){if((n+=1)<h)return o(t,i,s,n)}else if("preload"==r.rel&&"style"==r.as)return r.rel="stylesheet";i(t,l,e.defaultPrevented)},!1!==u(t,r)&&l.head.appendChild(r)}function l(e,t,i){var s,n,a=(e=e.push?e:[e]).length,r=a,l=[];for(s=function(e,i,s){if("e"==i&&l.push(e),"b"==i){if(!s)return;l.push(e)}--a||t(l)},n=0;n<r;n++)o(e[n],s,i)}function c(e,i,s){var n,o;if(i&&i.trim&&(n=i),o=(n?s:i)||{},n){if(n in t)throw"LoadJS";t[n]=!0}function c(t,i){l(e,(function(e){r(o,e),t&&r({success:t,error:i},e),a(n,e)}),o)}if(o.returnPromise)return new Promise(c);c()}return c.ready=function(e,t){return n(e,(function(e){r(t,e)})),c},c.done=function(e){a(e,[])},c.reset=function(){t={},i={},s={}},c.isDefined=function(e){return e in t},c}()}));function ct(e){return new Promise(((t,i)=>{lt(e,{success:t,error:i})}))}function ht(e){e&&!this.embed.hasPlayed&&(this.embed.hasPlayed=!0),this.media.paused===e&&(this.media.paused=!e,we.call(this,this.media,e?"play":"pause"))}const ut={setup(){const e=this;oe(e.elements.wrapper,e.config.classNames.embed,!0),e.options.speed=e.config.speed.options,_e.call(e),I(window.Vimeo)?ut.ready.call(e):ct(e.config.urls.vimeo.sdk).then((()=>{ut.ready.call(e)})).catch((t=>{e.debug.warn("Vimeo SDK (player.js) failed to load",t)}))},ready(){const e=this,t=e.config.vimeo,{premium:i,referrerPolicy:s,...n}=t;let a=e.media.getAttribute("src"),r="";z(a)?(a=e.media.getAttribute(e.config.attributes.embed.id),r=e.media.getAttribute(e.config.attributes.embed.hash)):r=function(e){const t=e.match(/^.*(?:vimeo.com\/|video\/)(?:\d+)(?:\?.*&*h=|\/)+(?<hash>[\d,a-f]+)/);return t?t.groups.hash:null}(a);const o=r?{h:r}:{};i&&Object.assign(n,{controls:!1,sidedock:!1});const l=Ye({loop:e.config.loop.active,autoplay:e.autoplay,muted:e.muted,gesture:"media",playsinline:!this.config.fullscreen.iosNative,...o,...n}),c=z(h=a)?null:$(Number(h))?h:h.match(/^.*(vimeo.com\/|video\/)(\d+).*/)?RegExp.$2:h;var h;const u=ee("iframe"),d=$e(e.config.urls.vimeo.iframe,c,l);if(u.setAttribute("src",d),u.setAttribute("allowfullscreen",""),u.setAttribute("allow",["autoplay","fullscreen","picture-in-picture","encrypted-media","accelerometer","gyroscope"].join("; ")),z(s)||u.setAttribute("referrerPolicy",s),i||!t.customControls)u.setAttribute("data-poster",e.poster),e.media=ne(u,e.media);else{const t=ee("div",{class:e.config.classNames.embedContainer,"data-poster":e.poster});t.appendChild(u),e.media=ne(t,e.media)}t.customControls||Ve($e(e.config.urls.vimeo.api,d)).then((t=>{!z(t)&&t.thumbnail_url&&rt.setPoster.call(e,t.thumbnail_url).catch((()=>{}))})),e.embed=new window.Vimeo.Player(u,{autopause:e.config.autopause,muted:e.muted}),e.media.paused=!0,e.media.currentTime=0,e.supported.ui&&e.embed.disableTextTrack(),e.media.play=()=>(ht.call(e,!0),e.embed.play()),e.media.pause=()=>(ht.call(e,!1),e.embed.pause()),e.media.stop=()=>{e.pause(),e.currentTime=0};let{currentTime:p}=e.media;Object.defineProperty(e.media,"currentTime",{get:()=>p,set(t){const{embed:i,media:s,paused:n,volume:a}=e,r=n&&!i.hasPlayed;s.seeking=!0,we.call(e,s,"seeking"),Promise.resolve(r&&i.setVolume(0)).then((()=>i.setCurrentTime(t))).then((()=>r&&i.pause())).then((()=>r&&i.setVolume(a))).catch((()=>{}))}});let m=e.config.speed.selected;Object.defineProperty(e.media,"playbackRate",{get:()=>m,set(t){e.embed.setPlaybackRate(t).then((()=>{m=t,we.call(e,e.media,"ratechange")})).catch((()=>{e.options.speed=[1]}))}});let{volume:g}=e.config;Object.defineProperty(e.media,"volume",{get:()=>g,set(t){e.embed.setVolume(t).then((()=>{g=t,we.call(e,e.media,"volumechange")}))}});let{muted:f}=e.config;Object.defineProperty(e.media,"muted",{get:()=>f,set(t){const i=!!j(t)&&t;e.embed.setVolume(i?0:e.config.volume).then((()=>{f=i,we.call(e,e.media,"volumechange")}))}});let b,{loop:y}=e.config;Object.defineProperty(e.media,"loop",{get:()=>y,set(t){const i=j(t)?t:e.config.loop.active;e.embed.setLoop(i).then((()=>{y=i}))}}),e.embed.getVideoUrl().then((t=>{b=t,ze.setDownloadUrl.call(e)})).catch((e=>{this.debug.warn(e)})),Object.defineProperty(e.media,"currentSrc",{get:()=>b}),Object.defineProperty(e.media,"ended",{get:()=>e.currentTime===e.duration}),Promise.all([e.embed.getVideoWidth(),e.embed.getVideoHeight()]).then((t=>{const[i,s]=t;e.embed.ratio=Le(i,s),_e.call(this)})),e.embed.setAutopause(e.config.autopause).then((t=>{e.config.autopause=t})),e.embed.getVideoTitle().then((t=>{e.config.title=t,rt.setTitle.call(this)})),e.embed.getCurrentTime().then((t=>{p=t,we.call(e,e.media,"timeupdate")})),e.embed.getDuration().then((t=>{e.media.duration=t,we.call(e,e.media,"durationchange")})),e.embed.getTextTracks().then((t=>{e.media.textTracks=t,Qe.setup.call(e)})),e.embed.on("cuechange",(({cues:t=[]})=>{const i=t.map((e=>function(e){const t=document.createDocumentFragment(),i=document.createElement("div");return t.appendChild(i),i.innerHTML=e,t.firstChild.innerText}(e.text)));Qe.updateCues.call(e,i)})),e.embed.on("loaded",(()=>{if(e.embed.getPaused().then((t=>{ht.call(e,!t),t||we.call(e,e.media,"playing")})),H(e.embed.element)&&e.supported.ui){e.embed.element.setAttribute("tabindex",-1)}})),e.embed.on("bufferstart",(()=>{we.call(e,e.media,"waiting")})),e.embed.on("bufferend",(()=>{we.call(e,e.media,"playing")})),e.embed.on("play",(()=>{ht.call(e,!0),we.call(e,e.media,"playing")})),e.embed.on("pause",(()=>{ht.call(e,!1)})),e.embed.on("timeupdate",(t=>{e.media.seeking=!1,p=t.seconds,we.call(e,e.media,"timeupdate")})),e.embed.on("progress",(t=>{e.media.buffered=t.percent,we.call(e,e.media,"progress"),1===parseInt(t.percent,10)&&we.call(e,e.media,"canplaythrough"),e.embed.getDuration().then((t=>{t!==e.media.duration&&(e.media.duration=t,we.call(e,e.media,"durationchange"))}))})),e.embed.on("seeked",(()=>{e.media.seeking=!1,we.call(e,e.media,"seeked")})),e.embed.on("ended",(()=>{e.media.paused=!0,we.call(e,e.media,"ended")})),e.embed.on("error",(t=>{e.media.error=t,we.call(e,e.media,"error")})),t.customControls&&setTimeout((()=>rt.build.call(e)),0)}};function dt(e){e&&!this.embed.hasPlayed&&(this.embed.hasPlayed=!0),this.media.paused===e&&(this.media.paused=!e,we.call(this,this.media,e?"play":"pause"))}function pt(e){return e.noCookie?"https://www.youtube-nocookie.com":"http:"===window.location.protocol?"http://www.youtube.com":void 0}const mt={setup(){if(oe(this.elements.wrapper,this.config.classNames.embed,!0),I(window.YT)&&R(window.YT.Player))mt.ready.call(this);else{const e=window.onYouTubeIframeAPIReady;window.onYouTubeIframeAPIReady=()=>{R(e)&&e(),mt.ready.call(this)},ct(this.config.urls.youtube.sdk).catch((e=>{this.debug.warn("YouTube API failed to load",e)}))}},getTitle(e){Ve($e(this.config.urls.youtube.api,e)).then((e=>{if(I(e)){const{title:t,height:i,width:s}=e;this.config.title=t,rt.setTitle.call(this),this.embed.ratio=Le(s,i)}_e.call(this)})).catch((()=>{_e.call(this)}))},ready(){const e=this,t=e.config.youtube,i=e.media&&e.media.getAttribute("id");if(!z(i)&&i.startsWith("youtube-"))return;let s=e.media.getAttribute("src");z(s)&&(s=e.media.getAttribute(this.config.attributes.embed.id));const n=z(a=s)?null:a.match(/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/)?RegExp.$2:a;var a;const r=ee("div",{id:`${e.provider}-${Math.floor(1e4*Math.random())}`,"data-poster":t.customControls?e.poster:void 0});if(e.media=ne(r,e.media),t.customControls){const t=e=>`https://i.ytimg.com/vi/${n}/${e}default.jpg`;at(t("maxres"),121).catch((()=>at(t("sd"),121))).catch((()=>at(t("hq")))).then((t=>rt.setPoster.call(e,t.src))).then((t=>{t.includes("maxres")||(e.elements.poster.style.backgroundSize="cover")})).catch((()=>{}))}e.embed=new window.YT.Player(e.media,{videoId:n,host:pt(t),playerVars:J({},{autoplay:e.config.autoplay?1:0,hl:e.config.hl,controls:e.supported.ui&&t.customControls?0:1,disablekb:1,playsinline:e.config.fullscreen.iosNative?0:1,cc_load_policy:e.captions.active?1:0,cc_lang_pref:e.config.captions.language,widget_referrer:window?window.location.href:null},t),events:{onError(t){if(!e.media.error){const i=t.data,s={2:"The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.",5:"The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.",100:"The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.",101:"The owner of the requested video does not allow it to be played in embedded players.",150:"The owner of the requested video does not allow it to be played in embedded players."}[i]||"An unknown error occured";e.media.error={code:i,message:s},we.call(e,e.media,"error")}},onPlaybackRateChange(t){const i=t.target;e.media.playbackRate=i.getPlaybackRate(),we.call(e,e.media,"ratechange")},onReady(i){if(R(e.media.play))return;const s=i.target;mt.getTitle.call(e,n),e.media.play=()=>{dt.call(e,!0),s.playVideo()},e.media.pause=()=>{dt.call(e,!1),s.pauseVideo()},e.media.stop=()=>{s.stopVideo()},e.media.duration=s.getDuration(),e.media.paused=!0,e.media.currentTime=0,Object.defineProperty(e.media,"currentTime",{get:()=>Number(s.getCurrentTime()),set(t){e.paused&&!e.embed.hasPlayed&&e.embed.mute(),e.media.seeking=!0,we.call(e,e.media,"seeking"),s.seekTo(t)}}),Object.defineProperty(e.media,"playbackRate",{get:()=>s.getPlaybackRate(),set(e){s.setPlaybackRate(e)}});let{volume:a}=e.config;Object.defineProperty(e.media,"volume",{get:()=>a,set(t){a=t,s.setVolume(100*a),we.call(e,e.media,"volumechange")}});let{muted:r}=e.config;Object.defineProperty(e.media,"muted",{get:()=>r,set(t){const i=j(t)?t:r;r=i,s[i?"mute":"unMute"](),s.setVolume(100*a),we.call(e,e.media,"volumechange")}}),Object.defineProperty(e.media,"currentSrc",{get:()=>s.getVideoUrl()}),Object.defineProperty(e.media,"ended",{get:()=>e.currentTime===e.duration});const o=s.getAvailablePlaybackRates();e.options.speed=o.filter((t=>e.config.speed.options.includes(t))),e.supported.ui&&t.customControls&&e.media.setAttribute("tabindex",-1),we.call(e,e.media,"timeupdate"),we.call(e,e.media,"durationchange"),clearInterval(e.timers.buffering),e.timers.buffering=setInterval((()=>{e.media.buffered=s.getVideoLoadedFraction(),(null===e.media.lastBuffered||e.media.lastBuffered<e.media.buffered)&&we.call(e,e.media,"progress"),e.media.lastBuffered=e.media.buffered,1===e.media.buffered&&(clearInterval(e.timers.buffering),we.call(e,e.media,"canplaythrough"))}),200),t.customControls&&setTimeout((()=>rt.build.call(e)),50)},onStateChange(i){const s=i.target;clearInterval(e.timers.playing);switch(e.media.seeking&&[1,2].includes(i.data)&&(e.media.seeking=!1,we.call(e,e.media,"seeked")),i.data){case-1:we.call(e,e.media,"timeupdate"),e.media.buffered=s.getVideoLoadedFraction(),we.call(e,e.media,"progress");break;case 0:dt.call(e,!1),e.media.loop?(s.stopVideo(),s.playVideo()):we.call(e,e.media,"ended");break;case 1:t.customControls&&!e.config.autoplay&&e.media.paused&&!e.embed.hasPlayed?e.media.pause():(dt.call(e,!0),we.call(e,e.media,"playing"),e.timers.playing=setInterval((()=>{we.call(e,e.media,"timeupdate")}),50),e.media.duration!==s.getDuration()&&(e.media.duration=s.getDuration(),we.call(e,e.media,"durationchange")));break;case 2:e.muted||e.embed.unMute(),dt.call(e,!1);break;case 3:we.call(e,e.media,"waiting")}we.call(e,e.elements.container,"statechange",!1,{code:i.data})}}})}},gt={setup(){this.media?(oe(this.elements.container,this.config.classNames.type.replace("{0}",this.type),!0),oe(this.elements.container,this.config.classNames.provider.replace("{0}",this.provider),!0),this.isEmbed&&oe(this.elements.container,this.config.classNames.type.replace("{0}","video"),!0),this.isVideo&&(this.elements.wrapper=ee("div",{class:this.config.classNames.video}),G(this.media,this.elements.wrapper),this.elements.poster=ee("div",{class:this.config.classNames.poster}),this.elements.wrapper.appendChild(this.elements.poster)),this.isHTML5?Ie.setup.call(this):this.isYouTube?mt.setup.call(this):this.isVimeo&&ut.setup.call(this)):this.debug.warn("No media element found!")}};class ft{constructor(e){t(this,"load",(()=>{this.enabled&&(I(window.google)&&I(window.google.ima)?this.ready():ct(this.player.config.urls.googleIMA.sdk).then((()=>{this.ready()})).catch((()=>{this.trigger("error",new Error("Google IMA SDK failed to load"))})))})),t(this,"ready",(()=>{var e;this.enabled||((e=this).manager&&e.manager.destroy(),e.elements.displayContainer&&e.elements.displayContainer.destroy(),e.elements.container.remove()),this.startSafetyTimer(12e3,"ready()"),this.managerPromise.then((()=>{this.clearSafetyTimer("onAdsManagerLoaded()")})),this.listeners(),this.setupIMA()})),t(this,"setupIMA",(()=>{this.elements.container=ee("div",{class:this.player.config.classNames.ads}),this.player.elements.container.appendChild(this.elements.container),google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED),google.ima.settings.setLocale(this.player.config.ads.language),google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline),this.elements.displayContainer=new google.ima.AdDisplayContainer(this.elements.container,this.player.media),this.loader=new google.ima.AdsLoader(this.elements.displayContainer),this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,(e=>this.onAdsManagerLoaded(e)),!1),this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,(e=>this.onAdError(e)),!1),this.requestAds()})),t(this,"requestAds",(()=>{const{container:e}=this.player.elements;try{const t=new google.ima.AdsRequest;t.adTagUrl=this.tagUrl,t.linearAdSlotWidth=e.offsetWidth,t.linearAdSlotHeight=e.offsetHeight,t.nonLinearAdSlotWidth=e.offsetWidth,t.nonLinearAdSlotHeight=e.offsetHeight,t.forceNonLinearFullSlot=!1,t.setAdWillPlayMuted(!this.player.muted),this.loader.requestAds(t)}catch(e){this.onAdError(e)}})),t(this,"pollCountdown",((e=!1)=>{if(!e)return clearInterval(this.countdownTimer),void this.elements.container.removeAttribute("data-badge-text");this.countdownTimer=setInterval((()=>{const e=We(Math.max(this.manager.getRemainingTime(),0)),t=`${He.get("advertisement",this.player.config)} - ${e}`;this.elements.container.setAttribute("data-badge-text",t)}),100)})),t(this,"onAdsManagerLoaded",(e=>{if(!this.enabled)return;const t=new google.ima.AdsRenderingSettings;t.restoreCustomPlaybackStateOnAdBreakComplete=!0,t.enablePreloading=!0,this.manager=e.getAdsManager(this.player,t),this.cuePoints=this.manager.getCuePoints(),this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,(e=>this.onAdError(e))),Object.keys(google.ima.AdEvent.Type).forEach((e=>{this.manager.addEventListener(google.ima.AdEvent.Type[e],(e=>this.onAdEvent(e)))})),this.trigger("loaded")})),t(this,"addCuePoints",(()=>{z(this.cuePoints)||this.cuePoints.forEach((e=>{if(0!==e&&-1!==e&&e<this.player.duration){const t=this.player.elements.progress;if(H(t)){const i=100/this.player.duration*e,s=ee("span",{class:this.player.config.classNames.cues});s.style.left=`${i.toString()}%`,t.appendChild(s)}}}))})),t(this,"onAdEvent",(e=>{const{container:t}=this.player.elements,i=e.getAd(),s=e.getAdData();switch((e=>{we.call(this.player,this.player.media,`ads${e.replace(/_/g,"").toLowerCase()}`)})(e.type),e.type){case google.ima.AdEvent.Type.LOADED:this.trigger("loaded"),this.pollCountdown(!0),i.isLinear()||(i.width=t.offsetWidth,i.height=t.offsetHeight);break;case google.ima.AdEvent.Type.STARTED:this.manager.setVolume(this.player.volume);break;case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:this.player.ended?this.loadAds():this.loader.contentComplete();break;case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:this.pauseContent();break;case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:this.pollCountdown(),this.resumeContent();break;case google.ima.AdEvent.Type.LOG:s.adError&&this.player.debug.warn(`Non-fatal ad error: ${s.adError.getMessage()}`)}})),t(this,"onAdError",(e=>{this.cancel(),this.player.debug.warn("Ads error",e)})),t(this,"listeners",(()=>{const{container:e}=this.player.elements;let t;this.player.on("canplay",(()=>{this.addCuePoints()})),this.player.on("ended",(()=>{this.loader.contentComplete()})),this.player.on("timeupdate",(()=>{t=this.player.currentTime})),this.player.on("seeked",(()=>{const e=this.player.currentTime;z(this.cuePoints)||this.cuePoints.forEach(((i,s)=>{t<i&&i<e&&(this.manager.discardAdBreak(),this.cuePoints.splice(s,1))}))})),window.addEventListener("resize",(()=>{this.manager&&this.manager.resize(e.offsetWidth,e.offsetHeight,google.ima.ViewMode.NORMAL)}))})),t(this,"play",(()=>{const{container:e}=this.player.elements;this.managerPromise||this.resumeContent(),this.managerPromise.then((()=>{this.manager.setVolume(this.player.volume),this.elements.displayContainer.initialize();try{this.initialized||(this.manager.init(e.offsetWidth,e.offsetHeight,google.ima.ViewMode.NORMAL),this.manager.start()),this.initialized=!0}catch(e){this.onAdError(e)}})).catch((()=>{}))})),t(this,"resumeContent",(()=>{this.elements.container.style.zIndex="",this.playing=!1,Ce(this.player.media.play())})),t(this,"pauseContent",(()=>{this.elements.container.style.zIndex=3,this.playing=!0,this.player.media.pause()})),t(this,"cancel",(()=>{this.initialized&&this.resumeContent(),this.trigger("error"),this.loadAds()})),t(this,"loadAds",(()=>{this.managerPromise.then((()=>{this.manager&&this.manager.destroy(),this.managerPromise=new Promise((e=>{this.on("loaded",e),this.player.debug.log(this.manager)})),this.initialized=!1,this.requestAds()})).catch((()=>{}))})),t(this,"trigger",((e,...t)=>{const i=this.events[e];q(i)&&i.forEach((e=>{R(e)&&e.apply(this,t)}))})),t(this,"on",((e,t)=>(q(this.events[e])||(this.events[e]=[]),this.events[e].push(t),this))),t(this,"startSafetyTimer",((e,t)=>{this.player.debug.log(`Safety timer invoked from: ${t}`),this.safetyTimer=setTimeout((()=>{this.cancel(),this.clearSafetyTimer("startSafetyTimer()")}),e)})),t(this,"clearSafetyTimer",(e=>{L(this.safetyTimer)||(this.player.debug.log(`Safety timer cleared from: ${e}`),clearTimeout(this.safetyTimer),this.safetyTimer=null)})),this.player=e,this.config=e.config.ads,this.playing=!1,this.initialized=!1,this.elements={container:null,displayContainer:null},this.manager=null,this.loader=null,this.cuePoints=null,this.events={},this.safetyTimer=null,this.countdownTimer=null,this.managerPromise=new Promise(((e,t)=>{this.on("loaded",e),this.on("error",t)})),this.load()}get enabled(){const{config:e}=this;return this.player.isHTML5&&this.player.isVideo&&e.enabled&&(!z(e.publisherId)||W(e.tagUrl))}get tagUrl(){const{config:e}=this;if(W(e.tagUrl))return e.tagUrl;return`https://go.aniview.com/api/adserver6/vast/?${Ye({AV_PUBLISHERID:"58c25bb0073ef448b1087ad6",AV_CHANNELID:"5a0458dc28a06145e4519d21",AV_URL:window.location.hostname,cb:Date.now(),AV_WIDTH:640,AV_HEIGHT:480,AV_CDIM2:e.publisherId})}`}}const bt=e=>{const t=[];return e.split(/\r\n\r\n|\n\n|\r\r/).forEach((e=>{const i={};e.split(/\r\n|\n|\r/).forEach((e=>{if($(i.startTime)){if(!z(e.trim())&&z(i.text)){const t=e.trim().split("#xywh=");[i.text]=t,t[1]&&([i.x,i.y,i.w,i.h]=t[1].split(","))}}else{const t=e.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})/);t&&(i.startTime=60*Number(t[1]||0)*60+60*Number(t[2])+Number(t[3])+Number(`0.${t[4]}`),i.endTime=60*Number(t[6]||0)*60+60*Number(t[7])+Number(t[8])+Number(`0.${t[9]}`))}})),i.text&&t.push(i)})),t},yt=(e,t)=>{const i={};return e>t.width/t.height?(i.width=t.width,i.height=1/e*t.width):(i.height=t.height,i.width=e*t.height),i};class vt{constructor(e){t(this,"load",(()=>{this.player.elements.display.seekTooltip&&(this.player.elements.display.seekTooltip.hidden=this.enabled),this.enabled&&this.getThumbnails().then((()=>{this.enabled&&(this.render(),this.determineContainerAutoSizing(),this.loaded=!0)}))})),t(this,"getThumbnails",(()=>new Promise((e=>{const{src:t}=this.player.config.previewThumbnails;if(z(t))throw new Error("Missing previewThumbnails.src config attribute");const i=()=>{this.thumbnails.sort(((e,t)=>e.height-t.height)),this.player.debug.log("Preview thumbnails",this.thumbnails),e()};if(R(t))t((e=>{this.thumbnails=e,i()}));else{const e=(O(t)?[t]:t).map((e=>this.getThumbnail(e)));Promise.all(e).then(i)}})))),t(this,"getThumbnail",(e=>new Promise((t=>{Ve(e).then((i=>{const s={frames:bt(i),height:null,urlPrefix:""};s.frames[0].text.startsWith("/")||s.frames[0].text.startsWith("http://")||s.frames[0].text.startsWith("https://")||(s.urlPrefix=e.substring(0,e.lastIndexOf("/")+1));const n=new Image;n.onload=()=>{s.height=n.naturalHeight,s.width=n.naturalWidth,this.thumbnails.push(s),t()},n.src=s.urlPrefix+s.frames[0].text}))})))),t(this,"startMove",(e=>{if(this.loaded&&F(e)&&["touchmove","mousemove"].includes(e.type)&&this.player.media.duration){if("touchmove"===e.type)this.seekTime=this.player.media.duration*(this.player.elements.inputs.seek.value/100);else{const t=this.player.elements.progress.getBoundingClientRect(),i=100/t.width*(e.pageX-t.left);this.seekTime=this.player.media.duration*(i/100),this.seekTime<0&&(this.seekTime=0),this.seekTime>this.player.media.duration-1&&(this.seekTime=this.player.media.duration-1),this.mousePosX=e.pageX,this.elements.thumb.time.innerText=We(this.seekTime)}this.showImageAtCurrentTime()}})),t(this,"endMove",(()=>{this.toggleThumbContainer(!1,!0)})),t(this,"startScrubbing",(e=>{(L(e.button)||!1===e.button||0===e.button)&&(this.mouseDown=!0,this.player.media.duration&&(this.toggleScrubbingContainer(!0),this.toggleThumbContainer(!1,!0),this.showImageAtCurrentTime()))})),t(this,"endScrubbing",(()=>{this.mouseDown=!1,Math.ceil(this.lastTime)===Math.ceil(this.player.media.currentTime)?this.toggleScrubbingContainer(!1):ve.call(this.player,this.player.media,"timeupdate",(()=>{this.mouseDown||this.toggleScrubbingContainer(!1)}))})),t(this,"listeners",(()=>{this.player.on("play",(()=>{this.toggleThumbContainer(!1,!0)})),this.player.on("seeked",(()=>{this.toggleThumbContainer(!1)})),this.player.on("timeupdate",(()=>{this.lastTime=this.player.media.currentTime}))})),t(this,"render",(()=>{this.elements.thumb.container=ee("div",{class:this.player.config.classNames.previewThumbnails.thumbContainer}),this.elements.thumb.imageContainer=ee("div",{class:this.player.config.classNames.previewThumbnails.imageContainer}),this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer);const e=ee("div",{class:this.player.config.classNames.previewThumbnails.timeContainer});this.elements.thumb.time=ee("span",{},"00:00"),e.appendChild(this.elements.thumb.time),this.elements.thumb.container.appendChild(e),H(this.player.elements.progress)&&this.player.elements.progress.appendChild(this.elements.thumb.container),this.elements.scrubbing.container=ee("div",{class:this.player.config.classNames.previewThumbnails.scrubbingContainer}),this.player.elements.wrapper.appendChild(this.elements.scrubbing.container)})),t(this,"destroy",(()=>{this.elements.thumb.container&&this.elements.thumb.container.remove(),this.elements.scrubbing.container&&this.elements.scrubbing.container.remove()})),t(this,"showImageAtCurrentTime",(()=>{this.mouseDown?this.setScrubbingContainerSize():this.setThumbContainerSizeAndPos();const e=this.thumbnails[0].frames.findIndex((e=>this.seekTime>=e.startTime&&this.seekTime<=e.endTime)),t=e>=0;let i=0;this.mouseDown||this.toggleThumbContainer(t),t&&(this.thumbnails.forEach(((t,s)=>{this.loadedImages.includes(t.frames[e].text)&&(i=s)})),e!==this.showingThumb&&(this.showingThumb=e,this.loadImage(i)))})),t(this,"loadImage",((e=0)=>{const t=this.showingThumb,i=this.thumbnails[e],{urlPrefix:s}=i,n=i.frames[t],a=i.frames[t].text,r=s+a;if(this.currentImageElement&&this.currentImageElement.dataset.filename===a)this.showImage(this.currentImageElement,n,e,t,a,!1),this.currentImageElement.dataset.index=t,this.removeOldImages(this.currentImageElement);else{this.loadingImage&&this.usingSprites&&(this.loadingImage.onload=null);const i=new Image;i.src=r,i.dataset.index=t,i.dataset.filename=a,this.showingThumbFilename=a,this.player.debug.log(`Loading image: ${r}`),i.onload=()=>this.showImage(i,n,e,t,a,!0),this.loadingImage=i,this.removeOldImages(i)}})),t(this,"showImage",((e,t,i,s,n,a=!0)=>{this.player.debug.log(`Showing thumb: ${n}. num: ${s}. qual: ${i}. newimg: ${a}`),this.setImageSizeAndOffset(e,t),a&&(this.currentImageContainer.appendChild(e),this.currentImageElement=e,this.loadedImages.includes(n)||this.loadedImages.push(n)),this.preloadNearby(s,!0).then(this.preloadNearby(s,!1)).then(this.getHigherQuality(i,e,t,n))})),t(this,"removeOldImages",(e=>{Array.from(this.currentImageContainer.children).forEach((t=>{if("img"!==t.tagName.toLowerCase())return;const i=this.usingSprites?500:1e3;if(t.dataset.index!==e.dataset.index&&!t.dataset.deleting){t.dataset.deleting=!0;const{currentImageContainer:e}=this;setTimeout((()=>{e.removeChild(t),this.player.debug.log(`Removing thumb: ${t.dataset.filename}`)}),i)}}))})),t(this,"preloadNearby",((e,t=!0)=>new Promise((i=>{setTimeout((()=>{const s=this.thumbnails[0].frames[e].text;if(this.showingThumbFilename===s){let n;n=t?this.thumbnails[0].frames.slice(e):this.thumbnails[0].frames.slice(0,e).reverse();let a=!1;n.forEach((e=>{const t=e.text;if(t!==s&&!this.loadedImages.includes(t)){a=!0,this.player.debug.log(`Preloading thumb filename: ${t}`);const{urlPrefix:e}=this.thumbnails[0],s=e+t,n=new Image;n.src=s,n.onload=()=>{this.player.debug.log(`Preloaded thumb filename: ${t}`),this.loadedImages.includes(t)||this.loadedImages.push(t),i()}}})),a||i()}}),300)})))),t(this,"getHigherQuality",((e,t,i,s)=>{if(e<this.thumbnails.length-1){let n=t.naturalHeight;this.usingSprites&&(n=i.h),n<this.thumbContainerHeight&&setTimeout((()=>{this.showingThumbFilename===s&&(this.player.debug.log(`Showing higher quality thumb for: ${s}`),this.loadImage(e+1))}),300)}})),t(this,"toggleThumbContainer",((e=!1,t=!1)=>{const i=this.player.config.classNames.previewThumbnails.thumbContainerShown;this.elements.thumb.container.classList.toggle(i,e),!e&&t&&(this.showingThumb=null,this.showingThumbFilename=null)})),t(this,"toggleScrubbingContainer",((e=!1)=>{const t=this.player.config.classNames.previewThumbnails.scrubbingContainerShown;this.elements.scrubbing.container.classList.toggle(t,e),e||(this.showingThumb=null,this.showingThumbFilename=null)})),t(this,"determineContainerAutoSizing",(()=>{(this.elements.thumb.imageContainer.clientHeight>20||this.elements.thumb.imageContainer.clientWidth>20)&&(this.sizeSpecifiedInCSS=!0)})),t(this,"setThumbContainerSizeAndPos",(()=>{if(this.sizeSpecifiedInCSS){if(this.elements.thumb.imageContainer.clientHeight>20&&this.elements.thumb.imageContainer.clientWidth<20){const e=Math.floor(this.elements.thumb.imageContainer.clientHeight*this.thumbAspectRatio);this.elements.thumb.imageContainer.style.width=`${e}px`}else if(this.elements.thumb.imageContainer.clientHeight<20&&this.elements.thumb.imageContainer.clientWidth>20){const e=Math.floor(this.elements.thumb.imageContainer.clientWidth/this.thumbAspectRatio);this.elements.thumb.imageContainer.style.height=`${e}px`}}else{const e=Math.floor(this.thumbContainerHeight*this.thumbAspectRatio);this.elements.thumb.imageContainer.style.height=`${this.thumbContainerHeight}px`,this.elements.thumb.imageContainer.style.width=`${e}px`}this.setThumbContainerPos()})),t(this,"setThumbContainerPos",(()=>{const e=this.player.elements.progress.getBoundingClientRect(),t=this.player.elements.container.getBoundingClientRect(),{container:i}=this.elements.thumb,s=t.left-e.left+10,n=t.right-e.left-i.clientWidth-10;let a=this.mousePosX-e.left-i.clientWidth/2;a<s&&(a=s),a>n&&(a=n),i.style.left=`${a}px`})),t(this,"setScrubbingContainerSize",(()=>{const{width:e,height:t}=yt(this.thumbAspectRatio,{width:this.player.media.clientWidth,height:this.player.media.clientHeight});this.elements.scrubbing.container.style.width=`${e}px`,this.elements.scrubbing.container.style.height=`${t}px`})),t(this,"setImageSizeAndOffset",((e,t)=>{if(!this.usingSprites)return;const i=this.thumbContainerHeight/t.h;e.style.height=e.naturalHeight*i+"px",e.style.width=e.naturalWidth*i+"px",e.style.left=`-${t.x*i}px`,e.style.top=`-${t.y*i}px`})),this.player=e,this.thumbnails=[],this.loaded=!1,this.lastMouseMoveTime=Date.now(),this.mouseDown=!1,this.loadedImages=[],this.elements={thumb:{},scrubbing:{}},this.load()}get enabled(){return this.player.isHTML5&&this.player.isVideo&&this.player.config.previewThumbnails.enabled}get currentImageContainer(){return this.mouseDown?this.elements.scrubbing.container:this.elements.thumb.imageContainer}get usingSprites(){return Object.keys(this.thumbnails[0].frames[0]).includes("w")}get thumbAspectRatio(){return this.usingSprites?this.thumbnails[0].frames[0].w/this.thumbnails[0].frames[0].h:this.thumbnails[0].width/this.thumbnails[0].height}get thumbContainerHeight(){if(this.mouseDown){const{height:e}=yt(this.thumbAspectRatio,{width:this.player.media.clientWidth,height:this.player.media.clientHeight});return e}return this.sizeSpecifiedInCSS?this.elements.thumb.imageContainer.clientHeight:Math.floor(this.player.media.clientWidth/this.thumbAspectRatio/4)}get currentImageElement(){return this.mouseDown?this.currentScrubbingImageElement:this.currentThumbnailImageElement}set currentImageElement(e){this.mouseDown?this.currentScrubbingImageElement=e:this.currentThumbnailImageElement=e}}const wt={insertElements(e,t){O(t)?te(e,this.media,{src:t}):q(t)&&t.forEach((t=>{te(e,this.media,t)}))},change(e){X(e,"sources.length")?(Ie.cancelRequests.call(this),this.destroy.call(this,(()=>{this.options.quality=[],ie(this.media),this.media=null,H(this.elements.container)&&this.elements.container.removeAttribute("class");const{sources:t,type:i}=e,[{provider:s=Ze.html5,src:n}]=t,a="html5"===s?i:"div",r="html5"===s?{}:{src:n};Object.assign(this,{provider:s,type:i,supported:me.check(i,s,this.config.playsinline),media:ee(a,r)}),this.elements.container.appendChild(this.media),j(e.autoplay)&&(this.config.autoplay=e.autoplay),this.isHTML5&&(this.config.crossorigin&&this.media.setAttribute("crossorigin",""),this.config.autoplay&&this.media.setAttribute("autoplay",""),z(e.poster)||(this.poster=e.poster),this.config.loop.active&&this.media.setAttribute("loop",""),this.config.muted&&this.media.setAttribute("muted",""),this.config.playsinline&&this.media.setAttribute("playsinline","")),rt.addStyleHook.call(this),this.isHTML5&&wt.insertElements.call(this,"source",t),this.config.title=e.title,gt.setup.call(this),this.isHTML5&&Object.keys(e).includes("tracks")&&wt.insertElements.call(this,"track",e.tracks),(this.isHTML5||this.isEmbed&&!this.supported.ui)&&rt.build.call(this),this.isHTML5&&this.media.load(),z(e.previewThumbnails)||(Object.assign(this.config.previewThumbnails,e.previewThumbnails),this.previewThumbnails&&this.previewThumbnails.loaded&&(this.previewThumbnails.destroy(),this.previewThumbnails=null),this.config.previewThumbnails.enabled&&(this.previewThumbnails=new vt(this))),this.fullscreen.update()}),!0)):this.debug.warn("Invalid source format")}};class Tt{constructor(e,i){if(t(this,"play",(()=>R(this.media.play)?(this.ads&&this.ads.enabled&&this.ads.managerPromise.then((()=>this.ads.play())).catch((()=>Ce(this.media.play()))),this.media.play()):null)),t(this,"pause",(()=>this.playing&&R(this.media.pause)?this.media.pause():null)),t(this,"togglePlay",(e=>(j(e)?e:!this.playing)?this.play():this.pause())),t(this,"stop",(()=>{this.isHTML5?(this.pause(),this.restart()):R(this.media.stop)&&this.media.stop()})),t(this,"restart",(()=>{this.currentTime=0})),t(this,"rewind",(e=>{this.currentTime-=$(e)?e:this.config.seekTime})),t(this,"forward",(e=>{this.currentTime+=$(e)?e:this.config.seekTime})),t(this,"increaseVolume",(e=>{const t=this.media.muted?0:this.volume;this.volume=t+($(e)?e:0)})),t(this,"decreaseVolume",(e=>{this.increaseVolume(-e)})),t(this,"airplay",(()=>{me.airplay&&this.media.webkitShowPlaybackTargetPicker()})),t(this,"toggleControls",(e=>{if(this.supported.ui&&!this.isAudio){const t=le(this.elements.container,this.config.classNames.hideControls),i=void 0===e?void 0:!e,s=oe(this.elements.container,this.config.classNames.hideControls,i);if(s&&q(this.config.controls)&&this.config.controls.includes("settings")&&!z(this.config.settings)&&ze.toggleMenu.call(this,!1),s!==t){const e=s?"controlshidden":"controlsshown";we.call(this,this.media,e)}return!s}return!1})),t(this,"on",((e,t)=>{be.call(this,this.elements.container,e,t)})),t(this,"once",((e,t)=>{ve.call(this,this.elements.container,e,t)})),t(this,"off",((e,t)=>{ye(this.elements.container,e,t)})),t(this,"destroy",((e,t=!1)=>{if(!this.ready)return;const i=()=>{document.body.style.overflow="",this.embed=null,t?(Object.keys(this.elements).length&&(ie(this.elements.buttons.play),ie(this.elements.captions),ie(this.elements.controls),ie(this.elements.wrapper),this.elements.buttons.play=null,this.elements.captions=null,this.elements.controls=null,this.elements.wrapper=null),R(e)&&e()):(Te.call(this),Ie.cancelRequests.call(this),ne(this.elements.original,this.elements.container),we.call(this,this.elements.original,"destroyed",!0),R(e)&&e.call(this.elements.original),this.ready=!1,setTimeout((()=>{this.elements=null,this.media=null}),200))};this.stop(),clearTimeout(this.timers.loading),clearTimeout(this.timers.controls),clearTimeout(this.timers.resized),this.isHTML5?(rt.toggleNativeControls.call(this,!0),i()):this.isYouTube?(clearInterval(this.timers.buffering),clearInterval(this.timers.playing),null!==this.embed&&R(this.embed.destroy)&&this.embed.destroy(),i()):this.isVimeo&&(null!==this.embed&&this.embed.unload().then(i),setTimeout(i,200))})),t(this,"supports",(e=>me.mime.call(this,e))),this.timers={},this.ready=!1,this.loading=!1,this.failed=!1,this.touch=me.touch,this.media=e,O(this.media)&&(this.media=document.querySelectorAll(this.media)),(window.jQuery&&this.media instanceof jQuery||D(this.media)||q(this.media))&&(this.media=this.media[0]),this.config=J({},Xe,Tt.defaults,i||{},(()=>{try{return JSON.parse(this.media.getAttribute("data-plyr-config"))}catch(e){return{}}})()),this.elements={container:null,fullscreen:null,captions:null,buttons:{},display:{},progress:{},inputs:{},settings:{popup:null,menu:null,panels:{},buttons:{}}},this.captions={active:null,currentTrack:-1,meta:new WeakMap},this.fullscreen={active:!1},this.options={speed:[],quality:[]},this.debug=new st(this.config.debug),this.debug.log("Config",this.config),this.debug.log("Support",me),L(this.media)||!H(this.media))return void this.debug.error("Setup failed: no suitable element passed");if(this.media.plyr)return void this.debug.warn("Target already setup");if(!this.config.enabled)return void this.debug.error("Setup failed: disabled by config");if(!me.check().api)return void this.debug.error("Setup failed: no support");const s=this.media.cloneNode(!0);s.autoplay=!1,this.elements.original=s;const n=this.media.tagName.toLowerCase();let a=null,r=null;switch(n){case"div":if(a=this.media.querySelector("iframe"),H(a)){if(r=Ke(a.getAttribute("src")),this.provider=function(e){return/^(https?:\/\/)?(www\.)?(youtube\.com|youtube-nocookie\.com|youtu\.?be)\/.+$/.test(e)?Ze.youtube:/^https?:\/\/player.vimeo.com\/video\/\d{0,9}(?=\b|\/)/.test(e)?Ze.vimeo:null}(r.toString()),this.elements.container=this.media,this.media=a,this.elements.container.className="",r.search.length){const e=["1","true"];e.includes(r.searchParams.get("autoplay"))&&(this.config.autoplay=!0),e.includes(r.searchParams.get("loop"))&&(this.config.loop.active=!0),this.isYouTube?(this.config.playsinline=e.includes(r.searchParams.get("playsinline")),this.config.youtube.hl=r.searchParams.get("hl")):this.config.playsinline=!0}}else this.provider=this.media.getAttribute(this.config.attributes.embed.provider),this.media.removeAttribute(this.config.attributes.embed.provider);if(z(this.provider)||!Object.values(Ze).includes(this.provider))return void this.debug.error("Setup failed: Invalid provider");this.type=tt;break;case"video":case"audio":this.type=n,this.provider=Ze.html5,this.media.hasAttribute("crossorigin")&&(this.config.crossorigin=!0),this.media.hasAttribute("autoplay")&&(this.config.autoplay=!0),(this.media.hasAttribute("playsinline")||this.media.hasAttribute("webkit-playsinline"))&&(this.config.playsinline=!0),this.media.hasAttribute("muted")&&(this.config.muted=!0),this.media.hasAttribute("loop")&&(this.config.loop.active=!0);break;default:return void this.debug.error("Setup failed: unsupported type")}this.supported=me.check(this.type,this.provider,this.config.playsinline),this.supported.api?(this.eventListeners=[],this.listeners=new ot(this),this.storage=new Fe(this),this.media.plyr=this,H(this.elements.container)||(this.elements.container=ee("div",{tabindex:0}),G(this.media,this.elements.container)),rt.migrateStyles.call(this),rt.addStyleHook.call(this),gt.setup.call(this),this.config.debug&&be.call(this,this.elements.container,this.config.events.join(" "),(e=>{this.debug.log(`event: ${e.type}`)})),this.fullscreen=new nt(this),(this.isHTML5||this.isEmbed&&!this.supported.ui)&&rt.build.call(this),this.listeners.container(),this.listeners.global(),this.config.ads.enabled&&(this.ads=new ft(this)),this.isHTML5&&this.config.autoplay&&this.once("canplay",(()=>Ce(this.play()))),this.lastSeekTime=0,this.config.previewThumbnails.enabled&&(this.previewThumbnails=new vt(this))):this.debug.error("Setup failed: no support")}get isHTML5(){return this.provider===Ze.html5}get isEmbed(){return this.isYouTube||this.isVimeo}get isYouTube(){return this.provider===Ze.youtube}get isVimeo(){return this.provider===Ze.vimeo}get isVideo(){return this.type===tt}get isAudio(){return this.type===et}get playing(){return Boolean(this.ready&&!this.paused&&!this.ended)}get paused(){return Boolean(this.media.paused)}get stopped(){return Boolean(this.paused&&0===this.currentTime)}get ended(){return Boolean(this.media.ended)}set currentTime(e){if(!this.duration)return;const t=$(e)&&e>0;this.media.currentTime=t?Math.min(e,this.duration):0,this.debug.log(`Seeking to ${this.currentTime} seconds`)}get currentTime(){return Number(this.media.currentTime)}get buffered(){const{buffered:e}=this.media;return $(e)?e:e&&e.length&&this.duration>0?e.end(0)/this.duration:0}get seeking(){return Boolean(this.media.seeking)}get duration(){const e=parseFloat(this.config.duration),t=(this.media||{}).duration,i=$(t)&&t!==1/0?t:0;return e||i}set volume(e){let t=e;O(t)&&(t=Number(t)),$(t)||(t=this.storage.get("volume")),$(t)||({volume:t}=this.config),t>1&&(t=1),t<0&&(t=0),this.config.volume=t,this.media.volume=t,!z(e)&&this.muted&&t>0&&(this.muted=!1)}get volume(){return Number(this.media.volume)}set muted(e){let t=e;j(t)||(t=this.storage.get("muted")),j(t)||(t=this.config.muted),this.config.muted=t,this.media.muted=t}get muted(){return Boolean(this.media.muted)}get hasAudio(){return!this.isHTML5||(!!this.isAudio||(Boolean(this.media.mozHasAudio)||Boolean(this.media.webkitAudioDecodedByteCount)||Boolean(this.media.audioTracks&&this.media.audioTracks.length)))}set speed(e){let t=null;$(e)&&(t=e),$(t)||(t=this.storage.get("speed")),$(t)||(t=this.config.speed.selected);const{minimumSpeed:i,maximumSpeed:s}=this;t=function(e=0,t=0,i=255){return Math.min(Math.max(e,t),i)}(t,i,s),this.config.speed.selected=t,setTimeout((()=>{this.media&&(this.media.playbackRate=t)}),0)}get speed(){return Number(this.media.playbackRate)}get minimumSpeed(){return this.isYouTube?Math.min(...this.options.speed):this.isVimeo?.5:.0625}get maximumSpeed(){return this.isYouTube?Math.max(...this.options.speed):this.isVimeo?2:16}set quality(e){const t=this.config.quality,i=this.options.quality;if(!i.length)return;let s=[!z(e)&&Number(e),this.storage.get("quality"),t.selected,t.default].find($),n=!0;if(!i.includes(s)){const e=Se(i,s);this.debug.warn(`Unsupported quality option: ${s}, using ${e} instead`),s=e,n=!1}t.selected=s,this.media.quality=s,n&&this.storage.set({quality:s})}get quality(){return this.media.quality}set loop(e){const t=j(e)?e:this.config.loop.active;this.config.loop.active=t,this.media.loop=t}get loop(){return Boolean(this.media.loop)}set source(e){wt.change.call(this,e)}get source(){return this.media.currentSrc}get download(){const{download:e}=this.config.urls;return W(e)?e:this.source}set download(e){W(e)&&(this.config.urls.download=e,ze.setDownloadUrl.call(this))}set poster(e){this.isVideo?rt.setPoster.call(this,e,!1).catch((()=>{})):this.debug.warn("Poster can only be set for video")}get poster(){return this.isVideo?this.media.getAttribute("poster")||this.media.getAttribute("data-poster"):null}get ratio(){if(!this.isVideo)return null;const e=Ne(Me.call(this));return q(e)?e.join(":"):e}set ratio(e){this.isVideo?O(e)&&xe(e)?(this.config.ratio=Ne(e),_e.call(this)):this.debug.error(`Invalid aspect ratio specified (${e})`):this.debug.warn("Aspect ratio can only be set for video")}set autoplay(e){const t=j(e)?e:this.config.autoplay;this.config.autoplay=t}get autoplay(){return Boolean(this.config.autoplay)}toggleCaptions(e){Qe.toggle.call(this,e,!1)}set currentTrack(e){Qe.set.call(this,e,!1),Qe.setup()}get currentTrack(){const{toggled:e,currentTrack:t}=this.captions;return e?t:-1}set language(e){Qe.setLanguage.call(this,e,!1)}get language(){return(Qe.getCurrentTrack.call(this)||{}).language}set pip(e){if(!me.pip)return;const t=j(e)?e:!this.pip;R(this.media.webkitSetPresentationMode)&&this.media.webkitSetPresentationMode(t?Je:Ge),R(this.media.requestPictureInPicture)&&(!this.pip&&t?this.media.requestPictureInPicture():this.pip&&!t&&document.exitPictureInPicture())}get pip(){return me.pip?z(this.media.webkitPresentationMode)?this.media===document.pictureInPictureElement:this.media.webkitPresentationMode===Je:null}setPreviewThumbnails(e){this.previewThumbnails&&this.previewThumbnails.loaded&&(this.previewThumbnails.destroy(),this.previewThumbnails=null),Object.assign(this.config.previewThumbnails,e),this.config.previewThumbnails.enabled&&(this.previewThumbnails=new vt(this))}static supported(e,t,i){return me.check(e,t,i)}static loadSprite(e,t){return Ue(e,t)}static setup(e,t={}){let i=null;return O(e)?i=Array.from(document.querySelectorAll(e)):D(e)?i=Array.from(e):q(e)&&(i=e.filter(H)),z(i)?null:i.map((e=>new Tt(e,t)))}}var kt;return Tt.defaults=(kt=Xe,JSON.parse(JSON.stringify(kt))),Tt})); +//# sourceMappingURL=plyr.polyfilled.min.js.map diff --git a/extlib/plyr/plyr.polyfilled.min.js.map b/extlib/plyr/plyr.polyfilled.min.js.map new file mode 100644 index 00000000..1f1b289a --- /dev/null +++ b/extlib/plyr/plyr.polyfilled.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["plyr.polyfilled.js","node_modules/custom-event-polyfill/polyfill.js","node_modules/rangetouch/dist/rangetouch.mjs","node_modules/url-polyfill/url-polyfill.js","src/js/utils/is.js","src/js/utils/animation.js","src/js/utils/browser.js","src/js/utils/objects.js","src/js/utils/elements.js","src/js/support.js","src/js/utils/events.js","src/js/utils/promise.js","src/js/utils/arrays.js","src/js/utils/style.js","src/js/html5.js","src/js/utils/strings.js","src/js/utils/i18n.js","src/js/storage.js","src/js/utils/fetch.js","src/js/utils/load-sprite.js","src/js/utils/time.js","src/js/controls.js","src/js/utils/urls.js","src/js/captions.js","src/js/config/defaults.js","src/js/config/states.js","src/js/config/types.js","src/js/console.js","src/js/fullscreen.js","src/js/utils/load-image.js","src/js/ui.js","src/js/listeners.js","node_modules/loadjs/dist/loadjs.umd.js","src/js/utils/load-script.js","src/js/plugins/vimeo.js","src/js/plugins/youtube.js","src/js/media.js","src/js/plugins/ads.js","src/js/plugins/preview-thumbnails.js","src/js/source.js","src/js/plyr.js","src/js/utils/numbers.js"],"names":["navigator","global","factory","exports","module","define","amd","globalThis","self","Plyr","this","window","ce","CustomEvent","cancelable","preventDefault","defaultPrevented","Error","e","event","params","evt","origPrevent","bubbles","document","createEvent","initCustomEvent","detail","call","Object","defineProperty","get","prototype","Event","commonjsGlobal","_defineProperty$1","obj","key","value","enumerable","configurable","writable","_defineProperties","t","n","length","r","_defineProperty","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","push","apply","_objectSpread2","arguments","forEach","getOwnPropertyDescriptors","defineProperties","iteratorSupported","Symbol","iterator","error","checkIfIteratorIsSupported","createIterator","items","next","shift","done","serializeParam","encodeURIComponent","replace","deserializeParam","decodeURIComponent","String","URLSearchParams","toString","set","entries","checkIfURLSearchParamsSupported","searchString","typeofSearchString","_fromString","_this","name","append","TypeError","i","entry","hasOwnProperty","proto","_entries","delete","getAll","slice","has","callback","thisArg","values","searchArray","join","polyfillURLSearchParams","sort","a","b","attribute","attributes","split","u","URL","pathname","href","searchParams","checkIfURLIsSupported","_URL","url","base","baseElement","doc","location","toLowerCase","implementation","createHTMLDocument","createElement","head","appendChild","indexOf","err","anchorElement","body","inputElement","type","protocol","test","checkValidity","search","enableSearchUpdate","enableSearchParamsUpdate","methodName","method","attributeName","_anchorElement","linkURLWithAnchorAttribute","_updateSearchParams","origin","expectedPort","addPortToOrigin","port","hostname","password","username","createObjectURL","blob","revokeObjectURL","polyfillURL","getOrigin","setInterval","defaults","addCSS","thumbWidth","watch","matches","Array","from","querySelectorAll","includes","getConstructor","constructor","instanceOf","isNullOrUndefined","isObject","isString","isArray","isNodeList","NodeList","is","Element","round","concat","match","Math","max","getDecimalPlaces","parseFloat","toFixed","RangeTouch","_classCallCheck","element","querySelector","rangeTouch","config","init","_createClass","enabled","style","userSelect","webKitUserSelect","touchAction","listeners","target","changedTouches","o","getAttribute","s","c","getBoundingClientRect","width","clientX","left","disabled","dispatchEvent","trigger","MutationObserver","addedNodes","observe","childList","subtree","map","documentElement","input","Boolean","isFunction","Function","isEmpty","Number","isNaN","nodeType","ownerDocument","KeyboardEvent","TextTrack","kind","Promise","then","string","startsWith","_","transitionEndEvent","events","WebkitTransition","MozTransition","OTransition","transition","find","undefined","repaint","delay","setTimeout","hidden","offsetHeight","browser","isIE","documentMode","isEdge","userAgent","isWebkit","isIPhone","platform","isIos","maxTouchPoints","getDeep","object","path","reduce","extend","sources","source","assign","wrap","elements","wrapper","targets","reverse","index","child","cloneNode","parent","parentNode","sibling","nextSibling","insertBefore","setAttributes","setAttribute","text","innerText","insertElement","removeElement","removeChild","emptyElement","childNodes","lastChild","replaceElement","newChild","oldChild","replaceChild","getAttributesFromSelector","sel","existingAttributes","existing","selector","trim","className","parts","charAt","class","id","toggleHidden","hide","toggleClass","force","classList","contains","hasClass","webkitMatchesSelector","mozMatchesSelector","msMatchesSelector","getElements","container","getElement","setFocus","tabFocus","focus","preventScroll","classNames","defaultCodecs","support","audio","video","check","provider","playsinline","canPlayInline","api","ui","rangeInput","pip","webkitSetPresentationMode","pictureInPictureEnabled","disablePictureInPicture","airplay","WebKitPlaybackTargetAvailabilityEvent","mime","mediaType","isHTML5","media","canPlayType","textTracks","range","touch","transitions","reducedMotion","matchMedia","supportsPassiveListeners","supported","options","addEventListener","removeEventListener","toggleListener","toggle","passive","capture","eventListeners","on","off","once","onceCallback","args","triggerEvent","plyr","unbindListeners","item","ready","resolve","silencePromise","dedupe","array","closest","prev","curr","abs","supportsCSS","declaration","CSS","supports","standardRatios","out","x","y","validateAspectRatio","every","reduceAspectRatio","ratio","height","getDivider","w","h","divider","getAspectRatio","parse","embed","videoWidth","videoHeight","setAspectRatio","isVideo","padding","aspectRatio","paddingBottom","isVimeo","vimeo","premium","offsetWidth","parseInt","getComputedStyle","offset","fullscreen","active","transform","add","videoFixedRatio","roundAspectRatio","tolerance","closestRatio","html5","getSources","getQualityOptions","quality","forced","setup","player","speed","onChange","currentTime","paused","preload","readyState","playbackRate","src","play","load","cancelRequests","blankVideo","debug","log","format","replaceAll","RegExp","toTitleCase","toUpperCase","substr","toCamelCase","toPascalCase","getHTML","innerHTML","resources","youtube","i18n","seekTime","title","k","v","Storage","store","localStorage","getItem","json","JSON","storage","setItem","stringify","removeItem","fetch","responseType","reject","request","XMLHttpRequest","responseText","response","status","open","send","loadSprite","hasId","isCached","exists","getElementById","update","data","insertAdjacentElement","useStorage","cached","content","result","catch","getHours","trunc","formatTime","time","displayHours","inverted","hours","mins","secs","getSeconds","controls","getIconUrl","iconUrl","host","top","cors","svg4everybody","findElements","selectors","buttons","pause","restart","rewind","fastForward","mute","settings","captions","progress","inputs","seek","volume","display","buffer","duration","seekTooltip","tooltip","warn","toggleNativeControls","createIcon","namespace","iconPath","iconPrefix","icon","createElementNS","focusable","use","setAttributeNS","createLabel","attr","createBadge","badge","menu","createButton","buttonType","props","label","labelPressed","iconPressed","some","control","button","createRange","min","step","autocomplete","role","updateRangeFill","createProgress","suffixKey","played","suffix","createTime","attrs","bindMenuItemShortcuts","menuItem","which","stopPropagation","isRadioButton","showMenuPanel","nextElementSibling","firstElementChild","previousElementSibling","lastElementChild","focusFirstMenuItem","createMenuItem","list","checked","flex","children","node","bind","currentTrack","updateTimeDisplay","updateVolume","setRange","muted","pressed","updateProgress","setProgress","val","getElementsByTagName","nodeValue","current","buffered","percent","setProperty","updateSeekTooltip","tooltips","visible","show","clientRect","pageX","timeUpdate","invert","invertTime","seeking","durationUpdate","hasDuration","displayDuration","toggleMenuButton","setting","updateSetting","pane","panels","default","getLabel","setQualityMenu","checkMenu","getBadge","sorting","setCaptionsMenu","tracks","getTracks","track","toggled","language","unshift","setSpeedMenu","minimumSpeed","maximumSpeed","popup","p","firstItem","toggleMenu","composedPath","isMenuItem","getMenuSize","tab","clone","position","opacity","removeAttribute","scrollWidth","scrollHeight","size","restore","propertyName","setDownloadUrl","download","create","defaultAttributes","progressContainer","inner","home","backButton","urls","isEmbed","inject","floor","random","seektime","addProperty","controlPressed","labels","parseUrl","safe","parser","buildUrlParams","isYouTube","languages","userLanguage","trackEvents","meta","currentTrackNode","languageExists","mode","updateCues","setLanguage","activeClass","findTrack","enableTextTrack","sortIsDefault","sorted","getCurrentTrack","cues","activeCues","cue","getCueAsHTML","cueText","caption","autoplay","autopause","toggleInvert","clickToPlay","hideControls","resetOnEnd","disableContextMenu","loop","selected","keyboard","focused","fallback","iosNative","seekLabel","unmute","enableCaptions","disableCaptions","enterFullscreen","exitFullscreen","frameTitle","menuBack","normal","start","end","all","reset","advertisement","qualityBadge","sdk","iframe","googleIMA","editable","embedContainer","poster","posterEnabled","ads","playing","stopped","loading","hover","isTouch","uiSupported","noTransition","previewThumbnails","thumbContainer","thumbContainerShown","imageContainer","timeContainer","scrubbingContainer","scrubbingContainerShown","hash","publisherId","tagUrl","byline","portrait","transparent","customControls","referrerPolicy","rel","showinfo","iv_load_policy","modestbranding","noCookie","providers","types","noop","Console","console","Fullscreen","scrollPosition","scrollX","scrollY","scrollTo","overflow","viewport","property","hasProperty","cleanupViewport","part","keyCode","activeElement","first","last","shiftKey","forceFallback","native","requestFullscreen","webkitEnterFullscreen","toggleFallback","prefix","navigationUI","webkitExitFullscreen","action","cancelFullScreen","exit","enter","el","parentElement","proxy","trapFocus","fullscreenEnabled","webkitFullscreenEnabled","mozFullScreenEnabled","msFullscreenEnabled","usingNative","pre","getRootNode","fullscreenElement","shadowRoot","loadImage","minWidth","image","Image","handler","onload","onerror","naturalWidth","addStyleHook","build","checkPlaying","setTitle","setPoster","togglePoster","enable","backgroundImage","backgroundSize","toggleControls","checkLoading","clearTimeout","timers","controlsElement","recentTouchSeek","lastSeekTime","Date","now","migrateStyles","getPropertyValue","removeProperty","Listeners","focusTimer","lastKeyDown","timeStamp","wasKeyDown","removeCurrent","handleKey","firstTouch","setTabFocus","setGutter","useNativeAspectRatio","maxWidth","margin","viewportWidth","viewportHeight","clientWidth","innerWidth","clientHeight","innerHeight","resized","isAudio","ended","togglePlay","proxyEvents","defaultHandler","customHandlerKey","customHandler","returned","hasCustomHandler","inputEvent","forward","toggleCaptions","code","rect","currentTarget","hasAttribute","seekTo","loaded","startMove","endMove","startScrubbing","endScrubbing","webkitDirectionInvertedFromDevice","deltaX","deltaY","direction","sign","increaseVolume","lastKey","repeat","altKey","ctrlKey","metaKey","decreaseVolume","loadjs_umd","fn","createCommonjsModule","devnull","bundleIdCache","bundleResultCache","bundleCallbackQueue","subscribe","bundleIds","callbackFn","bundleId","depsNotFound","numWaiting","pathsNotFound","publish","q","splice","executeCallbacks","success","loadFile","numTries","isLegacyIECss","async","maxTries","numRetries","beforeCallbackFn","before","pathStripped","relList","as","onbeforeload","ev","sheet","cssText","loadFiles","paths","loadjs","arg1","arg2","loadFn","returnPromise","deps","isDefined","loadScript","assurePlaybackState","hasPlayed","Vimeo","frameParams","found","groups","parseHash","hashParam","sidedock","gesture","$2","thumbnail_url","Player","disableTextTrack","stop","restorePause","setVolume","setCurrentTime","setPlaybackRate","currentSrc","setLoop","getVideoUrl","getVideoWidth","getVideoHeight","dimensions","setAutopause","state","getVideoTitle","getCurrentTime","getDuration","getTextTracks","strippedCues","fragment","createDocumentFragment","firstChild","stripHTML","getPaused","seconds","getHost","YT","onYouTubeIframeAPIReady","getTitle","videoId","currentId","posterSrc","playerVars","hl","disablekb","cc_load_policy","cc_lang_pref","widget_referrer","onError","message","onPlaybackRateChange","instance","getPlaybackRate","onReady","playVideo","pauseVideo","stopVideo","speeds","getAvailablePlaybackRates","clearInterval","buffering","getVideoLoadedFraction","lastBuffered","onStateChange","unMute","Ads","google","ima","manager","destroy","displayContainer","remove","startSafetyTimer","managerPromise","clearSafetyTimer","setupIMA","setVpaidMode","ImaSdkSettings","VpaidMode","ENABLED","setLocale","setDisableCustomPlaybackForIOS10Plus","AdDisplayContainer","loader","AdsLoader","AdsManagerLoadedEvent","Type","ADS_MANAGER_LOADED","onAdsManagerLoaded","AdErrorEvent","AD_ERROR","onAdError","requestAds","AdsRequest","adTagUrl","linearAdSlotWidth","linearAdSlotHeight","nonLinearAdSlotWidth","nonLinearAdSlotHeight","forceNonLinearFullSlot","setAdWillPlayMuted","countdownTimer","getRemainingTime","AdsRenderingSettings","restoreCustomPlaybackStateOnAdBreakComplete","enablePreloading","getAdsManager","cuePoints","getCuePoints","AdEvent","onAdEvent","cuePoint","seekElement","cuePercentage","ad","getAd","adData","getAdData","LOADED","pollCountdown","isLinear","STARTED","ALL_ADS_COMPLETED","loadAds","contentComplete","CONTENT_PAUSE_REQUESTED","pauseContent","CONTENT_RESUME_REQUESTED","resumeContent","LOG","adError","getMessage","cancel","addCuePoints","seekedTime","discardAdBreak","resize","ViewMode","NORMAL","initialize","initialized","zIndex","handlers","safetyTimer","AV_PUBLISHERID","AV_CHANNELID","AV_URL","cb","AV_WIDTH","AV_HEIGHT","AV_CDIM2","parseVtt","vttDataString","processedList","frame","line","startTime","lineSplit","matchTimes","endTime","fitRatio","outer","PreviewThumbnails","getThumbnails","render","determineContainerAutoSizing","sortAndResolve","thumbnails","promises","getThumbnail","thumbnail","frames","urlPrefix","substring","lastIndexOf","tempImage","naturalHeight","percentage","mousePosX","thumb","showImageAtCurrentTime","toggleThumbContainer","mouseDown","toggleScrubbingContainer","ceil","lastTime","scrubbing","setScrubbingContainerSize","setThumbContainerSizeAndPos","thumbNum","findIndex","hasThumb","qualityIndex","loadedImages","showingThumb","thumbFilename","thumbUrl","currentImageElement","dataset","filename","showImage","removeOldImages","loadingImage","usingSprites","previewImage","showingThumbFilename","newImage","setImageSizeAndOffset","currentImageContainer","preloadNearby","getHigherQuality","currentImage","tagName","removeDelay","deleting","oldThumbFilename","thumbnailsClone","foundOne","newThumbFilename","thumbURL","currentQualityIndex","previewImageHeight","thumbContainerHeight","clearShowing","sizeSpecifiedInCSS","thumbAspectRatio","thumbHeight","setThumbContainerPos","seekbarRect","plyrRect","minVal","maxVal","right","previewPos","multiplier","lastMouseMoveTime","currentScrubbingImageElement","currentThumbnailImageElement","insertElements","change","crossorigin","webkitShowPlaybackTargetPicker","isHidden","hiding","eventName","soft","original","unload","failed","jQuery","WeakMap","getProviderByUrl","truthy","tabindex","inputIsValid","fauxDuration","realDuration","Infinity","hasAudio","mozHasAudio","webkitAudioDecodedByteCount","audioTracks","clamp","updateStorage","requestPictureInPicture","exitPictureInPicture","webkitPresentationMode","pictureInPictureElement","setPreviewThumbnails","thumbnailSource","static","inline"],"mappings":"AAAqB,iBAAdA,WAA0B,SAAWC,EAAQC,GAC/B,iBAAZC,SAA0C,oBAAXC,OAAyBA,OAAOD,QAAUD,IAC9D,mBAAXG,QAAyBA,OAAOC,IAAMD,OAAO,OAAQH,IAC3DD,EAA+B,oBAAfM,WAA6BA,WAAaN,GAAUO,MAAaC,KAAOP,IAH1D,CAI9BQ,MAAM,WAAe,cCExB,WACE,GAAsB,oBAAXC,OAIX,IACE,IAAIC,EAAK,IAAID,OAAOE,YAAY,OAAQ,CAAEC,YAAY,IAEtD,GADAF,EAAGG,kBACyB,IAAxBH,EAAGI,iBAGL,MAAM,IAAIC,MAAM,6BAElB,MAAOC,GACP,IAAIL,EAAc,SAASM,EAAOC,GAChC,IAAIC,EAAKC,EAyBT,OAxBAF,EAASA,GAAU,IACZG,UAAYH,EAAOG,QAC1BH,EAAON,aAAeM,EAAON,YAE7BO,EAAMG,SAASC,YAAY,gBACvBC,gBACFP,EACAC,EAAOG,QACPH,EAAON,WACPM,EAAOO,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GACJ,KAGFA,EAAQrD,KAAK/K,GAAM,IAAIlC,GAAKkC,EAAGuT,MjCtvCnC,IAAmB7F,GPq/RxB,OwC3vPF5P,GAAKqJ,UjC1vCqBuG,GiC0vCAvG,GjCzvCjBmT,KAAKnE,MAAMmE,KAAKG,UAAU/M,MPo/R1B5P","file":"plyr.polyfilled.min.js","sourcesContent":["typeof navigator === \"object\" && (function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define('Plyr', factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Plyr = factory());\n})(this, (function () { 'use strict';\n\n // Polyfill for creating CustomEvents on IE9/10/11\n // code pulled from:\n // https://github.com/d4tocchini/customevent-polyfill\n // https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill\n (function () {\n if (typeof window === 'undefined') {\n return;\n }\n\n try {\n var ce = new window.CustomEvent('test', {\n cancelable: true\n });\n ce.preventDefault();\n\n if (ce.defaultPrevented !== true) {\n // IE has problems with .preventDefault() on custom events\n // http://stackoverflow.com/questions/23349191\n throw new Error('Could not prevent default');\n }\n } catch (e) {\n var CustomEvent = function (event, params) {\n var evt, origPrevent;\n params = params || {};\n params.bubbles = !!params.bubbles;\n params.cancelable = !!params.cancelable;\n evt = document.createEvent('CustomEvent');\n evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);\n origPrevent = evt.preventDefault;\n\n evt.preventDefault = function () {\n origPrevent.call(this);\n\n try {\n Object.defineProperty(this, 'defaultPrevented', {\n get: function () {\n return true;\n }\n });\n } catch (e) {\n this.defaultPrevented = true;\n }\n };\n\n return evt;\n };\n\n CustomEvent.prototype = window.Event.prototype;\n window.CustomEvent = CustomEvent; // expose definition to window\n }\n })();\n\n var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\n function createCommonjsModule(fn, module) {\n \treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n }\n\n (function (global) {\n /**\r\n * Polyfill URLSearchParams\r\n *\r\n * Inspired from : https://github.com/WebReflection/url-search-params/blob/master/src/url-search-params.js\r\n */\n var checkIfIteratorIsSupported = function () {\n try {\n return !!Symbol.iterator;\n } catch (error) {\n return false;\n }\n };\n\n var iteratorSupported = checkIfIteratorIsSupported();\n\n var createIterator = function (items) {\n var iterator = {\n next: function () {\n var value = items.shift();\n return {\n done: value === void 0,\n value: value\n };\n }\n };\n\n if (iteratorSupported) {\n iterator[Symbol.iterator] = function () {\n return iterator;\n };\n }\n\n return iterator;\n };\n /**\r\n * Search param name and values should be encoded according to https://url.spec.whatwg.org/#urlencoded-serializing\r\n * encodeURIComponent() produces the same result except encoding spaces as `%20` instead of `+`.\r\n */\n\n\n var serializeParam = function (value) {\n return encodeURIComponent(value).replace(/%20/g, '+');\n };\n\n var deserializeParam = function (value) {\n return decodeURIComponent(String(value).replace(/\\+/g, ' '));\n };\n\n var polyfillURLSearchParams = function () {\n var URLSearchParams = function (searchString) {\n Object.defineProperty(this, '_entries', {\n writable: true,\n value: {}\n });\n var typeofSearchString = typeof searchString;\n\n if (typeofSearchString === 'undefined') ; else if (typeofSearchString === 'string') {\n if (searchString !== '') {\n this._fromString(searchString);\n }\n } else if (searchString instanceof URLSearchParams) {\n var _this = this;\n\n searchString.forEach(function (value, name) {\n _this.append(name, value);\n });\n } else if (searchString !== null && typeofSearchString === 'object') {\n if (Object.prototype.toString.call(searchString) === '[object Array]') {\n for (var i = 0; i < searchString.length; i++) {\n var entry = searchString[i];\n\n if (Object.prototype.toString.call(entry) === '[object Array]' || entry.length !== 2) {\n this.append(entry[0], entry[1]);\n } else {\n throw new TypeError('Expected [string, any] as entry at index ' + i + ' of URLSearchParams\\'s input');\n }\n }\n } else {\n for (var key in searchString) {\n if (searchString.hasOwnProperty(key)) {\n this.append(key, searchString[key]);\n }\n }\n }\n } else {\n throw new TypeError('Unsupported input\\'s type for URLSearchParams');\n }\n };\n\n var proto = URLSearchParams.prototype;\n\n proto.append = function (name, value) {\n if (name in this._entries) {\n this._entries[name].push(String(value));\n } else {\n this._entries[name] = [String(value)];\n }\n };\n\n proto.delete = function (name) {\n delete this._entries[name];\n };\n\n proto.get = function (name) {\n return name in this._entries ? this._entries[name][0] : null;\n };\n\n proto.getAll = function (name) {\n return name in this._entries ? this._entries[name].slice(0) : [];\n };\n\n proto.has = function (name) {\n return name in this._entries;\n };\n\n proto.set = function (name, value) {\n this._entries[name] = [String(value)];\n };\n\n proto.forEach = function (callback, thisArg) {\n var entries;\n\n for (var name in this._entries) {\n if (this._entries.hasOwnProperty(name)) {\n entries = this._entries[name];\n\n for (var i = 0; i < entries.length; i++) {\n callback.call(thisArg, entries[i], name, this);\n }\n }\n }\n };\n\n proto.keys = function () {\n var items = [];\n this.forEach(function (value, name) {\n items.push(name);\n });\n return createIterator(items);\n };\n\n proto.values = function () {\n var items = [];\n this.forEach(function (value) {\n items.push(value);\n });\n return createIterator(items);\n };\n\n proto.entries = function () {\n var items = [];\n this.forEach(function (value, name) {\n items.push([name, value]);\n });\n return createIterator(items);\n };\n\n if (iteratorSupported) {\n proto[Symbol.iterator] = proto.entries;\n }\n\n proto.toString = function () {\n var searchArray = [];\n this.forEach(function (value, name) {\n searchArray.push(serializeParam(name) + '=' + serializeParam(value));\n });\n return searchArray.join('&');\n };\n\n global.URLSearchParams = URLSearchParams;\n };\n\n var checkIfURLSearchParamsSupported = function () {\n try {\n var URLSearchParams = global.URLSearchParams;\n return new URLSearchParams('?a=1').toString() === 'a=1' && typeof URLSearchParams.prototype.set === 'function' && typeof URLSearchParams.prototype.entries === 'function';\n } catch (e) {\n return false;\n }\n };\n\n if (!checkIfURLSearchParamsSupported()) {\n polyfillURLSearchParams();\n }\n\n var proto = global.URLSearchParams.prototype;\n\n if (typeof proto.sort !== 'function') {\n proto.sort = function () {\n var _this = this;\n\n var items = [];\n this.forEach(function (value, name) {\n items.push([name, value]);\n\n if (!_this._entries) {\n _this.delete(name);\n }\n });\n items.sort(function (a, b) {\n if (a[0] < b[0]) {\n return -1;\n } else if (a[0] > b[0]) {\n return +1;\n } else {\n return 0;\n }\n });\n\n if (_this._entries) {\n // force reset because IE keeps keys index\n _this._entries = {};\n }\n\n for (var i = 0; i < items.length; i++) {\n this.append(items[i][0], items[i][1]);\n }\n };\n }\n\n if (typeof proto._fromString !== 'function') {\n Object.defineProperty(proto, '_fromString', {\n enumerable: false,\n configurable: false,\n writable: false,\n value: function (searchString) {\n if (this._entries) {\n this._entries = {};\n } else {\n var keys = [];\n this.forEach(function (value, name) {\n keys.push(name);\n });\n\n for (var i = 0; i < keys.length; i++) {\n this.delete(keys[i]);\n }\n }\n\n searchString = searchString.replace(/^\\?/, '');\n var attributes = searchString.split('&');\n var attribute;\n\n for (var i = 0; i < attributes.length; i++) {\n attribute = attributes[i].split('=');\n this.append(deserializeParam(attribute[0]), attribute.length > 1 ? deserializeParam(attribute[1]) : '');\n }\n }\n });\n } // HTMLAnchorElement\n\n })(typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal);\n\n (function (global) {\n /**\r\n * Polyfill URL\r\n *\r\n * Inspired from : https://github.com/arv/DOM-URL-Polyfill/blob/master/src/url.js\r\n */\n var checkIfURLIsSupported = function () {\n try {\n var u = new global.URL('b', 'http://a');\n u.pathname = 'c d';\n return u.href === 'http://a/c%20d' && u.searchParams;\n } catch (e) {\n return false;\n }\n };\n\n var polyfillURL = function () {\n var _URL = global.URL;\n\n var URL = function (url, base) {\n if (typeof url !== 'string') url = String(url);\n if (base && typeof base !== 'string') base = String(base); // Only create another document if the base is different from current location.\n\n var doc = document,\n baseElement;\n\n if (base && (global.location === void 0 || base !== global.location.href)) {\n base = base.toLowerCase();\n doc = document.implementation.createHTMLDocument('');\n baseElement = doc.createElement('base');\n baseElement.href = base;\n doc.head.appendChild(baseElement);\n\n try {\n if (baseElement.href.indexOf(base) !== 0) throw new Error(baseElement.href);\n } catch (err) {\n throw new Error('URL unable to set base ' + base + ' due to ' + err);\n }\n }\n\n var anchorElement = doc.createElement('a');\n anchorElement.href = url;\n\n if (baseElement) {\n doc.body.appendChild(anchorElement);\n anchorElement.href = anchorElement.href; // force href to refresh\n }\n\n var inputElement = doc.createElement('input');\n inputElement.type = 'url';\n inputElement.value = url;\n\n if (anchorElement.protocol === ':' || !/:/.test(anchorElement.href) || !inputElement.checkValidity() && !base) {\n throw new TypeError('Invalid URL');\n }\n\n Object.defineProperty(this, '_anchorElement', {\n value: anchorElement\n }); // create a linked searchParams which reflect its changes on URL\n\n var searchParams = new global.URLSearchParams(this.search);\n var enableSearchUpdate = true;\n var enableSearchParamsUpdate = true;\n\n var _this = this;\n\n ['append', 'delete', 'set'].forEach(function (methodName) {\n var method = searchParams[methodName];\n\n searchParams[methodName] = function () {\n method.apply(searchParams, arguments);\n\n if (enableSearchUpdate) {\n enableSearchParamsUpdate = false;\n _this.search = searchParams.toString();\n enableSearchParamsUpdate = true;\n }\n };\n });\n Object.defineProperty(this, 'searchParams', {\n value: searchParams,\n enumerable: true\n });\n var search = void 0;\n Object.defineProperty(this, '_updateSearchParams', {\n enumerable: false,\n configurable: false,\n writable: false,\n value: function () {\n if (this.search !== search) {\n search = this.search;\n\n if (enableSearchParamsUpdate) {\n enableSearchUpdate = false;\n\n this.searchParams._fromString(this.search);\n\n enableSearchUpdate = true;\n }\n }\n }\n });\n };\n\n var proto = URL.prototype;\n\n var linkURLWithAnchorAttribute = function (attributeName) {\n Object.defineProperty(proto, attributeName, {\n get: function () {\n return this._anchorElement[attributeName];\n },\n set: function (value) {\n this._anchorElement[attributeName] = value;\n },\n enumerable: true\n });\n };\n\n ['hash', 'host', 'hostname', 'port', 'protocol'].forEach(function (attributeName) {\n linkURLWithAnchorAttribute(attributeName);\n });\n Object.defineProperty(proto, 'search', {\n get: function () {\n return this._anchorElement['search'];\n },\n set: function (value) {\n this._anchorElement['search'] = value;\n\n this._updateSearchParams();\n },\n enumerable: true\n });\n Object.defineProperties(proto, {\n 'toString': {\n get: function () {\n var _this = this;\n\n return function () {\n return _this.href;\n };\n }\n },\n 'href': {\n get: function () {\n return this._anchorElement.href.replace(/\\?$/, '');\n },\n set: function (value) {\n this._anchorElement.href = value;\n\n this._updateSearchParams();\n },\n enumerable: true\n },\n 'pathname': {\n get: function () {\n return this._anchorElement.pathname.replace(/(^\\/?)/, '/');\n },\n set: function (value) {\n this._anchorElement.pathname = value;\n },\n enumerable: true\n },\n 'origin': {\n get: function () {\n // get expected port from protocol\n var expectedPort = {\n 'http:': 80,\n 'https:': 443,\n 'ftp:': 21\n }[this._anchorElement.protocol]; // add port to origin if, expected port is different than actual port\n // and it is not empty f.e http://foo:8080\n // 8080 != 80 && 8080 != ''\n\n var addPortToOrigin = this._anchorElement.port != expectedPort && this._anchorElement.port !== '';\n return this._anchorElement.protocol + '//' + this._anchorElement.hostname + (addPortToOrigin ? ':' + this._anchorElement.port : '');\n },\n enumerable: true\n },\n 'password': {\n // TODO\n get: function () {\n return '';\n },\n set: function (value) {},\n enumerable: true\n },\n 'username': {\n // TODO\n get: function () {\n return '';\n },\n set: function (value) {},\n enumerable: true\n }\n });\n\n URL.createObjectURL = function (blob) {\n return _URL.createObjectURL.apply(_URL, arguments);\n };\n\n URL.revokeObjectURL = function (url) {\n return _URL.revokeObjectURL.apply(_URL, arguments);\n };\n\n global.URL = URL;\n };\n\n if (!checkIfURLIsSupported()) {\n polyfillURL();\n }\n\n if (global.location !== void 0 && !('origin' in global.location)) {\n var getOrigin = function () {\n return global.location.protocol + '//' + global.location.hostname + (global.location.port ? ':' + global.location.port : '');\n };\n\n try {\n Object.defineProperty(global.location, 'origin', {\n get: getOrigin,\n enumerable: true\n });\n } catch (e) {\n setInterval(function () {\n global.location.origin = getOrigin();\n }, 100);\n }\n }\n })(typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal);\n\n function _defineProperty$1(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n }\n\n function _classCallCheck(e, t) {\n if (!(e instanceof t)) throw new TypeError(\"Cannot call a class as a function\");\n }\n\n function _defineProperties(e, t) {\n for (var n = 0; n < t.length; n++) {\n var r = t[n];\n r.enumerable = r.enumerable || !1, r.configurable = !0, \"value\" in r && (r.writable = !0), Object.defineProperty(e, r.key, r);\n }\n }\n\n function _createClass(e, t, n) {\n return t && _defineProperties(e.prototype, t), n && _defineProperties(e, n), e;\n }\n\n function _defineProperty(e, t, n) {\n return t in e ? Object.defineProperty(e, t, {\n value: n,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[t] = n, e;\n }\n\n function ownKeys(e, t) {\n var n = Object.keys(e);\n\n if (Object.getOwnPropertySymbols) {\n var r = Object.getOwnPropertySymbols(e);\n t && (r = r.filter(function (t) {\n return Object.getOwnPropertyDescriptor(e, t).enumerable;\n })), n.push.apply(n, r);\n }\n\n return n;\n }\n\n function _objectSpread2(e) {\n for (var t = 1; t < arguments.length; t++) {\n var n = null != arguments[t] ? arguments[t] : {};\n t % 2 ? ownKeys(Object(n), !0).forEach(function (t) {\n _defineProperty(e, t, n[t]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : ownKeys(Object(n)).forEach(function (t) {\n Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));\n });\n }\n\n return e;\n }\n\n var defaults$1 = {\n addCSS: !0,\n thumbWidth: 15,\n watch: !0\n };\n\n function matches$1(e, t) {\n return function () {\n return Array.from(document.querySelectorAll(t)).includes(this);\n }.call(e, t);\n }\n\n function trigger(e, t) {\n if (e && t) {\n var n = new Event(t, {\n bubbles: !0\n });\n e.dispatchEvent(n);\n }\n }\n\n var getConstructor$1 = function (e) {\n return null != e ? e.constructor : null;\n },\n instanceOf$1 = function (e, t) {\n return !!(e && t && e instanceof t);\n },\n isNullOrUndefined$1 = function (e) {\n return null == e;\n },\n isObject$1 = function (e) {\n return getConstructor$1(e) === Object;\n },\n isNumber$1 = function (e) {\n return getConstructor$1(e) === Number && !Number.isNaN(e);\n },\n isString$1 = function (e) {\n return getConstructor$1(e) === String;\n },\n isBoolean$1 = function (e) {\n return getConstructor$1(e) === Boolean;\n },\n isFunction$1 = function (e) {\n return getConstructor$1(e) === Function;\n },\n isArray$1 = function (e) {\n return Array.isArray(e);\n },\n isNodeList$1 = function (e) {\n return instanceOf$1(e, NodeList);\n },\n isElement$1 = function (e) {\n return instanceOf$1(e, Element);\n },\n isEvent$1 = function (e) {\n return instanceOf$1(e, Event);\n },\n isEmpty$1 = function (e) {\n return isNullOrUndefined$1(e) || (isString$1(e) || isArray$1(e) || isNodeList$1(e)) && !e.length || isObject$1(e) && !Object.keys(e).length;\n },\n is$1 = {\n nullOrUndefined: isNullOrUndefined$1,\n object: isObject$1,\n number: isNumber$1,\n string: isString$1,\n boolean: isBoolean$1,\n function: isFunction$1,\n array: isArray$1,\n nodeList: isNodeList$1,\n element: isElement$1,\n event: isEvent$1,\n empty: isEmpty$1\n };\n\n function getDecimalPlaces(e) {\n var t = \"\".concat(e).match(/(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/);\n return t ? Math.max(0, (t[1] ? t[1].length : 0) - (t[2] ? +t[2] : 0)) : 0;\n }\n\n function round(e, t) {\n if (1 > t) {\n var n = getDecimalPlaces(t);\n return parseFloat(e.toFixed(n));\n }\n\n return Math.round(e / t) * t;\n }\n\n var RangeTouch = function () {\n function e(t, n) {\n _classCallCheck(this, e), is$1.element(t) ? this.element = t : is$1.string(t) && (this.element = document.querySelector(t)), is$1.element(this.element) && is$1.empty(this.element.rangeTouch) && (this.config = _objectSpread2({}, defaults$1, {}, n), this.init());\n }\n\n return _createClass(e, [{\n key: \"init\",\n value: function () {\n e.enabled && (this.config.addCSS && (this.element.style.userSelect = \"none\", this.element.style.webKitUserSelect = \"none\", this.element.style.touchAction = \"manipulation\"), this.listeners(!0), this.element.rangeTouch = this);\n }\n }, {\n key: \"destroy\",\n value: function () {\n e.enabled && (this.config.addCSS && (this.element.style.userSelect = \"\", this.element.style.webKitUserSelect = \"\", this.element.style.touchAction = \"\"), this.listeners(!1), this.element.rangeTouch = null);\n }\n }, {\n key: \"listeners\",\n value: function (e) {\n var t = this,\n n = e ? \"addEventListener\" : \"removeEventListener\";\n [\"touchstart\", \"touchmove\", \"touchend\"].forEach(function (e) {\n t.element[n](e, function (e) {\n return t.set(e);\n }, !1);\n });\n }\n }, {\n key: \"get\",\n value: function (t) {\n if (!e.enabled || !is$1.event(t)) return null;\n var n,\n r = t.target,\n i = t.changedTouches[0],\n o = parseFloat(r.getAttribute(\"min\")) || 0,\n s = parseFloat(r.getAttribute(\"max\")) || 100,\n u = parseFloat(r.getAttribute(\"step\")) || 1,\n c = r.getBoundingClientRect(),\n a = 100 / c.width * (this.config.thumbWidth / 2) / 100;\n return 0 > (n = 100 / c.width * (i.clientX - c.left)) ? n = 0 : 100 < n && (n = 100), 50 > n ? n -= (100 - 2 * n) * a : 50 < n && (n += 2 * (n - 50) * a), o + round(n / 100 * (s - o), u);\n }\n }, {\n key: \"set\",\n value: function (t) {\n e.enabled && is$1.event(t) && !t.target.disabled && (t.preventDefault(), t.target.value = this.get(t), trigger(t.target, \"touchend\" === t.type ? \"change\" : \"input\"));\n }\n }], [{\n key: \"setup\",\n value: function (t) {\n var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {},\n r = null;\n if (is$1.empty(t) || is$1.string(t) ? r = Array.from(document.querySelectorAll(is$1.string(t) ? t : 'input[type=\"range\"]')) : is$1.element(t) ? r = [t] : is$1.nodeList(t) ? r = Array.from(t) : is$1.array(t) && (r = t.filter(is$1.element)), is$1.empty(r)) return null;\n\n var i = _objectSpread2({}, defaults$1, {}, n);\n\n if (is$1.string(t) && i.watch) {\n var o = new MutationObserver(function (n) {\n Array.from(n).forEach(function (n) {\n Array.from(n.addedNodes).forEach(function (n) {\n is$1.element(n) && matches$1(n, t) && new e(n, i);\n });\n });\n });\n o.observe(document.body, {\n childList: !0,\n subtree: !0\n });\n }\n\n return r.map(function (t) {\n return new e(t, n);\n });\n }\n }, {\n key: \"enabled\",\n get: function () {\n return \"ontouchstart\" in document.documentElement;\n }\n }]), e;\n }();\n\n // ==========================================================================\n // Type checking utils\n // ==========================================================================\n const getConstructor = input => input !== null && typeof input !== 'undefined' ? input.constructor : null;\n\n const instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor);\n\n const isNullOrUndefined = input => input === null || typeof input === 'undefined';\n\n const isObject = input => getConstructor(input) === Object;\n\n const isNumber = input => getConstructor(input) === Number && !Number.isNaN(input);\n\n const isString = input => getConstructor(input) === String;\n\n const isBoolean = input => getConstructor(input) === Boolean;\n\n const isFunction = input => getConstructor(input) === Function;\n\n const isArray = input => Array.isArray(input);\n\n const isWeakMap = input => instanceOf(input, WeakMap);\n\n const isNodeList = input => instanceOf(input, NodeList);\n\n const isTextNode = input => getConstructor(input) === Text;\n\n const isEvent = input => instanceOf(input, Event);\n\n const isKeyboardEvent = input => instanceOf(input, KeyboardEvent);\n\n const isCue = input => instanceOf(input, window.TextTrackCue) || instanceOf(input, window.VTTCue);\n\n const isTrack = input => instanceOf(input, TextTrack) || !isNullOrUndefined(input) && isString(input.kind);\n\n const isPromise = input => instanceOf(input, Promise) && isFunction(input.then);\n\n const isElement = input => input !== null && typeof input === 'object' && input.nodeType === 1 && typeof input.style === 'object' && typeof input.ownerDocument === 'object';\n\n const isEmpty = input => isNullOrUndefined(input) || (isString(input) || isArray(input) || isNodeList(input)) && !input.length || isObject(input) && !Object.keys(input).length;\n\n const isUrl = input => {\n // Accept a URL object\n if (instanceOf(input, window.URL)) {\n return true;\n } // Must be string from here\n\n\n if (!isString(input)) {\n return false;\n } // Add the protocol if required\n\n\n let string = input;\n\n if (!input.startsWith('http://') || !input.startsWith('https://')) {\n string = `http://${input}`;\n }\n\n try {\n return !isEmpty(new URL(string).hostname);\n } catch (_) {\n return false;\n }\n };\n\n var is = {\n nullOrUndefined: isNullOrUndefined,\n object: isObject,\n number: isNumber,\n string: isString,\n boolean: isBoolean,\n function: isFunction,\n array: isArray,\n weakMap: isWeakMap,\n nodeList: isNodeList,\n element: isElement,\n textNode: isTextNode,\n event: isEvent,\n keyboardEvent: isKeyboardEvent,\n cue: isCue,\n track: isTrack,\n promise: isPromise,\n url: isUrl,\n empty: isEmpty\n };\n\n // ==========================================================================\n const transitionEndEvent = (() => {\n const element = document.createElement('span');\n const events = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend'\n };\n const type = Object.keys(events).find(event => element.style[event] !== undefined);\n return is.string(type) ? events[type] : false;\n })(); // Force repaint of element\n\n function repaint(element, delay) {\n setTimeout(() => {\n try {\n // eslint-disable-next-line no-param-reassign\n element.hidden = true; // eslint-disable-next-line no-unused-expressions\n\n element.offsetHeight; // eslint-disable-next-line no-param-reassign\n\n element.hidden = false;\n } catch (_) {// Do nothing\n }\n }, delay);\n }\n\n // ==========================================================================\n // Browser sniffing\n // Unfortunately, due to mixed support, UA sniffing is required\n // ==========================================================================\n const browser = {\n isIE: Boolean(window.document.documentMode),\n isEdge: window.navigator.userAgent.includes('Edge'),\n isWebkit: 'WebkitAppearance' in document.documentElement.style && !/Edge/.test(navigator.userAgent),\n isIPhone: /(iPhone|iPod)/gi.test(navigator.platform),\n isIos: navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 || /(iPad|iPhone|iPod)/gi.test(navigator.platform)\n };\n\n // ==========================================================================\n\n function cloneDeep(object) {\n return JSON.parse(JSON.stringify(object));\n } // Get a nested value in an object\n\n function getDeep(object, path) {\n return path.split('.').reduce((obj, key) => obj && obj[key], object);\n } // Deep extend destination object with N more objects\n\n function extend(target = {}, ...sources) {\n if (!sources.length) {\n return target;\n }\n\n const source = sources.shift();\n\n if (!is.object(source)) {\n return target;\n }\n\n Object.keys(source).forEach(key => {\n if (is.object(source[key])) {\n if (!Object.keys(target).includes(key)) {\n Object.assign(target, {\n [key]: {}\n });\n }\n\n extend(target[key], source[key]);\n } else {\n Object.assign(target, {\n [key]: source[key]\n });\n }\n });\n return extend(target, ...sources);\n }\n\n // ==========================================================================\n\n function wrap(elements, wrapper) {\n // Convert `elements` to an array, if necessary.\n const targets = elements.length ? elements : [elements]; // Loops backwards to prevent having to clone the wrapper on the\n // first element (see `child` below).\n\n Array.from(targets).reverse().forEach((element, index) => {\n const child = index > 0 ? wrapper.cloneNode(true) : wrapper; // Cache the current parent and sibling.\n\n const parent = element.parentNode;\n const sibling = element.nextSibling; // Wrap the element (is automatically removed from its current\n // parent).\n\n child.appendChild(element); // If the element had a sibling, insert the wrapper before\n // the sibling to maintain the HTML structure; otherwise, just\n // append it to the parent.\n\n if (sibling) {\n parent.insertBefore(child, sibling);\n } else {\n parent.appendChild(child);\n }\n });\n } // Set attributes\n\n function setAttributes(element, attributes) {\n if (!is.element(element) || is.empty(attributes)) {\n return;\n } // Assume null and undefined attributes should be left out,\n // Setting them would otherwise convert them to \"null\" and \"undefined\"\n\n\n Object.entries(attributes).filter(([, value]) => !is.nullOrUndefined(value)).forEach(([key, value]) => element.setAttribute(key, value));\n } // Create a DocumentFragment\n\n function createElement(type, attributes, text) {\n // Create a new <element>\n const element = document.createElement(type); // Set all passed attributes\n\n if (is.object(attributes)) {\n setAttributes(element, attributes);\n } // Add text node\n\n\n if (is.string(text)) {\n element.innerText = text;\n } // Return built element\n\n\n return element;\n } // Inaert an element after another\n\n function insertAfter(element, target) {\n if (!is.element(element) || !is.element(target)) {\n return;\n }\n\n target.parentNode.insertBefore(element, target.nextSibling);\n } // Insert a DocumentFragment\n\n function insertElement(type, parent, attributes, text) {\n if (!is.element(parent)) {\n return;\n }\n\n parent.appendChild(createElement(type, attributes, text));\n } // Remove element(s)\n\n function removeElement(element) {\n if (is.nodeList(element) || is.array(element)) {\n Array.from(element).forEach(removeElement);\n return;\n }\n\n if (!is.element(element) || !is.element(element.parentNode)) {\n return;\n }\n\n element.parentNode.removeChild(element);\n } // Remove all child elements\n\n function emptyElement(element) {\n if (!is.element(element)) {\n return;\n }\n\n let {\n length\n } = element.childNodes;\n\n while (length > 0) {\n element.removeChild(element.lastChild);\n length -= 1;\n }\n } // Replace element\n\n function replaceElement(newChild, oldChild) {\n if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) {\n return null;\n }\n\n oldChild.parentNode.replaceChild(newChild, oldChild);\n return newChild;\n } // Get an attribute object from a string selector\n\n function getAttributesFromSelector(sel, existingAttributes) {\n // For example:\n // '.test' to { class: 'test' }\n // '#test' to { id: 'test' }\n // '[data-test=\"test\"]' to { 'data-test': 'test' }\n if (!is.string(sel) || is.empty(sel)) {\n return {};\n }\n\n const attributes = {};\n const existing = extend({}, existingAttributes);\n sel.split(',').forEach(s => {\n // Remove whitespace\n const selector = s.trim();\n const className = selector.replace('.', '');\n const stripped = selector.replace(/[[\\]]/g, ''); // Get the parts and value\n\n const parts = stripped.split('=');\n const [key] = parts;\n const value = parts.length > 1 ? parts[1].replace(/[\"']/g, '') : ''; // Get the first character\n\n const start = selector.charAt(0);\n\n switch (start) {\n case '.':\n // Add to existing classname\n if (is.string(existing.class)) {\n attributes.class = `${existing.class} ${className}`;\n } else {\n attributes.class = className;\n }\n\n break;\n\n case '#':\n // ID selector\n attributes.id = selector.replace('#', '');\n break;\n\n case '[':\n // Attribute selector\n attributes[key] = value;\n break;\n }\n });\n return extend(existing, attributes);\n } // Toggle hidden\n\n function toggleHidden(element, hidden) {\n if (!is.element(element)) {\n return;\n }\n\n let hide = hidden;\n\n if (!is.boolean(hide)) {\n hide = !element.hidden;\n } // eslint-disable-next-line no-param-reassign\n\n\n element.hidden = hide;\n } // Mirror Element.classList.toggle, with IE compatibility for \"force\" argument\n\n function toggleClass(element, className, force) {\n if (is.nodeList(element)) {\n return Array.from(element).map(e => toggleClass(e, className, force));\n }\n\n if (is.element(element)) {\n let method = 'toggle';\n\n if (typeof force !== 'undefined') {\n method = force ? 'add' : 'remove';\n }\n\n element.classList[method](className);\n return element.classList.contains(className);\n }\n\n return false;\n } // Has class name\n\n function hasClass(element, className) {\n return is.element(element) && element.classList.contains(className);\n } // Element matches selector\n\n function matches(element, selector) {\n const {\n prototype\n } = Element;\n\n function match() {\n return Array.from(document.querySelectorAll(selector)).includes(this);\n }\n\n const method = prototype.matches || prototype.webkitMatchesSelector || prototype.mozMatchesSelector || prototype.msMatchesSelector || match;\n return method.call(element, selector);\n } // Closest ancestor element matching selector (also tests element itself)\n\n function closest$1(element, selector) {\n const {\n prototype\n } = Element; // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill\n\n function closestElement() {\n let el = this;\n\n do {\n if (matches.matches(el, selector)) return el;\n el = el.parentElement || el.parentNode;\n } while (el !== null && el.nodeType === 1);\n\n return null;\n }\n\n const method = prototype.closest || closestElement;\n return method.call(element, selector);\n } // Find all elements\n\n function getElements(selector) {\n return this.elements.container.querySelectorAll(selector);\n } // Find a single element\n\n function getElement(selector) {\n return this.elements.container.querySelector(selector);\n } // Set focus and tab focus class\n\n function setFocus(element = null, tabFocus = false) {\n if (!is.element(element)) {\n return;\n } // Set regular focus\n\n\n element.focus({\n preventScroll: true\n }); // If we want to mimic keyboard focus via tab\n\n if (tabFocus) {\n toggleClass(element, this.config.classNames.tabFocus);\n }\n }\n\n // ==========================================================================\n\n const defaultCodecs = {\n 'audio/ogg': 'vorbis',\n 'audio/wav': '1',\n 'video/webm': 'vp8, vorbis',\n 'video/mp4': 'avc1.42E01E, mp4a.40.2',\n 'video/ogg': 'theora'\n }; // Check for feature support\n\n const support = {\n // Basic support\n audio: 'canPlayType' in document.createElement('audio'),\n video: 'canPlayType' in document.createElement('video'),\n\n // Check for support\n // Basic functionality vs full UI\n check(type, provider, playsinline) {\n const canPlayInline = browser.isIPhone && playsinline && support.playsinline;\n const api = support[type] || provider !== 'html5';\n const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline);\n return {\n api,\n ui\n };\n },\n\n // Picture-in-picture support\n // Safari & Chrome only currently\n pip: (() => {\n if (browser.isIPhone) {\n return false;\n } // Safari\n // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls\n\n\n if (is.function(createElement('video').webkitSetPresentationMode)) {\n return true;\n } // Chrome\n // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture\n\n\n if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) {\n return true;\n }\n\n return false;\n })(),\n // Airplay support\n // Safari only currently\n airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent),\n // Inline playback support\n // https://webkit.org/blog/6784/new-video-policies-for-ios/\n playsinline: 'playsInline' in document.createElement('video'),\n\n // Check for mime type support against a player instance\n // Credits: http://diveintohtml5.info/everything.html\n // Related: http://www.leanbackplayer.com/test/h5mt.html\n mime(input) {\n if (is.empty(input)) {\n return false;\n }\n\n const [mediaType] = input.split('/');\n let type = input; // Verify we're using HTML5 and there's no media type mismatch\n\n if (!this.isHTML5 || mediaType !== this.type) {\n return false;\n } // Add codec if required\n\n\n if (Object.keys(defaultCodecs).includes(type)) {\n type += `; codecs=\"${defaultCodecs[input]}\"`;\n }\n\n try {\n return Boolean(type && this.media.canPlayType(type).replace(/no/, ''));\n } catch (_) {\n return false;\n }\n },\n\n // Check for textTracks support\n textTracks: 'textTracks' in document.createElement('video'),\n // <input type=\"range\"> Sliders\n rangeInput: (() => {\n const range = document.createElement('input');\n range.type = 'range';\n return range.type === 'range';\n })(),\n // Touch\n // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event\n touch: 'ontouchstart' in document.documentElement,\n // Detect transitions support\n transitions: transitionEndEvent !== false,\n // Reduced motion iOS & MacOS setting\n // https://webkit.org/blog/7551/responsive-design-for-motion/\n reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches\n };\n\n // ==========================================================================\n // https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md\n // https://www.youtube.com/watch?v=NPM6172J22g\n\n const supportsPassiveListeners = (() => {\n // Test via a getter in the options object to see if the passive property is accessed\n let supported = false;\n\n try {\n const options = Object.defineProperty({}, 'passive', {\n get() {\n supported = true;\n return null;\n }\n\n });\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n } catch (_) {// Do nothing\n }\n\n return supported;\n })(); // Toggle event listener\n\n\n function toggleListener(element, event, callback, toggle = false, passive = true, capture = false) {\n // Bail if no element, event, or callback\n if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) {\n return;\n } // Allow multiple events\n\n\n const events = event.split(' '); // Build options\n // Default to just the capture boolean for browsers with no passive listener support\n\n let options = capture; // If passive events listeners are supported\n\n if (supportsPassiveListeners) {\n options = {\n // Whether the listener can be passive (i.e. default never prevented)\n passive,\n // Whether the listener is a capturing listener or not\n capture\n };\n } // If a single node is passed, bind the event listener\n\n\n events.forEach(type => {\n if (this && this.eventListeners && toggle) {\n // Cache event listener\n this.eventListeners.push({\n element,\n type,\n callback,\n options\n });\n }\n\n element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options);\n });\n } // Bind event handler\n\n function on(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, true, passive, capture);\n } // Unbind event handler\n\n function off(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, false, passive, capture);\n } // Bind once-only event handler\n\n function once(element, events = '', callback, passive = true, capture = false) {\n const onceCallback = (...args) => {\n off(element, events, onceCallback, passive, capture);\n callback.apply(this, args);\n };\n\n toggleListener.call(this, element, events, onceCallback, true, passive, capture);\n } // Trigger event\n\n function triggerEvent(element, type = '', bubbles = false, detail = {}) {\n // Bail if no element\n if (!is.element(element) || is.empty(type)) {\n return;\n } // Create and dispatch the event\n\n\n const event = new CustomEvent(type, {\n bubbles,\n detail: { ...detail,\n plyr: this\n }\n }); // Dispatch the event\n\n element.dispatchEvent(event);\n } // Unbind all cached event listeners\n\n function unbindListeners() {\n if (this && this.eventListeners) {\n this.eventListeners.forEach(item => {\n const {\n element,\n type,\n callback,\n options\n } = item;\n element.removeEventListener(type, callback, options);\n });\n this.eventListeners = [];\n }\n } // Run method when / if player is ready\n\n function ready() {\n return new Promise(resolve => this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve)).then(() => {});\n }\n\n /**\n * Silence a Promise-like object.\n * This is useful for avoiding non-harmful, but potentially confusing \"uncaught\n * play promise\" rejection error messages.\n * @param {Object} value An object that may or may not be `Promise`-like.\n */\n\n function silencePromise(value) {\n if (is.promise(value)) {\n value.then(null, () => {});\n }\n }\n\n // ==========================================================================\n\n function dedupe(array) {\n if (!is.array(array)) {\n return array;\n }\n\n return array.filter((item, index) => array.indexOf(item) === index);\n } // Get the closest value in an array\n\n function closest(array, value) {\n if (!is.array(array) || !array.length) {\n return null;\n }\n\n return array.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev);\n }\n\n // ==========================================================================\n\n function supportsCSS(declaration) {\n if (!window || !window.CSS) {\n return false;\n }\n\n return window.CSS.supports(declaration);\n } // Standard/common aspect ratios\n\n const standardRatios = [[1, 1], [4, 3], [3, 4], [5, 4], [4, 5], [3, 2], [2, 3], [16, 10], [10, 16], [16, 9], [9, 16], [21, 9], [9, 21], [32, 9], [9, 32]].reduce((out, [x, y]) => ({ ...out,\n [x / y]: [x, y]\n }), {}); // Validate an aspect ratio\n\n function validateAspectRatio(input) {\n if (!is.array(input) && (!is.string(input) || !input.includes(':'))) {\n return false;\n }\n\n const ratio = is.array(input) ? input : input.split(':');\n return ratio.map(Number).every(is.number);\n } // Reduce an aspect ratio to it's lowest form\n\n function reduceAspectRatio(ratio) {\n if (!is.array(ratio) || !ratio.every(is.number)) {\n return null;\n }\n\n const [width, height] = ratio;\n\n const getDivider = (w, h) => h === 0 ? w : getDivider(h, w % h);\n\n const divider = getDivider(width, height);\n return [width / divider, height / divider];\n } // Calculate an aspect ratio\n\n function getAspectRatio(input) {\n const parse = ratio => validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null; // Try provided ratio\n\n\n let ratio = parse(input); // Get from config\n\n if (ratio === null) {\n ratio = parse(this.config.ratio);\n } // Get from embed\n\n\n if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) {\n ({\n ratio\n } = this.embed);\n } // Get from HTML5 video\n\n\n if (ratio === null && this.isHTML5) {\n const {\n videoWidth,\n videoHeight\n } = this.media;\n ratio = [videoWidth, videoHeight];\n }\n\n return reduceAspectRatio(ratio);\n } // Set aspect ratio for responsive container\n\n function setAspectRatio(input) {\n if (!this.isVideo) {\n return {};\n }\n\n const {\n wrapper\n } = this.elements;\n const ratio = getAspectRatio.call(this, input);\n\n if (!is.array(ratio)) {\n return {};\n }\n\n const [x, y] = reduceAspectRatio(ratio);\n const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`);\n const padding = 100 / x * y;\n\n if (useNative) {\n wrapper.style.aspectRatio = `${x}/${y}`;\n } else {\n wrapper.style.paddingBottom = `${padding}%`;\n } // For Vimeo we have an extra <div> to hide the standard controls and UI\n\n\n if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) {\n const height = 100 / this.media.offsetWidth * parseInt(window.getComputedStyle(this.media).paddingBottom, 10);\n const offset = (height - padding) / (height / 50);\n\n if (this.fullscreen.active) {\n wrapper.style.paddingBottom = null;\n } else {\n this.media.style.transform = `translateY(-${offset}%)`;\n }\n } else if (this.isHTML5) {\n wrapper.classList.add(this.config.classNames.videoFixedRatio);\n }\n\n return {\n padding,\n ratio\n };\n } // Round an aspect ratio to closest standard ratio\n\n function roundAspectRatio(x, y, tolerance = 0.05) {\n const ratio = x / y;\n const closestRatio = closest(Object.keys(standardRatios), ratio); // Check match is within tolerance\n\n if (Math.abs(closestRatio - ratio) <= tolerance) {\n return standardRatios[closestRatio];\n } // No match\n\n\n return [x, y];\n } // Get the size of the viewport\n // https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions\n\n function getViewportSize() {\n const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);\n const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);\n return [width, height];\n }\n\n // ==========================================================================\n const html5 = {\n getSources() {\n if (!this.isHTML5) {\n return [];\n }\n\n const sources = Array.from(this.media.querySelectorAll('source')); // Filter out unsupported sources (if type is specified)\n\n return sources.filter(source => {\n const type = source.getAttribute('type');\n\n if (is.empty(type)) {\n return true;\n }\n\n return support.mime.call(this, type);\n });\n },\n\n // Get quality levels\n getQualityOptions() {\n // Whether we're forcing all options (e.g. for streaming)\n if (this.config.quality.forced) {\n return this.config.quality.options;\n } // Get sizes from <source> elements\n\n\n return html5.getSources.call(this).map(source => Number(source.getAttribute('data-res'))).filter(Boolean);\n },\n\n setup() {\n if (!this.isHTML5) {\n return;\n }\n\n const player = this; // Set speed options from config\n\n player.options.speed = player.config.speed.options; // Set aspect ratio if fixed\n\n if (!is.empty(this.config.ratio)) {\n setAspectRatio.call(player);\n } // Quality\n\n\n Object.defineProperty(player.media, 'quality', {\n get() {\n // Get sources\n const sources = html5.getSources.call(player);\n const source = sources.find(s => s.getAttribute('src') === player.source); // Return size, if match is found\n\n return source && Number(source.getAttribute('data-res'));\n },\n\n set(input) {\n if (player.quality === input) {\n return;\n } // If we're using an external handler...\n\n\n if (player.config.quality.forced && is.function(player.config.quality.onChange)) {\n player.config.quality.onChange(input);\n } else {\n // Get sources\n const sources = html5.getSources.call(player); // Get first match for requested size\n\n const source = sources.find(s => Number(s.getAttribute('data-res')) === input); // No matching source found\n\n if (!source) {\n return;\n } // Get current state\n\n\n const {\n currentTime,\n paused,\n preload,\n readyState,\n playbackRate\n } = player.media; // Set new source\n\n player.media.src = source.getAttribute('src'); // Prevent loading if preload=\"none\" and the current source isn't loaded (#1044)\n\n if (preload !== 'none' || readyState) {\n // Restore time\n player.once('loadedmetadata', () => {\n player.speed = playbackRate;\n player.currentTime = currentTime; // Resume playing\n\n if (!paused) {\n silencePromise(player.play());\n }\n }); // Load new source\n\n player.media.load();\n }\n } // Trigger change event\n\n\n triggerEvent.call(player, player.media, 'qualitychange', false, {\n quality: input\n });\n }\n\n });\n },\n\n // Cancel current network requests\n // See https://github.com/sampotts/plyr/issues/174\n cancelRequests() {\n if (!this.isHTML5) {\n return;\n } // Remove child sources\n\n\n removeElement(html5.getSources.call(this)); // Set blank video src attribute\n // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error\n // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection\n\n this.media.setAttribute('src', this.config.blankVideo); // Load the new empty source\n // This will cancel existing requests\n // See https://github.com/sampotts/plyr/issues/174\n\n this.media.load(); // Debugging\n\n this.debug.log('Cancelled network requests');\n }\n\n };\n\n // ==========================================================================\n\n function generateId(prefix) {\n return `${prefix}-${Math.floor(Math.random() * 10000)}`;\n } // Format string\n\n function format(input, ...args) {\n if (is.empty(input)) {\n return input;\n }\n\n return input.toString().replace(/{(\\d+)}/g, (match, i) => args[i].toString());\n } // Get percentage\n\n function getPercentage(current, max) {\n if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) {\n return 0;\n }\n\n return (current / max * 100).toFixed(2);\n } // Replace all occurances of a string in a string\n\n const replaceAll = (input = '', find = '', replace = '') => input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\\]/\\\\])/g, '\\\\$1'), 'g'), replace.toString()); // Convert to title case\n\n const toTitleCase = (input = '') => input.toString().replace(/\\w\\S*/g, text => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()); // Convert string to pascalCase\n\n function toPascalCase(input = '') {\n let string = input.toString(); // Convert kebab case\n\n string = replaceAll(string, '-', ' '); // Convert snake case\n\n string = replaceAll(string, '_', ' '); // Convert to title case\n\n string = toTitleCase(string); // Convert to pascal case\n\n return replaceAll(string, ' ', '');\n } // Convert string to pascalCase\n\n function toCamelCase(input = '') {\n let string = input.toString(); // Convert to pascal case\n\n string = toPascalCase(string); // Convert first character to lowercase\n\n return string.charAt(0).toLowerCase() + string.slice(1);\n } // Remove HTML from a string\n\n function stripHTML(source) {\n const fragment = document.createDocumentFragment();\n const element = document.createElement('div');\n fragment.appendChild(element);\n element.innerHTML = source;\n return fragment.firstChild.innerText;\n } // Like outerHTML, but also works for DocumentFragment\n\n function getHTML(element) {\n const wrapper = document.createElement('div');\n wrapper.appendChild(element);\n return wrapper.innerHTML;\n }\n\n // ==========================================================================\n\n const resources = {\n pip: 'PIP',\n airplay: 'AirPlay',\n html5: 'HTML5',\n vimeo: 'Vimeo',\n youtube: 'YouTube'\n };\n const i18n = {\n get(key = '', config = {}) {\n if (is.empty(key) || is.empty(config)) {\n return '';\n }\n\n let string = getDeep(config.i18n, key);\n\n if (is.empty(string)) {\n if (Object.keys(resources).includes(key)) {\n return resources[key];\n }\n\n return '';\n }\n\n const replace = {\n '{seektime}': config.seekTime,\n '{title}': config.title\n };\n Object.entries(replace).forEach(([k, v]) => {\n string = replaceAll(string, k, v);\n });\n return string;\n }\n\n };\n\n class Storage {\n constructor(player) {\n _defineProperty$1(this, \"get\", key => {\n if (!Storage.supported || !this.enabled) {\n return null;\n }\n\n const store = window.localStorage.getItem(this.key);\n\n if (is.empty(store)) {\n return null;\n }\n\n const json = JSON.parse(store);\n return is.string(key) && key.length ? json[key] : json;\n });\n\n _defineProperty$1(this, \"set\", object => {\n // Bail if we don't have localStorage support or it's disabled\n if (!Storage.supported || !this.enabled) {\n return;\n } // Can only store objectst\n\n\n if (!is.object(object)) {\n return;\n } // Get current storage\n\n\n let storage = this.get(); // Default to empty object\n\n if (is.empty(storage)) {\n storage = {};\n } // Update the working copy of the values\n\n\n extend(storage, object); // Update storage\n\n try {\n window.localStorage.setItem(this.key, JSON.stringify(storage));\n } catch (_) {// Do nothing\n }\n });\n\n this.enabled = player.config.storage.enabled;\n this.key = player.config.storage.key;\n } // Check for actual support (see if we can use it)\n\n\n static get supported() {\n try {\n if (!('localStorage' in window)) {\n return false;\n }\n\n const test = '___test'; // Try to use it (it might be disabled, e.g. user is in private mode)\n // see: https://github.com/sampotts/plyr/issues/131\n\n window.localStorage.setItem(test, test);\n window.localStorage.removeItem(test);\n return true;\n } catch (_) {\n return false;\n }\n }\n\n }\n\n // ==========================================================================\n // Fetch wrapper\n // Using XHR to avoid issues with older browsers\n // ==========================================================================\n function fetch(url, responseType = 'text') {\n return new Promise((resolve, reject) => {\n try {\n const request = new XMLHttpRequest(); // Check for CORS support\n\n if (!('withCredentials' in request)) {\n return;\n }\n\n request.addEventListener('load', () => {\n if (responseType === 'text') {\n try {\n resolve(JSON.parse(request.responseText));\n } catch (_) {\n resolve(request.responseText);\n }\n } else {\n resolve(request.response);\n }\n });\n request.addEventListener('error', () => {\n throw new Error(request.status);\n });\n request.open('GET', url, true); // Set the required response type\n\n request.responseType = responseType;\n request.send();\n } catch (error) {\n reject(error);\n }\n });\n }\n\n // ==========================================================================\n\n function loadSprite(url, id) {\n if (!is.string(url)) {\n return;\n }\n\n const prefix = 'cache';\n const hasId = is.string(id);\n let isCached = false;\n\n const exists = () => document.getElementById(id) !== null;\n\n const update = (container, data) => {\n // eslint-disable-next-line no-param-reassign\n container.innerHTML = data; // Check again incase of race condition\n\n if (hasId && exists()) {\n return;\n } // Inject the SVG to the body\n\n\n document.body.insertAdjacentElement('afterbegin', container);\n }; // Only load once if ID set\n\n\n if (!hasId || !exists()) {\n const useStorage = Storage.supported; // Create container\n\n const container = document.createElement('div');\n container.setAttribute('hidden', '');\n\n if (hasId) {\n container.setAttribute('id', id);\n } // Check in cache\n\n\n if (useStorage) {\n const cached = window.localStorage.getItem(`${prefix}-${id}`);\n isCached = cached !== null;\n\n if (isCached) {\n const data = JSON.parse(cached);\n update(container, data.content);\n }\n } // Get the sprite\n\n\n fetch(url).then(result => {\n if (is.empty(result)) {\n return;\n }\n\n if (useStorage) {\n try {\n window.localStorage.setItem(`${prefix}-${id}`, JSON.stringify({\n content: result\n }));\n } catch (_) {// Do nothing\n }\n }\n\n update(container, result);\n }).catch(() => {});\n }\n }\n\n // ==========================================================================\n\n const getHours = value => Math.trunc(value / 60 / 60 % 60, 10);\n const getMinutes = value => Math.trunc(value / 60 % 60, 10);\n const getSeconds = value => Math.trunc(value % 60, 10); // Format time to UI friendly string\n\n function formatTime(time = 0, displayHours = false, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return formatTime(undefined, displayHours, inverted);\n } // Format time component to add leading zero\n\n\n const format = value => `0${value}`.slice(-2); // Breakdown to hours, mins, secs\n\n\n let hours = getHours(time);\n const mins = getMinutes(time);\n const secs = getSeconds(time); // Do we need to display hours?\n\n if (displayHours || hours > 0) {\n hours = `${hours}:`;\n } else {\n hours = '';\n } // Render\n\n\n return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`;\n }\n\n // ==========================================================================\n\n const controls = {\n // Get icon URL\n getIconUrl() {\n const url = new URL(this.config.iconUrl, window.location);\n const host = window.location.host ? window.location.host : window.top.location.host;\n const cors = url.host !== host || browser.isIE && !window.svg4everybody;\n return {\n url: this.config.iconUrl,\n cors\n };\n },\n\n // Find the UI controls\n findElements() {\n try {\n this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper); // Buttons\n\n this.elements.buttons = {\n play: getElements.call(this, this.config.selectors.buttons.play),\n pause: getElement.call(this, this.config.selectors.buttons.pause),\n restart: getElement.call(this, this.config.selectors.buttons.restart),\n rewind: getElement.call(this, this.config.selectors.buttons.rewind),\n fastForward: getElement.call(this, this.config.selectors.buttons.fastForward),\n mute: getElement.call(this, this.config.selectors.buttons.mute),\n pip: getElement.call(this, this.config.selectors.buttons.pip),\n airplay: getElement.call(this, this.config.selectors.buttons.airplay),\n settings: getElement.call(this, this.config.selectors.buttons.settings),\n captions: getElement.call(this, this.config.selectors.buttons.captions),\n fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen)\n }; // Progress\n\n this.elements.progress = getElement.call(this, this.config.selectors.progress); // Inputs\n\n this.elements.inputs = {\n seek: getElement.call(this, this.config.selectors.inputs.seek),\n volume: getElement.call(this, this.config.selectors.inputs.volume)\n }; // Display\n\n this.elements.display = {\n buffer: getElement.call(this, this.config.selectors.display.buffer),\n currentTime: getElement.call(this, this.config.selectors.display.currentTime),\n duration: getElement.call(this, this.config.selectors.display.duration)\n }; // Seek tooltip\n\n if (is.element(this.elements.progress)) {\n this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`);\n }\n\n return true;\n } catch (error) {\n // Log it\n this.debug.warn('It looks like there is a problem with your custom controls HTML', error); // Restore native video controls\n\n this.toggleNativeControls(true);\n return false;\n }\n },\n\n // Create <svg> icon\n createIcon(type, attributes) {\n const namespace = 'http://www.w3.org/2000/svg';\n const iconUrl = controls.getIconUrl.call(this);\n const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`; // Create <svg>\n\n const icon = document.createElementNS(namespace, 'svg');\n setAttributes(icon, extend(attributes, {\n 'aria-hidden': 'true',\n focusable: 'false'\n })); // Create the <use> to reference sprite\n\n const use = document.createElementNS(namespace, 'use');\n const path = `${iconPath}-${type}`; // Set `href` attributes\n // https://github.com/sampotts/plyr/issues/460\n // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href\n\n if ('href' in use) {\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path);\n } // Always set the older attribute even though it's \"deprecated\" (it'll be around for ages)\n\n\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path); // Add <use> to <svg>\n\n icon.appendChild(use);\n return icon;\n },\n\n // Create hidden text label\n createLabel(key, attr = {}) {\n const text = i18n.get(key, this.config);\n const attributes = { ...attr,\n class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ')\n };\n return createElement('span', attributes, text);\n },\n\n // Create a badge\n createBadge(text) {\n if (is.empty(text)) {\n return null;\n }\n\n const badge = createElement('span', {\n class: this.config.classNames.menu.value\n });\n badge.appendChild(createElement('span', {\n class: this.config.classNames.menu.badge\n }, text));\n return badge;\n },\n\n // Create a <button>\n createButton(buttonType, attr) {\n const attributes = extend({}, attr);\n let type = toCamelCase(buttonType);\n const props = {\n element: 'button',\n toggle: false,\n label: null,\n icon: null,\n labelPressed: null,\n iconPressed: null\n };\n ['element', 'icon', 'label'].forEach(key => {\n if (Object.keys(attributes).includes(key)) {\n props[key] = attributes[key];\n delete attributes[key];\n }\n }); // Default to 'button' type to prevent form submission\n\n if (props.element === 'button' && !Object.keys(attributes).includes('type')) {\n attributes.type = 'button';\n } // Set class name\n\n\n if (Object.keys(attributes).includes('class')) {\n if (!attributes.class.split(' ').some(c => c === this.config.classNames.control)) {\n extend(attributes, {\n class: `${attributes.class} ${this.config.classNames.control}`\n });\n }\n } else {\n attributes.class = this.config.classNames.control;\n } // Large play button\n\n\n switch (buttonType) {\n case 'play':\n props.toggle = true;\n props.label = 'play';\n props.labelPressed = 'pause';\n props.icon = 'play';\n props.iconPressed = 'pause';\n break;\n\n case 'mute':\n props.toggle = true;\n props.label = 'mute';\n props.labelPressed = 'unmute';\n props.icon = 'volume';\n props.iconPressed = 'muted';\n break;\n\n case 'captions':\n props.toggle = true;\n props.label = 'enableCaptions';\n props.labelPressed = 'disableCaptions';\n props.icon = 'captions-off';\n props.iconPressed = 'captions-on';\n break;\n\n case 'fullscreen':\n props.toggle = true;\n props.label = 'enterFullscreen';\n props.labelPressed = 'exitFullscreen';\n props.icon = 'enter-fullscreen';\n props.iconPressed = 'exit-fullscreen';\n break;\n\n case 'play-large':\n attributes.class += ` ${this.config.classNames.control}--overlaid`;\n type = 'play';\n props.label = 'play';\n props.icon = 'play';\n break;\n\n default:\n if (is.empty(props.label)) {\n props.label = type;\n }\n\n if (is.empty(props.icon)) {\n props.icon = buttonType;\n }\n\n }\n\n const button = createElement(props.element); // Setup toggle icon and labels\n\n if (props.toggle) {\n // Icon\n button.appendChild(controls.createIcon.call(this, props.iconPressed, {\n class: 'icon--pressed'\n }));\n button.appendChild(controls.createIcon.call(this, props.icon, {\n class: 'icon--not-pressed'\n })); // Label/Tooltip\n\n button.appendChild(controls.createLabel.call(this, props.labelPressed, {\n class: 'label--pressed'\n }));\n button.appendChild(controls.createLabel.call(this, props.label, {\n class: 'label--not-pressed'\n }));\n } else {\n button.appendChild(controls.createIcon.call(this, props.icon));\n button.appendChild(controls.createLabel.call(this, props.label));\n } // Merge and set attributes\n\n\n extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes));\n setAttributes(button, attributes); // We have multiple play buttons\n\n if (type === 'play') {\n if (!is.array(this.elements.buttons[type])) {\n this.elements.buttons[type] = [];\n }\n\n this.elements.buttons[type].push(button);\n } else {\n this.elements.buttons[type] = button;\n }\n\n return button;\n },\n\n // Create an <input type='range'>\n createRange(type, attributes) {\n // Seek input\n const input = createElement('input', extend(getAttributesFromSelector(this.config.selectors.inputs[type]), {\n type: 'range',\n min: 0,\n max: 100,\n step: 0.01,\n value: 0,\n autocomplete: 'off',\n // A11y fixes for https://github.com/sampotts/plyr/issues/905\n role: 'slider',\n 'aria-label': i18n.get(type, this.config),\n 'aria-valuemin': 0,\n 'aria-valuemax': 100,\n 'aria-valuenow': 0\n }, attributes));\n this.elements.inputs[type] = input; // Set the fill for webkit now\n\n controls.updateRangeFill.call(this, input); // Improve support on touch devices\n\n RangeTouch.setup(input);\n return input;\n },\n\n // Create a <progress>\n createProgress(type, attributes) {\n const progress = createElement('progress', extend(getAttributesFromSelector(this.config.selectors.display[type]), {\n min: 0,\n max: 100,\n value: 0,\n role: 'progressbar',\n 'aria-hidden': true\n }, attributes)); // Create the label inside\n\n if (type !== 'volume') {\n progress.appendChild(createElement('span', null, '0'));\n const suffixKey = {\n played: 'played',\n buffer: 'buffered'\n }[type];\n const suffix = suffixKey ? i18n.get(suffixKey, this.config) : '';\n progress.innerText = `% ${suffix.toLowerCase()}`;\n }\n\n this.elements.display[type] = progress;\n return progress;\n },\n\n // Create time display\n createTime(type, attrs) {\n const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs);\n const container = createElement('div', extend(attributes, {\n class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(),\n 'aria-label': i18n.get(type, this.config)\n }), '00:00'); // Reference for updates\n\n this.elements.display[type] = container;\n return container;\n },\n\n // Bind keyboard shortcuts for a menu item\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n bindMenuItemShortcuts(menuItem, type) {\n // Navigate through menus via arrow keys and space\n on.call(this, menuItem, 'keydown keyup', event => {\n // We only care about space and ⬆️ ⬇️️ ➡️\n if (![32, 38, 39, 40].includes(event.which)) {\n return;\n } // Prevent play / seek\n\n\n event.preventDefault();\n event.stopPropagation(); // We're just here to prevent the keydown bubbling\n\n if (event.type === 'keydown') {\n return;\n }\n\n const isRadioButton = matches(menuItem, '[role=\"menuitemradio\"]'); // Show the respective menu\n\n if (!isRadioButton && [32, 39].includes(event.which)) {\n controls.showMenuPanel.call(this, type, true);\n } else {\n let target;\n\n if (event.which !== 32) {\n if (event.which === 40 || isRadioButton && event.which === 39) {\n target = menuItem.nextElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.firstElementChild;\n }\n } else {\n target = menuItem.previousElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.lastElementChild;\n }\n }\n\n setFocus.call(this, target, true);\n }\n }\n }, false); // Enter will fire a `click` event but we still need to manage focus\n // So we bind to keyup which fires after and set focus here\n\n on.call(this, menuItem, 'keyup', event => {\n if (event.which !== 13) {\n return;\n }\n\n controls.focusFirstMenuItem.call(this, null, true);\n });\n },\n\n // Create a settings menu item\n createMenuItem({\n value,\n list,\n type,\n title,\n badge = null,\n checked = false\n }) {\n const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]);\n const menuItem = createElement('button', extend(attributes, {\n type: 'button',\n role: 'menuitemradio',\n class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(),\n 'aria-checked': checked,\n value\n }));\n const flex = createElement('span'); // We have to set as HTML incase of special characters\n\n flex.innerHTML = title;\n\n if (is.element(badge)) {\n flex.appendChild(badge);\n }\n\n menuItem.appendChild(flex); // Replicate radio button behaviour\n\n Object.defineProperty(menuItem, 'checked', {\n enumerable: true,\n\n get() {\n return menuItem.getAttribute('aria-checked') === 'true';\n },\n\n set(check) {\n // Ensure exclusivity\n if (check) {\n Array.from(menuItem.parentNode.children).filter(node => matches(node, '[role=\"menuitemradio\"]')).forEach(node => node.setAttribute('aria-checked', 'false'));\n }\n\n menuItem.setAttribute('aria-checked', check ? 'true' : 'false');\n }\n\n });\n this.listeners.bind(menuItem, 'click keyup', event => {\n if (is.keyboardEvent(event) && event.which !== 32) {\n return;\n }\n\n event.preventDefault();\n event.stopPropagation();\n menuItem.checked = true;\n\n switch (type) {\n case 'language':\n this.currentTrack = Number(value);\n break;\n\n case 'quality':\n this.quality = value;\n break;\n\n case 'speed':\n this.speed = parseFloat(value);\n break;\n }\n\n controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event));\n }, type, false);\n controls.bindMenuItemShortcuts.call(this, menuItem, type);\n list.appendChild(menuItem);\n },\n\n // Format a time for display\n formatTime(time = 0, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return time;\n } // Always display hours if duration is over an hour\n\n\n const forceHours = getHours(this.duration) > 0;\n return formatTime(time, forceHours, inverted);\n },\n\n // Update the displayed time\n updateTimeDisplay(target = null, time = 0, inverted = false) {\n // Bail if there's no element to display or the value isn't a number\n if (!is.element(target) || !is.number(time)) {\n return;\n } // eslint-disable-next-line no-param-reassign\n\n\n target.innerText = controls.formatTime(time, inverted);\n },\n\n // Update volume UI and storage\n updateVolume() {\n if (!this.supported.ui) {\n return;\n } // Update range\n\n\n if (is.element(this.elements.inputs.volume)) {\n controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);\n } // Update mute state\n\n\n if (is.element(this.elements.buttons.mute)) {\n this.elements.buttons.mute.pressed = this.muted || this.volume === 0;\n }\n },\n\n // Update seek value and lower fill\n setRange(target, value = 0) {\n if (!is.element(target)) {\n return;\n } // eslint-disable-next-line\n\n\n target.value = value; // Webkit range fill\n\n controls.updateRangeFill.call(this, target);\n },\n\n // Update <progress> elements\n updateProgress(event) {\n if (!this.supported.ui || !is.event(event)) {\n return;\n }\n\n let value = 0;\n\n const setProgress = (target, input) => {\n const val = is.number(input) ? input : 0;\n const progress = is.element(target) ? target : this.elements.display.buffer; // Update value and label\n\n if (is.element(progress)) {\n progress.value = val; // Update text label inside\n\n const label = progress.getElementsByTagName('span')[0];\n\n if (is.element(label)) {\n label.childNodes[0].nodeValue = val;\n }\n }\n };\n\n if (event) {\n switch (event.type) {\n // Video playing\n case 'timeupdate':\n case 'seeking':\n case 'seeked':\n value = getPercentage(this.currentTime, this.duration); // Set seek range value only if it's a 'natural' time event\n\n if (event.type === 'timeupdate') {\n controls.setRange.call(this, this.elements.inputs.seek, value);\n }\n\n break;\n // Check buffer status\n\n case 'playing':\n case 'progress':\n setProgress(this.elements.display.buffer, this.buffered * 100);\n break;\n }\n }\n },\n\n // Webkit polyfill for lower fill range\n updateRangeFill(target) {\n // Get range from event if event passed\n const range = is.event(target) ? target.target : target; // Needs to be a valid <input type='range'>\n\n if (!is.element(range) || range.getAttribute('type') !== 'range') {\n return;\n } // Set aria values for https://github.com/sampotts/plyr/issues/905\n\n\n if (matches(range, this.config.selectors.inputs.seek)) {\n range.setAttribute('aria-valuenow', this.currentTime);\n const currentTime = controls.formatTime(this.currentTime);\n const duration = controls.formatTime(this.duration);\n const format = i18n.get('seekLabel', this.config);\n range.setAttribute('aria-valuetext', format.replace('{currentTime}', currentTime).replace('{duration}', duration));\n } else if (matches(range, this.config.selectors.inputs.volume)) {\n const percent = range.value * 100;\n range.setAttribute('aria-valuenow', percent);\n range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`);\n } else {\n range.setAttribute('aria-valuenow', range.value);\n } // WebKit only\n\n\n if (!browser.isWebkit) {\n return;\n } // Set CSS custom property\n\n\n range.style.setProperty('--value', `${range.value / range.max * 100}%`);\n },\n\n // Update hover tooltip for seeking\n updateSeekTooltip(event) {\n // Bail if setting not true\n if (!this.config.tooltips.seek || !is.element(this.elements.inputs.seek) || !is.element(this.elements.display.seekTooltip) || this.duration === 0) {\n return;\n }\n\n const visible = `${this.config.classNames.tooltip}--visible`;\n\n const toggle = show => toggleClass(this.elements.display.seekTooltip, visible, show); // Hide on touch\n\n\n if (this.touch) {\n toggle(false);\n return;\n } // Determine percentage, if already visible\n\n\n let percent = 0;\n const clientRect = this.elements.progress.getBoundingClientRect();\n\n if (is.event(event)) {\n percent = 100 / clientRect.width * (event.pageX - clientRect.left);\n } else if (hasClass(this.elements.display.seekTooltip, visible)) {\n percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);\n } else {\n return;\n } // Set bounds\n\n\n if (percent < 0) {\n percent = 0;\n } else if (percent > 100) {\n percent = 100;\n } // Display the time a click would seek to\n\n\n controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent); // Set position\n\n this.elements.display.seekTooltip.style.left = `${percent}%`; // Show/hide the tooltip\n // If the event is a moues in/out and percentage is inside bounds\n\n if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) {\n toggle(event.type === 'mouseenter');\n }\n },\n\n // Handle time change event\n timeUpdate(event) {\n // Only invert if only one time element is displayed and used for both duration and currentTime\n const invert = !is.element(this.elements.display.duration) && this.config.invertTime; // Duration\n\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, invert ? this.duration - this.currentTime : this.currentTime, invert); // Ignore updates while seeking\n\n if (event && event.type === 'timeupdate' && this.media.seeking) {\n return;\n } // Playing progress\n\n\n controls.updateProgress.call(this, event);\n },\n\n // Show the duration on metadataloaded or durationchange events\n durationUpdate() {\n // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false\n if (!this.supported.ui || !this.config.invertTime && this.currentTime) {\n return;\n } // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar.\n // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415\n // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062\n // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338\n\n\n if (this.duration >= 2 ** 32) {\n toggleHidden(this.elements.display.currentTime, true);\n toggleHidden(this.elements.progress, true);\n return;\n } // Update ARIA values\n\n\n if (is.element(this.elements.inputs.seek)) {\n this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration);\n } // If there's a spot to display duration\n\n\n const hasDuration = is.element(this.elements.display.duration); // If there's only one time display, display duration there\n\n if (!hasDuration && this.config.displayDuration && this.paused) {\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);\n } // If there's a duration element, update content\n\n\n if (hasDuration) {\n controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);\n } // Update the tooltip (if visible)\n\n\n controls.updateSeekTooltip.call(this);\n },\n\n // Hide/show a tab\n toggleMenuButton(setting, toggle) {\n toggleHidden(this.elements.settings.buttons[setting], !toggle);\n },\n\n // Update the selected setting\n updateSetting(setting, container, input) {\n const pane = this.elements.settings.panels[setting];\n let value = null;\n let list = container;\n\n if (setting === 'captions') {\n value = this.currentTrack;\n } else {\n value = !is.empty(input) ? input : this[setting]; // Get default\n\n if (is.empty(value)) {\n value = this.config[setting].default;\n } // Unsupported value\n\n\n if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) {\n this.debug.warn(`Unsupported value of '${value}' for ${setting}`);\n return;\n } // Disabled value\n\n\n if (!this.config[setting].options.includes(value)) {\n this.debug.warn(`Disabled value of '${value}' for ${setting}`);\n return;\n }\n } // Get the list if we need to\n\n\n if (!is.element(list)) {\n list = pane && pane.querySelector('[role=\"menu\"]');\n } // If there's no list it means it's not been rendered...\n\n\n if (!is.element(list)) {\n return;\n } // Update the label\n\n\n const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`);\n label.innerHTML = controls.getLabel.call(this, setting, value); // Find the radio option and check it\n\n const target = list && list.querySelector(`[value=\"${value}\"]`);\n\n if (is.element(target)) {\n target.checked = true;\n }\n },\n\n // Translate a value into a nice label\n getLabel(setting, value) {\n switch (setting) {\n case 'speed':\n return value === 1 ? i18n.get('normal', this.config) : `${value}×`;\n\n case 'quality':\n if (is.number(value)) {\n const label = i18n.get(`qualityLabel.${value}`, this.config);\n\n if (!label.length) {\n return `${value}p`;\n }\n\n return label;\n }\n\n return toTitleCase(value);\n\n case 'captions':\n return captions.getLabel.call(this);\n\n default:\n return null;\n }\n },\n\n // Set the quality menu\n setQualityMenu(options) {\n // Menu required\n if (!is.element(this.elements.settings.panels.quality)) {\n return;\n }\n\n const type = 'quality';\n const list = this.elements.settings.panels.quality.querySelector('[role=\"menu\"]'); // Set options if passed and filter based on uniqueness and config\n\n if (is.array(options)) {\n this.options.quality = dedupe(options).filter(quality => this.config.quality.options.includes(quality));\n } // Toggle the pane and tab\n\n\n const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1;\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If we're hiding, nothing more to do\n\n if (!toggle) {\n return;\n } // Get the badge HTML for HD, 4K etc\n\n\n const getBadge = quality => {\n const label = i18n.get(`qualityBadge.${quality}`, this.config);\n\n if (!label.length) {\n return null;\n }\n\n return controls.createBadge.call(this, label);\n }; // Sort options by the config and then render options\n\n\n this.options.quality.sort((a, b) => {\n const sorting = this.config.quality.options;\n return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1;\n }).forEach(quality => {\n controls.createMenuItem.call(this, {\n value: quality,\n list,\n type,\n title: controls.getLabel.call(this, 'quality', quality),\n badge: getBadge(quality)\n });\n });\n controls.updateSetting.call(this, type, list);\n },\n\n // Set the looping options\n\n /* setLoopMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.loop)) {\n return;\n }\n const options = ['start', 'end', 'all', 'reset'];\n const list = this.elements.settings.panels.loop.querySelector('[role=\"menu\"]');\n // Show the pane and tab\n toggleHidden(this.elements.settings.buttons.loop, false);\n toggleHidden(this.elements.settings.panels.loop, false);\n // Toggle the pane and tab\n const toggle = !is.empty(this.loop.options);\n controls.toggleMenuButton.call(this, 'loop', toggle);\n // Empty the menu\n emptyElement(list);\n options.forEach(option => {\n const item = createElement('li');\n const button = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.loop), {\n type: 'button',\n class: this.config.classNames.control,\n 'data-plyr-loop-action': option,\n }),\n i18n.get(option, this.config)\n );\n if (['start', 'end'].includes(option)) {\n const badge = controls.createBadge.call(this, '00:00');\n button.appendChild(badge);\n }\n item.appendChild(button);\n list.appendChild(item);\n });\n }, */\n // Get current selected caption language\n // TODO: rework this to user the getter in the API?\n // Set a list of available captions languages\n setCaptionsMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.captions)) {\n return;\n } // TODO: Captions or language? Currently it's mixed\n\n\n const type = 'captions';\n const list = this.elements.settings.panels.captions.querySelector('[role=\"menu\"]');\n const tracks = captions.getTracks.call(this);\n const toggle = Boolean(tracks.length); // Toggle the pane and tab\n\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If there's no captions, bail\n\n if (!toggle) {\n return;\n } // Generate options data\n\n\n const options = tracks.map((track, value) => ({\n value,\n checked: this.captions.toggled && this.currentTrack === value,\n title: captions.getLabel.call(this, track),\n badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()),\n list,\n type: 'language'\n })); // Add the \"Disabled\" option to turn off captions\n\n options.unshift({\n value: -1,\n checked: !this.captions.toggled,\n title: i18n.get('disabled', this.config),\n list,\n type: 'language'\n }); // Generate options\n\n options.forEach(controls.createMenuItem.bind(this));\n controls.updateSetting.call(this, type, list);\n },\n\n // Set a list of available captions languages\n setSpeedMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.speed)) {\n return;\n }\n\n const type = 'speed';\n const list = this.elements.settings.panels.speed.querySelector('[role=\"menu\"]'); // Filter out invalid speeds\n\n this.options.speed = this.options.speed.filter(o => o >= this.minimumSpeed && o <= this.maximumSpeed); // Toggle the pane and tab\n\n const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1;\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If we're hiding, nothing more to do\n\n if (!toggle) {\n return;\n } // Create items\n\n\n this.options.speed.forEach(speed => {\n controls.createMenuItem.call(this, {\n value: speed,\n list,\n type,\n title: controls.getLabel.call(this, 'speed', speed)\n });\n });\n controls.updateSetting.call(this, type, list);\n },\n\n // Check if we need to hide/show the settings menu\n checkMenu() {\n const {\n buttons\n } = this.elements.settings;\n const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden);\n toggleHidden(this.elements.settings.menu, !visible);\n },\n\n // Focus the first menu item in a given (or visible) menu\n focusFirstMenuItem(pane, tabFocus = false) {\n if (this.elements.settings.popup.hidden) {\n return;\n }\n\n let target = pane;\n\n if (!is.element(target)) {\n target = Object.values(this.elements.settings.panels).find(p => !p.hidden);\n }\n\n const firstItem = target.querySelector('[role^=\"menuitem\"]');\n setFocus.call(this, firstItem, tabFocus);\n },\n\n // Show/hide menu\n toggleMenu(input) {\n const {\n popup\n } = this.elements.settings;\n const button = this.elements.buttons.settings; // Menu and button are required\n\n if (!is.element(popup) || !is.element(button)) {\n return;\n } // True toggle by default\n\n\n const {\n hidden\n } = popup;\n let show = hidden;\n\n if (is.boolean(input)) {\n show = input;\n } else if (is.keyboardEvent(input) && input.which === 27) {\n show = false;\n } else if (is.event(input)) {\n // If Plyr is in a shadowDOM, the event target is set to the component, instead of the\n // Element in the shadowDOM. The path, if available, is complete.\n const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target;\n const isMenuItem = popup.contains(target); // If the click was inside the menu or if the click\n // wasn't the button or menu item and we're trying to\n // show the menu (a doc click shouldn't show the menu)\n\n if (isMenuItem || !isMenuItem && input.target !== button && show) {\n return;\n }\n } // Set button attributes\n\n\n button.setAttribute('aria-expanded', show); // Show the actual popup\n\n toggleHidden(popup, !show); // Add class hook\n\n toggleClass(this.elements.container, this.config.classNames.menu.open, show); // Focus the first item if key interaction\n\n if (show && is.keyboardEvent(input)) {\n controls.focusFirstMenuItem.call(this, null, true);\n } else if (!show && !hidden) {\n // If closing, re-focus the button\n setFocus.call(this, button, is.keyboardEvent(input));\n }\n },\n\n // Get the natural size of a menu panel\n getMenuSize(tab) {\n const clone = tab.cloneNode(true);\n clone.style.position = 'absolute';\n clone.style.opacity = 0;\n clone.removeAttribute('hidden'); // Append to parent so we get the \"real\" size\n\n tab.parentNode.appendChild(clone); // Get the sizes before we remove\n\n const width = clone.scrollWidth;\n const height = clone.scrollHeight; // Remove from the DOM\n\n removeElement(clone);\n return {\n width,\n height\n };\n },\n\n // Show a panel in the menu\n showMenuPanel(type = '', tabFocus = false) {\n const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`); // Nothing to show, bail\n\n if (!is.element(target)) {\n return;\n } // Hide all other panels\n\n\n const container = target.parentNode;\n const current = Array.from(container.children).find(node => !node.hidden); // If we can do fancy animations, we'll animate the height/width\n\n if (support.transitions && !support.reducedMotion) {\n // Set the current width as a base\n container.style.width = `${current.scrollWidth}px`;\n container.style.height = `${current.scrollHeight}px`; // Get potential sizes\n\n const size = controls.getMenuSize.call(this, target); // Restore auto height/width\n\n const restore = event => {\n // We're only bothered about height and width on the container\n if (event.target !== container || !['width', 'height'].includes(event.propertyName)) {\n return;\n } // Revert back to auto\n\n\n container.style.width = '';\n container.style.height = ''; // Only listen once\n\n off.call(this, container, transitionEndEvent, restore);\n }; // Listen for the transition finishing and restore auto height/width\n\n\n on.call(this, container, transitionEndEvent, restore); // Set dimensions to target\n\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n } // Set attributes on current tab\n\n\n toggleHidden(current, true); // Set attributes on target\n\n toggleHidden(target, false); // Focus the first item\n\n controls.focusFirstMenuItem.call(this, target, tabFocus);\n },\n\n // Set the download URL\n setDownloadUrl() {\n const button = this.elements.buttons.download; // Bail if no button\n\n if (!is.element(button)) {\n return;\n } // Set attribute\n\n\n button.setAttribute('href', this.download);\n },\n\n // Build the default HTML\n create(data) {\n const {\n bindMenuItemShortcuts,\n createButton,\n createProgress,\n createRange,\n createTime,\n setQualityMenu,\n setSpeedMenu,\n showMenuPanel\n } = controls;\n this.elements.controls = null; // Larger overlaid play button\n\n if (is.array(this.config.controls) && this.config.controls.includes('play-large')) {\n this.elements.container.appendChild(createButton.call(this, 'play-large'));\n } // Create the container\n\n\n const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper));\n this.elements.controls = container; // Default item attributes\n\n const defaultAttributes = {\n class: 'plyr__controls__item'\n }; // Loop through controls in order\n\n dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach(control => {\n // Restart button\n if (control === 'restart') {\n container.appendChild(createButton.call(this, 'restart', defaultAttributes));\n } // Rewind button\n\n\n if (control === 'rewind') {\n container.appendChild(createButton.call(this, 'rewind', defaultAttributes));\n } // Play/Pause button\n\n\n if (control === 'play') {\n container.appendChild(createButton.call(this, 'play', defaultAttributes));\n } // Fast forward button\n\n\n if (control === 'fast-forward') {\n container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes));\n } // Progress\n\n\n if (control === 'progress') {\n const progressContainer = createElement('div', {\n class: `${defaultAttributes.class} plyr__progress__container`\n });\n const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress)); // Seek range slider\n\n progress.appendChild(createRange.call(this, 'seek', {\n id: `plyr-seek-${data.id}`\n })); // Buffer progress\n\n progress.appendChild(createProgress.call(this, 'buffer')); // TODO: Add loop display indicator\n // Seek tooltip\n\n if (this.config.tooltips.seek) {\n const tooltip = createElement('span', {\n class: this.config.classNames.tooltip\n }, '00:00');\n progress.appendChild(tooltip);\n this.elements.display.seekTooltip = tooltip;\n }\n\n this.elements.progress = progress;\n progressContainer.appendChild(this.elements.progress);\n container.appendChild(progressContainer);\n } // Media current time display\n\n\n if (control === 'current-time') {\n container.appendChild(createTime.call(this, 'currentTime', defaultAttributes));\n } // Media duration display\n\n\n if (control === 'duration') {\n container.appendChild(createTime.call(this, 'duration', defaultAttributes));\n } // Volume controls\n\n\n if (control === 'mute' || control === 'volume') {\n let {\n volume\n } = this.elements; // Create the volume container if needed\n\n if (!is.element(volume) || !container.contains(volume)) {\n volume = createElement('div', extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__volume`.trim()\n }));\n this.elements.volume = volume;\n container.appendChild(volume);\n } // Toggle mute button\n\n\n if (control === 'mute') {\n volume.appendChild(createButton.call(this, 'mute'));\n } // Volume range control\n // Ignored on iOS as it's handled globally\n // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html\n\n\n if (control === 'volume' && !browser.isIos) {\n // Set the attributes\n const attributes = {\n max: 1,\n step: 0.05,\n value: this.config.volume\n }; // Create the volume range slider\n\n volume.appendChild(createRange.call(this, 'volume', extend(attributes, {\n id: `plyr-volume-${data.id}`\n })));\n }\n } // Toggle captions button\n\n\n if (control === 'captions') {\n container.appendChild(createButton.call(this, 'captions', defaultAttributes));\n } // Settings button / menu\n\n\n if (control === 'settings' && !is.empty(this.config.settings)) {\n const wrapper = createElement('div', extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__menu`.trim(),\n hidden: ''\n }));\n wrapper.appendChild(createButton.call(this, 'settings', {\n 'aria-haspopup': true,\n 'aria-controls': `plyr-settings-${data.id}`,\n 'aria-expanded': false\n }));\n const popup = createElement('div', {\n class: 'plyr__menu__container',\n id: `plyr-settings-${data.id}`,\n hidden: ''\n });\n const inner = createElement('div');\n const home = createElement('div', {\n id: `plyr-settings-${data.id}-home`\n }); // Create the menu\n\n const menu = createElement('div', {\n role: 'menu'\n });\n home.appendChild(menu);\n inner.appendChild(home);\n this.elements.settings.panels.home = home; // Build the menu items\n\n this.config.settings.forEach(type => {\n // TODO: bundle this with the createMenuItem helper and bindings\n const menuItem = createElement('button', extend(getAttributesFromSelector(this.config.selectors.buttons.settings), {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`,\n role: 'menuitem',\n 'aria-haspopup': true,\n hidden: ''\n })); // Bind menu shortcuts for keyboard users\n\n bindMenuItemShortcuts.call(this, menuItem, type); // Show menu on click\n\n on.call(this, menuItem, 'click', () => {\n showMenuPanel.call(this, type, false);\n });\n const flex = createElement('span', null, i18n.get(type, this.config));\n const value = createElement('span', {\n class: this.config.classNames.menu.value\n }); // Speed contains HTML entities\n\n value.innerHTML = data[type];\n flex.appendChild(value);\n menuItem.appendChild(flex);\n menu.appendChild(menuItem); // Build the panes\n\n const pane = createElement('div', {\n id: `plyr-settings-${data.id}-${type}`,\n hidden: ''\n }); // Back button\n\n const backButton = createElement('button', {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--back`\n }); // Visible label\n\n backButton.appendChild(createElement('span', {\n 'aria-hidden': true\n }, i18n.get(type, this.config))); // Screen reader label\n\n backButton.appendChild(createElement('span', {\n class: this.config.classNames.hidden\n }, i18n.get('menuBack', this.config))); // Go back via keyboard\n\n on.call(this, pane, 'keydown', event => {\n // We only care about <-\n if (event.which !== 37) {\n return;\n } // Prevent seek\n\n\n event.preventDefault();\n event.stopPropagation(); // Show the respective menu\n\n showMenuPanel.call(this, 'home', true);\n }, false); // Go back via button click\n\n on.call(this, backButton, 'click', () => {\n showMenuPanel.call(this, 'home', false);\n }); // Add to pane\n\n pane.appendChild(backButton); // Menu\n\n pane.appendChild(createElement('div', {\n role: 'menu'\n }));\n inner.appendChild(pane);\n this.elements.settings.buttons[type] = menuItem;\n this.elements.settings.panels[type] = pane;\n });\n popup.appendChild(inner);\n wrapper.appendChild(popup);\n container.appendChild(wrapper);\n this.elements.settings.popup = popup;\n this.elements.settings.menu = wrapper;\n } // Picture in picture button\n\n\n if (control === 'pip' && support.pip) {\n container.appendChild(createButton.call(this, 'pip', defaultAttributes));\n } // Airplay button\n\n\n if (control === 'airplay' && support.airplay) {\n container.appendChild(createButton.call(this, 'airplay', defaultAttributes));\n } // Download button\n\n\n if (control === 'download') {\n const attributes = extend({}, defaultAttributes, {\n element: 'a',\n href: this.download,\n target: '_blank'\n }); // Set download attribute for HTML5 only\n\n if (this.isHTML5) {\n attributes.download = '';\n }\n\n const {\n download\n } = this.config.urls;\n\n if (!is.url(download) && this.isEmbed) {\n extend(attributes, {\n icon: `logo-${this.provider}`,\n label: this.provider\n });\n }\n\n container.appendChild(createButton.call(this, 'download', attributes));\n } // Toggle fullscreen button\n\n\n if (control === 'fullscreen') {\n container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes));\n }\n }); // Set available quality levels\n\n if (this.isHTML5) {\n setQualityMenu.call(this, html5.getQualityOptions.call(this));\n }\n\n setSpeedMenu.call(this);\n return container;\n },\n\n // Insert controls\n inject() {\n // Sprite\n if (this.config.loadSprite) {\n const icon = controls.getIconUrl.call(this); // Only load external sprite using AJAX\n\n if (icon.cors) {\n loadSprite(icon.url, 'sprite-plyr');\n }\n } // Create a unique ID\n\n\n this.id = Math.floor(Math.random() * 10000); // Null by default\n\n let container = null;\n this.elements.controls = null; // Set template properties\n\n const props = {\n id: this.id,\n seektime: this.config.seekTime,\n title: this.config.title\n };\n let update = true; // If function, run it and use output\n\n if (is.function(this.config.controls)) {\n this.config.controls = this.config.controls.call(this, props);\n } // Convert falsy controls to empty array (primarily for empty strings)\n\n\n if (!this.config.controls) {\n this.config.controls = [];\n }\n\n if (is.element(this.config.controls) || is.string(this.config.controls)) {\n // HTMLElement or Non-empty string passed as the option\n container = this.config.controls;\n } else {\n // Create controls\n container = controls.create.call(this, {\n id: this.id,\n seektime: this.config.seekTime,\n speed: this.speed,\n quality: this.quality,\n captions: captions.getLabel.call(this) // TODO: Looping\n // loop: 'None',\n\n });\n update = false;\n } // Replace props with their value\n\n\n const replace = input => {\n let result = input;\n Object.entries(props).forEach(([key, value]) => {\n result = replaceAll(result, `{${key}}`, value);\n });\n return result;\n }; // Update markup\n\n\n if (update) {\n if (is.string(this.config.controls)) {\n container = replace(container);\n }\n } // Controls container\n\n\n let target; // Inject to custom location\n\n if (is.string(this.config.selectors.controls.container)) {\n target = document.querySelector(this.config.selectors.controls.container);\n } // Inject into the container by default\n\n\n if (!is.element(target)) {\n target = this.elements.container;\n } // Inject controls HTML (needs to be before captions, hence \"afterbegin\")\n\n\n const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML';\n target[insertMethod]('afterbegin', container); // Find the elements if need be\n\n if (!is.element(this.elements.controls)) {\n controls.findElements.call(this);\n } // Add pressed property to buttons\n\n\n if (!is.empty(this.elements.buttons)) {\n const addProperty = button => {\n const className = this.config.classNames.controlPressed;\n Object.defineProperty(button, 'pressed', {\n enumerable: true,\n\n get() {\n return hasClass(button, className);\n },\n\n set(pressed = false) {\n toggleClass(button, className, pressed);\n }\n\n });\n }; // Toggle classname when pressed property is set\n\n\n Object.values(this.elements.buttons).filter(Boolean).forEach(button => {\n if (is.array(button) || is.nodeList(button)) {\n Array.from(button).filter(Boolean).forEach(addProperty);\n } else {\n addProperty(button);\n }\n });\n } // Edge sometimes doesn't finish the paint so force a repaint\n\n\n if (browser.isEdge) {\n repaint(target);\n } // Setup tooltips\n\n\n if (this.config.tooltips.controls) {\n const {\n classNames,\n selectors\n } = this.config;\n const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`;\n const labels = getElements.call(this, selector);\n Array.from(labels).forEach(label => {\n toggleClass(label, this.config.classNames.hidden, false);\n toggleClass(label, this.config.classNames.tooltip, true);\n });\n }\n }\n\n };\n\n // ==========================================================================\n /**\n * Parse a string to a URL object\n * @param {String} input - the URL to be parsed\n * @param {Boolean} safe - failsafe parsing\n */\n\n function parseUrl(input, safe = true) {\n let url = input;\n\n if (safe) {\n const parser = document.createElement('a');\n parser.href = url;\n url = parser.href;\n }\n\n try {\n return new URL(url);\n } catch (_) {\n return null;\n }\n } // Convert object to URLSearchParams\n\n function buildUrlParams(input) {\n const params = new URLSearchParams();\n\n if (is.object(input)) {\n Object.entries(input).forEach(([key, value]) => {\n params.set(key, value);\n });\n }\n\n return params;\n }\n\n // ==========================================================================\n const captions = {\n // Setup captions\n setup() {\n // Requires UI support\n if (!this.supported.ui) {\n return;\n } // Only Vimeo and HTML5 video supported at this point\n\n\n if (!this.isVideo || this.isYouTube || this.isHTML5 && !support.textTracks) {\n // Clear menu and hide\n if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) {\n controls.setCaptionsMenu.call(this);\n }\n\n return;\n } // Inject the container\n\n\n if (!is.element(this.elements.captions)) {\n this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions));\n insertAfter(this.elements.captions, this.elements.wrapper);\n } // Fix IE captions if CORS is used\n // Fetch captions and inject as blobs instead (data URIs not supported!)\n\n\n if (browser.isIE && window.URL) {\n const elements = this.media.querySelectorAll('track');\n Array.from(elements).forEach(track => {\n const src = track.getAttribute('src');\n const url = parseUrl(src);\n\n if (url !== null && url.hostname !== window.location.href.hostname && ['http:', 'https:'].includes(url.protocol)) {\n fetch(src, 'blob').then(blob => {\n track.setAttribute('src', window.URL.createObjectURL(blob));\n }).catch(() => {\n removeElement(track);\n });\n }\n });\n } // Get and set initial data\n // The \"preferred\" options are not realized unless / until the wanted language has a match\n // * languages: Array of user's browser languages.\n // * language: The language preferred by user settings or config\n // * active: The state preferred by user settings or config\n // * toggled: The real captions state\n\n\n const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en'];\n const languages = dedupe(browserLanguages.map(language => language.split('-')[0]));\n let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase(); // Use first browser language when language is 'auto'\n\n if (language === 'auto') {\n [language] = languages;\n }\n\n let active = this.storage.get('captions');\n\n if (!is.boolean(active)) {\n ({\n active\n } = this.config.captions);\n }\n\n Object.assign(this.captions, {\n toggled: false,\n active,\n language,\n languages\n }); // Watch changes to textTracks and update captions menu\n\n if (this.isHTML5) {\n const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack';\n on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this));\n } // Update available languages in list next tick (the event must not be triggered before the listeners)\n\n\n setTimeout(captions.update.bind(this), 0);\n },\n\n // Update available language options in settings based on tracks\n update() {\n const tracks = captions.getTracks.call(this, true); // Get the wanted language\n\n const {\n active,\n language,\n meta,\n currentTrackNode\n } = this.captions;\n const languageExists = Boolean(tracks.find(track => track.language === language)); // Handle tracks (add event listener and \"pseudo\"-default)\n\n if (this.isHTML5 && this.isVideo) {\n tracks.filter(track => !meta.get(track)).forEach(track => {\n this.debug.log('Track added', track); // Attempt to store if the original dom element was \"default\"\n\n meta.set(track, {\n default: track.mode === 'showing'\n }); // Turn off native caption rendering to avoid double captions\n // Note: mode='hidden' forces a track to download. To ensure every track\n // isn't downloaded at once, only 'showing' tracks should be reassigned\n // eslint-disable-next-line no-param-reassign\n\n if (track.mode === 'showing') {\n // eslint-disable-next-line no-param-reassign\n track.mode = 'hidden';\n } // Add event listener for cue changes\n\n\n on.call(this, track, 'cuechange', () => captions.updateCues.call(this));\n });\n } // Update language first time it matches, or if the previous matching track was removed\n\n\n if (languageExists && this.language !== language || !tracks.includes(currentTrackNode)) {\n captions.setLanguage.call(this, language);\n captions.toggle.call(this, active && languageExists);\n } // Enable or disable captions based on track length\n\n\n if (this.elements) {\n toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks));\n } // Update available languages in list\n\n\n if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) {\n controls.setCaptionsMenu.call(this);\n }\n },\n\n // Toggle captions display\n // Used internally for the toggleCaptions method, with the passive option forced to false\n toggle(input, passive = true) {\n // If there's no full support\n if (!this.supported.ui) {\n return;\n }\n\n const {\n toggled\n } = this.captions; // Current state\n\n const activeClass = this.config.classNames.captions.active; // Get the next state\n // If the method is called without parameter, toggle based on current value\n\n const active = is.nullOrUndefined(input) ? !toggled : input; // Update state and trigger event\n\n if (active !== toggled) {\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.active = active;\n this.storage.set({\n captions: active\n });\n } // Force language if the call isn't passive and there is no matching language to toggle to\n\n\n if (!this.language && active && !passive) {\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true); // Override user preferences to avoid switching languages if a matching track is added\n\n this.captions.language = track.language; // Set caption, but don't store in localStorage as user preference\n\n captions.set.call(this, tracks.indexOf(track));\n return;\n } // Toggle button if it's enabled\n\n\n if (this.elements.buttons.captions) {\n this.elements.buttons.captions.pressed = active;\n } // Add class hook\n\n\n toggleClass(this.elements.container, activeClass, active);\n this.captions.toggled = active; // Update settings menu\n\n controls.updateSetting.call(this, 'captions'); // Trigger event (not used internally)\n\n triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled');\n } // Wait for the call stack to clear before setting mode='hidden'\n // on the active track - forcing the browser to download it\n\n\n setTimeout(() => {\n if (active && this.captions.toggled) {\n this.captions.currentTrackNode.mode = 'hidden';\n }\n });\n },\n\n // Set captions by track index\n // Used internally for the currentTrack setter with the passive option forced to false\n set(index, passive = true) {\n const tracks = captions.getTracks.call(this); // Disable captions if setting to -1\n\n if (index === -1) {\n captions.toggle.call(this, false, passive);\n return;\n }\n\n if (!is.number(index)) {\n this.debug.warn('Invalid caption argument', index);\n return;\n }\n\n if (!(index in tracks)) {\n this.debug.warn('Track not found', index);\n return;\n }\n\n if (this.captions.currentTrack !== index) {\n this.captions.currentTrack = index;\n const track = tracks[index];\n const {\n language\n } = track || {}; // Store reference to node for invalidation on remove\n\n this.captions.currentTrackNode = track; // Update settings menu\n\n controls.updateSetting.call(this, 'captions'); // When passive, don't override user preferences\n\n if (!passive) {\n this.captions.language = language;\n this.storage.set({\n language\n });\n } // Handle Vimeo captions\n\n\n if (this.isVimeo) {\n this.embed.enableTextTrack(language);\n } // Trigger event\n\n\n triggerEvent.call(this, this.media, 'languagechange');\n } // Show captions\n\n\n captions.toggle.call(this, true, passive);\n\n if (this.isHTML5 && this.isVideo) {\n // If we change the active track while a cue is already displayed we need to update it\n captions.updateCues.call(this);\n }\n },\n\n // Set captions by language\n // Used internally for the language setter with the passive option forced to false\n setLanguage(input, passive = true) {\n if (!is.string(input)) {\n this.debug.warn('Invalid language argument', input);\n return;\n } // Normalize\n\n\n const language = input.toLowerCase();\n this.captions.language = language; // Set currentTrack\n\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [language]);\n captions.set.call(this, tracks.indexOf(track), passive);\n },\n\n // Get current valid caption tracks\n // If update is false it will also ignore tracks without metadata\n // This is used to \"freeze\" the language options when captions.update is false\n getTracks(update = false) {\n // Handle media or textTracks missing or null\n const tracks = Array.from((this.media || {}).textTracks || []); // For HTML5, use cache instead of current tracks when it exists (if captions.update is false)\n // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata)\n\n return tracks.filter(track => !this.isHTML5 || update || this.captions.meta.has(track)).filter(track => ['captions', 'subtitles'].includes(track.kind));\n },\n\n // Match tracks based on languages and get the first\n findTrack(languages, force = false) {\n const tracks = captions.getTracks.call(this);\n\n const sortIsDefault = track => Number((this.captions.meta.get(track) || {}).default);\n\n const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a));\n let track;\n languages.every(language => {\n track = sorted.find(t => t.language === language);\n return !track; // Break iteration if there is a match\n }); // If no match is found but is required, get first\n\n return track || (force ? sorted[0] : undefined);\n },\n\n // Get the current track\n getCurrentTrack() {\n return captions.getTracks.call(this)[this.currentTrack];\n },\n\n // Get UI label for track\n getLabel(track) {\n let currentTrack = track;\n\n if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) {\n currentTrack = captions.getCurrentTrack.call(this);\n }\n\n if (is.track(currentTrack)) {\n if (!is.empty(currentTrack.label)) {\n return currentTrack.label;\n }\n\n if (!is.empty(currentTrack.language)) {\n return track.language.toUpperCase();\n }\n\n return i18n.get('enabled', this.config);\n }\n\n return i18n.get('disabled', this.config);\n },\n\n // Update captions using current track's active cues\n // Also optional array argument in case there isn't any track (ex: vimeo)\n updateCues(input) {\n // Requires UI\n if (!this.supported.ui) {\n return;\n }\n\n if (!is.element(this.elements.captions)) {\n this.debug.warn('No captions element to render to');\n return;\n } // Only accept array or empty input\n\n\n if (!is.nullOrUndefined(input) && !Array.isArray(input)) {\n this.debug.warn('updateCues: Invalid input', input);\n return;\n }\n\n let cues = input; // Get cues from track\n\n if (!cues) {\n const track = captions.getCurrentTrack.call(this);\n cues = Array.from((track || {}).activeCues || []).map(cue => cue.getCueAsHTML()).map(getHTML);\n } // Set new caption text\n\n\n const content = cues.map(cueText => cueText.trim()).join('\\n');\n const changed = content !== this.elements.captions.innerHTML;\n\n if (changed) {\n // Empty the container and create a new child element\n emptyElement(this.elements.captions);\n const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption));\n caption.innerHTML = content;\n this.elements.captions.appendChild(caption); // Trigger event\n\n triggerEvent.call(this, this.media, 'cuechange');\n }\n }\n\n };\n\n // ==========================================================================\n // Plyr default config\n // ==========================================================================\n const defaults = {\n // Disable\n enabled: true,\n // Custom media title\n title: '',\n // Logging to console\n debug: false,\n // Auto play (if supported)\n autoplay: false,\n // Only allow one media playing at once (vimeo only)\n autopause: true,\n // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present)\n // TODO: Remove iosNative fullscreen option in favour of this (logic needs work)\n playsinline: true,\n // Default time to skip when rewind/fast forward\n seekTime: 10,\n // Default volume\n volume: 1,\n muted: false,\n // Pass a custom duration\n duration: null,\n // Display the media duration on load in the current time position\n // If you have opted to display both duration and currentTime, this is ignored\n displayDuration: true,\n // Invert the current time to be a countdown\n invertTime: true,\n // Clicking the currentTime inverts it's value to show time left rather than elapsed\n toggleInvert: true,\n // Force an aspect ratio\n // The format must be `'w:h'` (e.g. `'16:9'`)\n ratio: null,\n // Click video container to play/pause\n clickToPlay: true,\n // Auto hide the controls\n hideControls: true,\n // Reset to start when playback ended\n resetOnEnd: false,\n // Disable the standard context menu\n disableContextMenu: true,\n // Sprite (for icons)\n loadSprite: true,\n iconPrefix: 'plyr',\n iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg',\n // Blank video (used to prevent errors on source change)\n blankVideo: 'https://cdn.plyr.io/static/blank.mp4',\n // Quality default\n quality: {\n default: 576,\n // The options to display in the UI, if available for the source media\n options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240],\n forced: false,\n onChange: null\n },\n // Set loops\n loop: {\n active: false // start: null,\n // end: null,\n\n },\n // Speed default and options to display\n speed: {\n selected: 1,\n // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x)\n options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4]\n },\n // Keyboard shortcut settings\n keyboard: {\n focused: true,\n global: false\n },\n // Display tooltips\n tooltips: {\n controls: false,\n seek: true\n },\n // Captions settings\n captions: {\n active: false,\n language: 'auto',\n // Listen to new tracks added after Plyr is initialized.\n // This is needed for streaming captions, but may result in unselectable options\n update: false\n },\n // Fullscreen settings\n fullscreen: {\n enabled: true,\n // Allow fullscreen?\n fallback: true,\n // Fallback using full viewport/window\n iosNative: false // Use the native fullscreen in iOS (disables custom controls)\n // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode\n // Non-ancestors of the player element will be ignored\n // container: null, // defaults to the player element\n\n },\n // Local storage\n storage: {\n enabled: true,\n key: 'plyr'\n },\n // Default controls\n controls: ['play-large', // 'restart',\n // 'rewind',\n 'play', // 'fast-forward',\n 'progress', 'current-time', // 'duration',\n 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', // 'download',\n 'fullscreen'],\n settings: ['captions', 'quality', 'speed'],\n // Localisation\n i18n: {\n restart: 'Restart',\n rewind: 'Rewind {seektime}s',\n play: 'Play',\n pause: 'Pause',\n fastForward: 'Forward {seektime}s',\n seek: 'Seek',\n seekLabel: '{currentTime} of {duration}',\n played: 'Played',\n buffered: 'Buffered',\n currentTime: 'Current time',\n duration: 'Duration',\n volume: 'Volume',\n mute: 'Mute',\n unmute: 'Unmute',\n enableCaptions: 'Enable captions',\n disableCaptions: 'Disable captions',\n download: 'Download',\n enterFullscreen: 'Enter fullscreen',\n exitFullscreen: 'Exit fullscreen',\n frameTitle: 'Player for {title}',\n captions: 'Captions',\n settings: 'Settings',\n pip: 'PIP',\n menuBack: 'Go back to previous menu',\n speed: 'Speed',\n normal: 'Normal',\n quality: 'Quality',\n loop: 'Loop',\n start: 'Start',\n end: 'End',\n all: 'All',\n reset: 'Reset',\n disabled: 'Disabled',\n enabled: 'Enabled',\n advertisement: 'Ad',\n qualityBadge: {\n 2160: '4K',\n 1440: 'HD',\n 1080: 'HD',\n 720: 'HD',\n 576: 'SD',\n 480: 'SD'\n }\n },\n // URLs\n urls: {\n download: null,\n vimeo: {\n sdk: 'https://player.vimeo.com/api/player.js',\n iframe: 'https://player.vimeo.com/video/{0}?{1}',\n api: 'https://vimeo.com/api/oembed.json?url={0}'\n },\n youtube: {\n sdk: 'https://www.youtube.com/iframe_api',\n api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}'\n },\n googleIMA: {\n sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js'\n }\n },\n // Custom control listeners\n listeners: {\n seek: null,\n play: null,\n pause: null,\n restart: null,\n rewind: null,\n fastForward: null,\n mute: null,\n volume: null,\n captions: null,\n download: null,\n fullscreen: null,\n pip: null,\n airplay: null,\n speed: null,\n quality: null,\n loop: null,\n language: null\n },\n // Events to watch and bubble\n events: [// Events to watch on HTML5 media elements and bubble\n // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events\n 'ended', 'progress', 'stalled', 'playing', 'waiting', 'canplay', 'canplaythrough', 'loadstart', 'loadeddata', 'loadedmetadata', 'timeupdate', 'volumechange', 'play', 'pause', 'error', 'seeking', 'seeked', 'emptied', 'ratechange', 'cuechange', // Custom events\n 'download', 'enterfullscreen', 'exitfullscreen', 'captionsenabled', 'captionsdisabled', 'languagechange', 'controlshidden', 'controlsshown', 'ready', // YouTube\n 'statechange', // Quality\n 'qualitychange', // Ads\n 'adsloaded', 'adscontentpause', 'adscontentresume', 'adstarted', 'adsmidpoint', 'adscomplete', 'adsallcomplete', 'adsimpression', 'adsclick'],\n // Selectors\n // Change these to match your template if using custom HTML\n selectors: {\n editable: 'input, textarea, select, [contenteditable]',\n container: '.plyr',\n controls: {\n container: null,\n wrapper: '.plyr__controls'\n },\n labels: '[data-plyr]',\n buttons: {\n play: '[data-plyr=\"play\"]',\n pause: '[data-plyr=\"pause\"]',\n restart: '[data-plyr=\"restart\"]',\n rewind: '[data-plyr=\"rewind\"]',\n fastForward: '[data-plyr=\"fast-forward\"]',\n mute: '[data-plyr=\"mute\"]',\n captions: '[data-plyr=\"captions\"]',\n download: '[data-plyr=\"download\"]',\n fullscreen: '[data-plyr=\"fullscreen\"]',\n pip: '[data-plyr=\"pip\"]',\n airplay: '[data-plyr=\"airplay\"]',\n settings: '[data-plyr=\"settings\"]',\n loop: '[data-plyr=\"loop\"]'\n },\n inputs: {\n seek: '[data-plyr=\"seek\"]',\n volume: '[data-plyr=\"volume\"]',\n speed: '[data-plyr=\"speed\"]',\n language: '[data-plyr=\"language\"]',\n quality: '[data-plyr=\"quality\"]'\n },\n display: {\n currentTime: '.plyr__time--current',\n duration: '.plyr__time--duration',\n buffer: '.plyr__progress__buffer',\n loop: '.plyr__progress__loop',\n // Used later\n volume: '.plyr__volume--display'\n },\n progress: '.plyr__progress',\n captions: '.plyr__captions',\n caption: '.plyr__caption'\n },\n // Class hooks added to the player in different states\n classNames: {\n type: 'plyr--{0}',\n provider: 'plyr--{0}',\n video: 'plyr__video-wrapper',\n embed: 'plyr__video-embed',\n videoFixedRatio: 'plyr__video-wrapper--fixed-ratio',\n embedContainer: 'plyr__video-embed__container',\n poster: 'plyr__poster',\n posterEnabled: 'plyr__poster-enabled',\n ads: 'plyr__ads',\n control: 'plyr__control',\n controlPressed: 'plyr__control--pressed',\n playing: 'plyr--playing',\n paused: 'plyr--paused',\n stopped: 'plyr--stopped',\n loading: 'plyr--loading',\n hover: 'plyr--hover',\n tooltip: 'plyr__tooltip',\n cues: 'plyr__cues',\n hidden: 'plyr__sr-only',\n hideControls: 'plyr--hide-controls',\n isIos: 'plyr--is-ios',\n isTouch: 'plyr--is-touch',\n uiSupported: 'plyr--full-ui',\n noTransition: 'plyr--no-transition',\n display: {\n time: 'plyr__time'\n },\n menu: {\n value: 'plyr__menu__value',\n badge: 'plyr__badge',\n open: 'plyr--menu-open'\n },\n captions: {\n enabled: 'plyr--captions-enabled',\n active: 'plyr--captions-active'\n },\n fullscreen: {\n enabled: 'plyr--fullscreen-enabled',\n fallback: 'plyr--fullscreen-fallback'\n },\n pip: {\n supported: 'plyr--pip-supported',\n active: 'plyr--pip-active'\n },\n airplay: {\n supported: 'plyr--airplay-supported',\n active: 'plyr--airplay-active'\n },\n tabFocus: 'plyr__tab-focus',\n previewThumbnails: {\n // Tooltip thumbs\n thumbContainer: 'plyr__preview-thumb',\n thumbContainerShown: 'plyr__preview-thumb--is-shown',\n imageContainer: 'plyr__preview-thumb__image-container',\n timeContainer: 'plyr__preview-thumb__time-container',\n // Scrubbing\n scrubbingContainer: 'plyr__preview-scrubbing',\n scrubbingContainerShown: 'plyr__preview-scrubbing--is-shown'\n }\n },\n // Embed attributes\n attributes: {\n embed: {\n provider: 'data-plyr-provider',\n id: 'data-plyr-embed-id',\n hash: 'data-plyr-embed-hash'\n }\n },\n // Advertisements plugin\n // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio\n ads: {\n enabled: false,\n publisherId: '',\n tagUrl: ''\n },\n // Preview Thumbnails plugin\n previewThumbnails: {\n enabled: false,\n src: ''\n },\n // Vimeo plugin\n vimeo: {\n byline: false,\n portrait: false,\n title: false,\n speed: true,\n transparent: false,\n // Custom settings from Plyr\n customControls: true,\n referrerPolicy: null,\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy\n // Whether the owner of the video has a Pro or Business account\n // (which allows us to properly hide controls without CSS hacks, etc)\n premium: false\n },\n // YouTube plugin\n youtube: {\n rel: 0,\n // No related vids\n showinfo: 0,\n // Hide info\n iv_load_policy: 3,\n // Hide annotations\n modestbranding: 1,\n // Hide logos as much as possible (they still show one in the corner when paused)\n // Custom settings from Plyr\n customControls: true,\n noCookie: false // Whether to use an alternative version of YouTube without cookies\n\n }\n };\n\n // ==========================================================================\n // Plyr states\n // ==========================================================================\n const pip = {\n active: 'picture-in-picture',\n inactive: 'inline'\n };\n\n // ==========================================================================\n // Plyr supported types and providers\n // ==========================================================================\n const providers = {\n html5: 'html5',\n youtube: 'youtube',\n vimeo: 'vimeo'\n };\n const types = {\n audio: 'audio',\n video: 'video'\n };\n /**\n * Get provider by URL\n * @param {String} url\n */\n\n function getProviderByUrl(url) {\n // YouTube\n if (/^(https?:\\/\\/)?(www\\.)?(youtube\\.com|youtube-nocookie\\.com|youtu\\.?be)\\/.+$/.test(url)) {\n return providers.youtube;\n } // Vimeo\n\n\n if (/^https?:\\/\\/player.vimeo.com\\/video\\/\\d{0,9}(?=\\b|\\/)/.test(url)) {\n return providers.vimeo;\n }\n\n return null;\n }\n\n // ==========================================================================\n // Console wrapper\n // ==========================================================================\n const noop = () => {};\n\n class Console {\n constructor(enabled = false) {\n this.enabled = window.console && enabled;\n\n if (this.enabled) {\n this.log('Debugging enabled');\n }\n }\n\n get log() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.log, console) : noop;\n }\n\n get warn() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop;\n }\n\n get error() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.error, console) : noop;\n }\n\n }\n\n class Fullscreen {\n constructor(player) {\n _defineProperty$1(this, \"onChange\", () => {\n if (!this.enabled) {\n return;\n } // Update toggle button\n\n\n const button = this.player.elements.buttons.fullscreen;\n\n if (is.element(button)) {\n button.pressed = this.active;\n } // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up\n\n\n const target = this.target === this.player.media ? this.target : this.player.elements.container; // Trigger an event\n\n triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true);\n });\n\n _defineProperty$1(this, \"toggleFallback\", (toggle = false) => {\n // Store or restore scroll position\n if (toggle) {\n this.scrollPosition = {\n x: window.scrollX || 0,\n y: window.scrollY || 0\n };\n } else {\n window.scrollTo(this.scrollPosition.x, this.scrollPosition.y);\n } // Toggle scroll\n\n\n document.body.style.overflow = toggle ? 'hidden' : ''; // Toggle class hook\n\n toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle); // Force full viewport on iPhone X+\n\n if (browser.isIos) {\n let viewport = document.head.querySelector('meta[name=\"viewport\"]');\n const property = 'viewport-fit=cover'; // Inject the viewport meta if required\n\n if (!viewport) {\n viewport = document.createElement('meta');\n viewport.setAttribute('name', 'viewport');\n } // Check if the property already exists\n\n\n const hasProperty = is.string(viewport.content) && viewport.content.includes(property);\n\n if (toggle) {\n this.cleanupViewport = !hasProperty;\n\n if (!hasProperty) {\n viewport.content += `,${property}`;\n }\n } else if (this.cleanupViewport) {\n viewport.content = viewport.content.split(',').filter(part => part.trim() !== property).join(',');\n }\n } // Toggle button and fire events\n\n\n this.onChange();\n });\n\n _defineProperty$1(this, \"trapFocus\", event => {\n // Bail if iOS, not active, not the tab key\n if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) {\n return;\n } // Get the current focused element\n\n\n const focused = document.activeElement;\n const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]');\n const [first] = focusable;\n const last = focusable[focusable.length - 1];\n\n if (focused === last && !event.shiftKey) {\n // Move focus to first element that can be tabbed if Shift isn't used\n first.focus();\n event.preventDefault();\n } else if (focused === first && event.shiftKey) {\n // Move focus to last element that can be tabbed if Shift is used\n last.focus();\n event.preventDefault();\n }\n });\n\n _defineProperty$1(this, \"update\", () => {\n if (this.enabled) {\n let mode;\n\n if (this.forceFallback) {\n mode = 'Fallback (forced)';\n } else if (Fullscreen.native) {\n mode = 'Native';\n } else {\n mode = 'Fallback';\n }\n\n this.player.debug.log(`${mode} fullscreen enabled`);\n } else {\n this.player.debug.log('Fullscreen not supported and fallback disabled');\n } // Add styling hook to show button\n\n\n toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled);\n });\n\n _defineProperty$1(this, \"enter\", () => {\n if (!this.enabled) {\n return;\n } // iOS native fullscreen doesn't need the request step\n\n\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n if (this.player.isVimeo) {\n this.player.embed.requestFullscreen();\n } else {\n this.target.webkitEnterFullscreen();\n }\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(true);\n } else if (!this.prefix) {\n this.target.requestFullscreen({\n navigationUI: 'hide'\n });\n } else if (!is.empty(this.prefix)) {\n this.target[`${this.prefix}Request${this.property}`]();\n }\n });\n\n _defineProperty$1(this, \"exit\", () => {\n if (!this.enabled) {\n return;\n } // iOS native fullscreen\n\n\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n this.target.webkitExitFullscreen();\n silencePromise(this.player.play());\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(false);\n } else if (!this.prefix) {\n (document.cancelFullScreen || document.exitFullscreen).call(document);\n } else if (!is.empty(this.prefix)) {\n const action = this.prefix === 'moz' ? 'Cancel' : 'Exit';\n document[`${this.prefix}${action}${this.property}`]();\n }\n });\n\n _defineProperty$1(this, \"toggle\", () => {\n if (!this.active) {\n this.enter();\n } else {\n this.exit();\n }\n });\n\n // Keep reference to parent\n this.player = player; // Get prefix\n\n this.prefix = Fullscreen.prefix;\n this.property = Fullscreen.property; // Scroll position\n\n this.scrollPosition = {\n x: 0,\n y: 0\n }; // Force the use of 'full window/browser' rather than fullscreen\n\n this.forceFallback = player.config.fullscreen.fallback === 'force'; // Get the fullscreen element\n // Checks container is an ancestor, defaults to null\n\n this.player.elements.fullscreen = player.config.fullscreen.container && closest$1(this.player.elements.container, player.config.fullscreen.container); // Register event listeners\n // Handle event (incase user presses escape etc)\n\n on.call(this.player, document, this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`, () => {\n // TODO: Filter for target??\n this.onChange();\n }); // Fullscreen toggle on double click\n\n on.call(this.player, this.player.elements.container, 'dblclick', event => {\n // Ignore double click in controls\n if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) {\n return;\n }\n\n this.player.listeners.proxy(event, this.toggle, 'fullscreen');\n }); // Tap focus when in fullscreen\n\n on.call(this, this.player.elements.container, 'keydown', event => this.trapFocus(event)); // Update the UI\n\n this.update(); // this.toggle = this.toggle.bind(this);\n } // Determine if native supported\n\n\n static get native() {\n return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled);\n } // If we're actually using native\n\n\n get usingNative() {\n return Fullscreen.native && !this.forceFallback;\n } // Get the prefix for handlers\n\n\n static get prefix() {\n // No prefix\n if (is.function(document.exitFullscreen)) {\n return '';\n } // Check for fullscreen support by vendor prefix\n\n\n let value = '';\n const prefixes = ['webkit', 'moz', 'ms'];\n prefixes.some(pre => {\n if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) {\n value = pre;\n return true;\n }\n\n return false;\n });\n return value;\n }\n\n static get property() {\n return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen';\n } // Determine if fullscreen is enabled\n\n\n get enabled() {\n return (Fullscreen.native || this.player.config.fullscreen.fallback) && this.player.config.fullscreen.enabled && this.player.supported.ui && this.player.isVideo;\n } // Get active state\n\n\n get active() {\n if (!this.enabled) {\n return false;\n } // Fallback using classname\n\n\n if (!Fullscreen.native || this.forceFallback) {\n return hasClass(this.target, this.player.config.classNames.fullscreen.fallback);\n }\n\n const element = !this.prefix ? this.target.getRootNode().fullscreenElement : this.target.getRootNode()[`${this.prefix}${this.property}Element`];\n return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target;\n } // Get target element\n\n\n get target() {\n return browser.isIos && this.player.config.fullscreen.iosNative ? this.player.media : this.player.elements.fullscreen || this.player.elements.container;\n }\n\n }\n\n // ==========================================================================\n // Load image avoiding xhr/fetch CORS issues\n // Server status can't be obtained this way unfortunately, so this uses \"naturalWidth\" to determine if the image has loaded\n // By default it checks if it is at least 1px, but you can add a second argument to change this\n // ==========================================================================\n function loadImage(src, minWidth = 1) {\n return new Promise((resolve, reject) => {\n const image = new Image();\n\n const handler = () => {\n delete image.onload;\n delete image.onerror;\n (image.naturalWidth >= minWidth ? resolve : reject)(image);\n };\n\n Object.assign(image, {\n onload: handler,\n onerror: handler,\n src\n });\n });\n }\n\n // ==========================================================================\n const ui = {\n addStyleHook() {\n toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);\n toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);\n },\n\n // Toggle native HTML5 media controls\n toggleNativeControls(toggle = false) {\n if (toggle && this.isHTML5) {\n this.media.setAttribute('controls', '');\n } else {\n this.media.removeAttribute('controls');\n }\n },\n\n // Setup the UI\n build() {\n // Re-attach media element listeners\n // TODO: Use event bubbling?\n this.listeners.media(); // Don't setup interface if no support\n\n if (!this.supported.ui) {\n this.debug.warn(`Basic support only for ${this.provider} ${this.type}`); // Restore native controls\n\n ui.toggleNativeControls.call(this, true); // Bail\n\n return;\n } // Inject custom controls if not present\n\n\n if (!is.element(this.elements.controls)) {\n // Inject custom controls\n controls.inject.call(this); // Re-attach control listeners\n\n this.listeners.controls();\n } // Remove native controls\n\n\n ui.toggleNativeControls.call(this); // Setup captions for HTML5\n\n if (this.isHTML5) {\n captions.setup.call(this);\n } // Reset volume\n\n\n this.volume = null; // Reset mute state\n\n this.muted = null; // Reset loop state\n\n this.loop = null; // Reset quality setting\n\n this.quality = null; // Reset speed\n\n this.speed = null; // Reset volume display\n\n controls.updateVolume.call(this); // Reset time display\n\n controls.timeUpdate.call(this); // Reset duration display\n\n controls.durationUpdate.call(this); // Update the UI\n\n ui.checkPlaying.call(this); // Check for picture-in-picture support\n\n toggleClass(this.elements.container, this.config.classNames.pip.supported, support.pip && this.isHTML5 && this.isVideo); // Check for airplay support\n\n toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5); // Add iOS class\n\n toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos); // Add touch class\n\n toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch); // Ready for API calls\n\n this.ready = true; // Ready event at end of execution stack\n\n setTimeout(() => {\n triggerEvent.call(this, this.media, 'ready');\n }, 0); // Set the title\n\n ui.setTitle.call(this); // Assure the poster image is set, if the property was added before the element was created\n\n if (this.poster) {\n ui.setPoster.call(this, this.poster, false).catch(() => {});\n } // Manually set the duration if user has overridden it.\n // The event listeners for it doesn't get called if preload is disabled (#701)\n\n\n if (this.config.duration) {\n controls.durationUpdate.call(this);\n }\n },\n\n // Setup aria attribute for play and iframe title\n setTitle() {\n // Find the current text\n let label = i18n.get('play', this.config); // If there's a media title set, use that for the label\n\n if (is.string(this.config.title) && !is.empty(this.config.title)) {\n label += `, ${this.config.title}`;\n } // If there's a play button, set label\n\n\n Array.from(this.elements.buttons.play || []).forEach(button => {\n button.setAttribute('aria-label', label);\n }); // Set iframe title\n // https://github.com/sampotts/plyr/issues/124\n\n if (this.isEmbed) {\n const iframe = getElement.call(this, 'iframe');\n\n if (!is.element(iframe)) {\n return;\n } // Default to media type\n\n\n const title = !is.empty(this.config.title) ? this.config.title : 'video';\n const format = i18n.get('frameTitle', this.config);\n iframe.setAttribute('title', format.replace('{title}', title));\n }\n },\n\n // Toggle poster\n togglePoster(enable) {\n toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);\n },\n\n // Set the poster image (async)\n // Used internally for the poster setter, with the passive option forced to false\n setPoster(poster, passive = true) {\n // Don't override if call is passive\n if (passive && this.poster) {\n return Promise.reject(new Error('Poster already set'));\n } // Set property synchronously to respect the call order\n\n\n this.media.setAttribute('data-poster', poster); // Show the poster\n\n this.elements.poster.removeAttribute('hidden'); // Wait until ui is ready\n\n return ready.call(this) // Load image\n .then(() => loadImage(poster)).catch(error => {\n // Hide poster on error unless it's been set by another call\n if (poster === this.poster) {\n ui.togglePoster.call(this, false);\n } // Rethrow\n\n\n throw error;\n }).then(() => {\n // Prevent race conditions\n if (poster !== this.poster) {\n throw new Error('setPoster cancelled by later call to setPoster');\n }\n }).then(() => {\n Object.assign(this.elements.poster.style, {\n backgroundImage: `url('${poster}')`,\n // Reset backgroundSize as well (since it can be set to \"cover\" for padded thumbnails for youtube)\n backgroundSize: ''\n });\n ui.togglePoster.call(this, true);\n return poster;\n });\n },\n\n // Check playing state\n checkPlaying(event) {\n // Class hooks\n toggleClass(this.elements.container, this.config.classNames.playing, this.playing);\n toggleClass(this.elements.container, this.config.classNames.paused, this.paused);\n toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped); // Set state\n\n Array.from(this.elements.buttons.play || []).forEach(target => {\n Object.assign(target, {\n pressed: this.playing\n });\n target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config));\n }); // Only update controls on non timeupdate events\n\n if (is.event(event) && event.type === 'timeupdate') {\n return;\n } // Toggle controls\n\n\n ui.toggleControls.call(this);\n },\n\n // Check if media is loading\n checkLoading(event) {\n this.loading = ['stalled', 'waiting'].includes(event.type); // Clear timer\n\n clearTimeout(this.timers.loading); // Timer to prevent flicker when seeking\n\n this.timers.loading = setTimeout(() => {\n // Update progress bar loading class state\n toggleClass(this.elements.container, this.config.classNames.loading, this.loading); // Update controls visibility\n\n ui.toggleControls.call(this);\n }, this.loading ? 250 : 0);\n },\n\n // Toggle controls based on state and `force` argument\n toggleControls(force) {\n const {\n controls: controlsElement\n } = this.elements;\n\n if (controlsElement && this.config.hideControls) {\n // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.)\n const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now(); // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide\n\n this.toggleControls(Boolean(force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek));\n }\n },\n\n // Migrate any custom properties from the media to the parent\n migrateStyles() {\n // Loop through values (as they are the keys when the object is spread 🤔)\n Object.values({ ...this.media.style\n }) // We're only fussed about Plyr specific properties\n .filter(key => !is.empty(key) && is.string(key) && key.startsWith('--plyr')).forEach(key => {\n // Set on the container\n this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key)); // Clean up from media element\n\n this.media.style.removeProperty(key);\n }); // Remove attribute if empty\n\n if (is.empty(this.media.style)) {\n this.media.removeAttribute('style');\n }\n }\n\n };\n\n class Listeners {\n constructor(_player) {\n _defineProperty$1(this, \"firstTouch\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n player.touch = true; // Add touch class\n\n toggleClass(elements.container, player.config.classNames.isTouch, true);\n });\n\n _defineProperty$1(this, \"setTabFocus\", event => {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n clearTimeout(this.focusTimer); // Ignore any key other than tab\n\n if (event.type === 'keydown' && event.which !== 9) {\n return;\n } // Store reference to event timeStamp\n\n\n if (event.type === 'keydown') {\n this.lastKeyDown = event.timeStamp;\n } // Remove current classes\n\n\n const removeCurrent = () => {\n const className = player.config.classNames.tabFocus;\n const current = getElements.call(player, `.${className}`);\n toggleClass(current, className, false);\n }; // Determine if a key was pressed to trigger this event\n\n\n const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20; // Ignore focus events if a key was pressed prior\n\n if (event.type === 'focus' && !wasKeyDown) {\n return;\n } // Remove all current\n\n\n removeCurrent(); // Delay the adding of classname until the focus has changed\n // This event fires before the focusin event\n\n if (event.type !== 'focusout') {\n this.focusTimer = setTimeout(() => {\n const focused = document.activeElement; // Ignore if current focus element isn't inside the player\n\n if (!elements.container.contains(focused)) {\n return;\n }\n\n toggleClass(document.activeElement, player.config.classNames.tabFocus, true);\n }, 10);\n }\n });\n\n _defineProperty$1(this, \"global\", (toggle = true) => {\n const {\n player\n } = this; // Keyboard shortcuts\n\n if (player.config.keyboard.global) {\n toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false);\n } // Click anywhere closes menu\n\n\n toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle); // Detect touch by events\n\n once.call(player, document.body, 'touchstart', this.firstTouch); // Tab focus detection\n\n toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true);\n });\n\n _defineProperty$1(this, \"container\", () => {\n const {\n player\n } = this;\n const {\n config,\n elements,\n timers\n } = player; // Keyboard shortcuts\n\n if (!config.keyboard.global && config.keyboard.focused) {\n on.call(player, elements.container, 'keydown keyup', this.handleKey, false);\n } // Toggle controls on mouse events and entering fullscreen\n\n\n on.call(player, elements.container, 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen', event => {\n const {\n controls: controlsElement\n } = elements; // Remove button states for fullscreen\n\n if (controlsElement && event.type === 'enterfullscreen') {\n controlsElement.pressed = false;\n controlsElement.hover = false;\n } // Show, then hide after a timeout unless another control event occurs\n\n\n const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type);\n let delay = 0;\n\n if (show) {\n ui.toggleControls.call(player, true); // Use longer timeout for touch devices\n\n delay = player.touch ? 3000 : 2000;\n } // Clear timer\n\n\n clearTimeout(timers.controls); // Set new timer to prevent flicker when seeking\n\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n }); // Set a gutter for Vimeo\n\n const setGutter = () => {\n if (!player.isVimeo || player.config.vimeo.premium) {\n return;\n }\n\n const target = elements.wrapper;\n const {\n active\n } = player.fullscreen;\n const [videoWidth, videoHeight] = getAspectRatio.call(player);\n const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`); // If not active, remove styles\n\n if (!active) {\n if (useNativeAspectRatio) {\n target.style.width = null;\n target.style.height = null;\n } else {\n target.style.maxWidth = null;\n target.style.margin = null;\n }\n\n return;\n } // Determine which dimension will overflow and constrain view\n\n\n const [viewportWidth, viewportHeight] = getViewportSize();\n const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight;\n\n if (useNativeAspectRatio) {\n target.style.width = overflow ? 'auto' : '100%';\n target.style.height = overflow ? '100%' : 'auto';\n } else {\n target.style.maxWidth = overflow ? `${viewportHeight / videoHeight * videoWidth}px` : null;\n target.style.margin = overflow ? '0 auto' : null;\n }\n }; // Handle resizing\n\n\n const resized = () => {\n clearTimeout(timers.resized);\n timers.resized = setTimeout(setGutter, 50);\n };\n\n on.call(player, elements.container, 'enterfullscreen exitfullscreen', event => {\n const {\n target\n } = player.fullscreen; // Ignore events not from target\n\n if (target !== elements.container) {\n return;\n } // If it's not an embed and no ratio specified\n\n\n if (!player.isEmbed && is.empty(player.config.ratio)) {\n return;\n } // Set Vimeo gutter\n\n\n setGutter(); // Watch for resizes\n\n const method = event.type === 'enterfullscreen' ? on : off;\n method.call(player, window, 'resize', resized);\n });\n });\n\n _defineProperty$1(this, \"media\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player; // Time change on media\n\n on.call(player, player.media, 'timeupdate seeking seeked', event => controls.timeUpdate.call(player, event)); // Display duration\n\n on.call(player, player.media, 'durationchange loadeddata loadedmetadata', event => controls.durationUpdate.call(player, event)); // Handle the media finishing\n\n on.call(player, player.media, 'ended', () => {\n // Show poster on end\n if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) {\n // Restart\n player.restart(); // Call pause otherwise IE11 will start playing the video again\n\n player.pause();\n }\n }); // Check for buffer progress\n\n on.call(player, player.media, 'progress playing seeking seeked', event => controls.updateProgress.call(player, event)); // Handle volume changes\n\n on.call(player, player.media, 'volumechange', event => controls.updateVolume.call(player, event)); // Handle play/pause\n\n on.call(player, player.media, 'playing play pause ended emptied timeupdate', event => ui.checkPlaying.call(player, event)); // Loading state\n\n on.call(player, player.media, 'waiting canplay seeked playing', event => ui.checkLoading.call(player, event)); // Click video\n\n if (player.supported.ui && player.config.clickToPlay && !player.isAudio) {\n // Re-fetch the wrapper\n const wrapper = getElement.call(player, `.${player.config.classNames.video}`); // Bail if there's no wrapper (this should never happen)\n\n if (!is.element(wrapper)) {\n return;\n } // On click play, pause or restart\n\n\n on.call(player, elements.container, 'click', event => {\n const targets = [elements.container, wrapper]; // Ignore if click if not container or in video wrapper\n\n if (!targets.includes(event.target) && !wrapper.contains(event.target)) {\n return;\n } // Touch devices will just show controls (if hidden)\n\n\n if (player.touch && player.config.hideControls) {\n return;\n }\n\n if (player.ended) {\n this.proxy(event, player.restart, 'restart');\n this.proxy(event, () => {\n silencePromise(player.play());\n }, 'play');\n } else {\n this.proxy(event, () => {\n silencePromise(player.togglePlay());\n }, 'play');\n }\n });\n } // Disable right click\n\n\n if (player.supported.ui && player.config.disableContextMenu) {\n on.call(player, elements.wrapper, 'contextmenu', event => {\n event.preventDefault();\n }, false);\n } // Volume change\n\n\n on.call(player, player.media, 'volumechange', () => {\n // Save to storage\n player.storage.set({\n volume: player.volume,\n muted: player.muted\n });\n }); // Speed change\n\n on.call(player, player.media, 'ratechange', () => {\n // Update UI\n controls.updateSetting.call(player, 'speed'); // Save to storage\n\n player.storage.set({\n speed: player.speed\n });\n }); // Quality change\n\n on.call(player, player.media, 'qualitychange', event => {\n // Update UI\n controls.updateSetting.call(player, 'quality', null, event.detail.quality);\n }); // Update download link when ready and if quality changes\n\n on.call(player, player.media, 'ready qualitychange', () => {\n controls.setDownloadUrl.call(player);\n }); // Proxy events to container\n // Bubble up key events for Edge\n\n const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' ');\n on.call(player, player.media, proxyEvents, event => {\n let {\n detail = {}\n } = event; // Get error details from media\n\n if (event.type === 'error') {\n detail = player.media.error;\n }\n\n triggerEvent.call(player, elements.container, event.type, true, detail);\n });\n });\n\n _defineProperty$1(this, \"proxy\", (event, defaultHandler, customHandlerKey) => {\n const {\n player\n } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n let returned = true; // Execute custom handler\n\n if (hasCustomHandler) {\n returned = customHandler.call(player, event);\n } // Only call default handler if not prevented in custom handler\n\n\n if (returned !== false && is.function(defaultHandler)) {\n defaultHandler.call(player, event);\n }\n });\n\n _defineProperty$1(this, \"bind\", (element, type, defaultHandler, customHandlerKey, passive = true) => {\n const {\n player\n } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n on.call(player, element, type, event => this.proxy(event, defaultHandler, customHandlerKey), passive && !hasCustomHandler);\n });\n\n _defineProperty$1(this, \"controls\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player; // IE doesn't support input event, so we fallback to change\n\n const inputEvent = browser.isIE ? 'change' : 'input'; // Play/pause toggle\n\n if (elements.buttons.play) {\n Array.from(elements.buttons.play).forEach(button => {\n this.bind(button, 'click', () => {\n silencePromise(player.togglePlay());\n }, 'play');\n });\n } // Pause\n\n\n this.bind(elements.buttons.restart, 'click', player.restart, 'restart'); // Rewind\n\n this.bind(elements.buttons.rewind, 'click', () => {\n // Record seek time so we can prevent hiding controls for a few seconds after rewind\n player.lastSeekTime = Date.now();\n player.rewind();\n }, 'rewind'); // Rewind\n\n this.bind(elements.buttons.fastForward, 'click', () => {\n // Record seek time so we can prevent hiding controls for a few seconds after fast forward\n player.lastSeekTime = Date.now();\n player.forward();\n }, 'fastForward'); // Mute toggle\n\n this.bind(elements.buttons.mute, 'click', () => {\n player.muted = !player.muted;\n }, 'mute'); // Captions toggle\n\n this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions()); // Download\n\n this.bind(elements.buttons.download, 'click', () => {\n triggerEvent.call(player, player.media, 'download');\n }, 'download'); // Fullscreen toggle\n\n this.bind(elements.buttons.fullscreen, 'click', () => {\n player.fullscreen.toggle();\n }, 'fullscreen'); // Picture-in-Picture\n\n this.bind(elements.buttons.pip, 'click', () => {\n player.pip = 'toggle';\n }, 'pip'); // Airplay\n\n this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay'); // Settings menu - click toggle\n\n this.bind(elements.buttons.settings, 'click', event => {\n // Prevent the document click listener closing the menu\n event.stopPropagation();\n event.preventDefault();\n controls.toggleMenu.call(player, event);\n }, null, false); // Can't be passive as we're preventing default\n // Settings menu - keyboard toggle\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n\n this.bind(elements.buttons.settings, 'keyup', event => {\n const code = event.which; // We only care about space and return\n\n if (![13, 32].includes(code)) {\n return;\n } // Because return triggers a click anyway, all we need to do is set focus\n\n\n if (code === 13) {\n controls.focusFirstMenuItem.call(player, null, true);\n return;\n } // Prevent scroll\n\n\n event.preventDefault(); // Prevent playing video (Firefox)\n\n event.stopPropagation(); // Toggle menu\n\n controls.toggleMenu.call(player, event);\n }, null, false // Can't be passive as we're preventing default\n ); // Escape closes menu\n\n this.bind(elements.settings.menu, 'keydown', event => {\n if (event.which === 27) {\n controls.toggleMenu.call(player, event);\n }\n }); // Set range input alternative \"value\", which matches the tooltip time (#954)\n\n this.bind(elements.inputs.seek, 'mousedown mousemove', event => {\n const rect = elements.progress.getBoundingClientRect();\n const percent = 100 / rect.width * (event.pageX - rect.left);\n event.currentTarget.setAttribute('seek-value', percent);\n }); // Pause while seeking\n\n this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', event => {\n const seek = event.currentTarget;\n const code = event.keyCode ? event.keyCode : event.which;\n const attribute = 'play-on-seeked';\n\n if (is.keyboardEvent(event) && code !== 39 && code !== 37) {\n return;\n } // Record seek time so we can prevent hiding controls for a few seconds after seek\n\n\n player.lastSeekTime = Date.now(); // Was playing before?\n\n const play = seek.hasAttribute(attribute); // Done seeking\n\n const done = ['mouseup', 'touchend', 'keyup'].includes(event.type); // If we're done seeking and it was playing, resume playback\n\n if (play && done) {\n seek.removeAttribute(attribute);\n silencePromise(player.play());\n } else if (!done && player.playing) {\n seek.setAttribute(attribute, '');\n player.pause();\n }\n }); // Fix range inputs on iOS\n // Super weird iOS bug where after you interact with an <input type=\"range\">,\n // it takes over further interactions on the page. This is a hack\n\n if (browser.isIos) {\n const inputs = getElements.call(player, 'input[type=\"range\"]');\n Array.from(inputs).forEach(input => this.bind(input, inputEvent, event => repaint(event.target)));\n } // Seek\n\n\n this.bind(elements.inputs.seek, inputEvent, event => {\n const seek = event.currentTarget; // If it exists, use seek-value instead of \"value\" for consistency with tooltip time (#954)\n\n let seekTo = seek.getAttribute('seek-value');\n\n if (is.empty(seekTo)) {\n seekTo = seek.value;\n }\n\n seek.removeAttribute('seek-value');\n player.currentTime = seekTo / seek.max * player.duration;\n }, 'seek'); // Seek tooltip\n\n this.bind(elements.progress, 'mouseenter mouseleave mousemove', event => controls.updateSeekTooltip.call(player, event)); // Preview thumbnails plugin\n // TODO: Really need to work on some sort of plug-in wide event bus or pub-sub for this\n\n this.bind(elements.progress, 'mousemove touchmove', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startMove(event);\n }\n }); // Hide thumbnail preview - on mouse click, mouse leave, and video play/seek. All four are required, e.g., for buffering\n\n this.bind(elements.progress, 'mouseleave touchend click', () => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endMove(false, true);\n }\n }); // Show scrubbing preview\n\n this.bind(elements.progress, 'mousedown touchstart', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startScrubbing(event);\n }\n });\n this.bind(elements.progress, 'mouseup touchend', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endScrubbing(event);\n }\n }); // Polyfill for lower fill in <input type=\"range\"> for webkit\n\n if (browser.isWebkit) {\n Array.from(getElements.call(player, 'input[type=\"range\"]')).forEach(element => {\n this.bind(element, 'input', event => controls.updateRangeFill.call(player, event.target));\n });\n } // Current time invert\n // Only if one time element is used for both currentTime and duration\n\n\n if (player.config.toggleInvert && !is.element(elements.display.duration)) {\n this.bind(elements.display.currentTime, 'click', () => {\n // Do nothing if we're at the start\n if (player.currentTime === 0) {\n return;\n }\n\n player.config.invertTime = !player.config.invertTime;\n controls.timeUpdate.call(player);\n });\n } // Volume\n\n\n this.bind(elements.inputs.volume, inputEvent, event => {\n player.volume = event.target.value;\n }, 'volume'); // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting)\n\n this.bind(elements.controls, 'mouseenter mouseleave', event => {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }); // Also update controls.hover state for any non-player children of fullscreen element (as above)\n\n if (elements.fullscreen) {\n Array.from(elements.fullscreen.children).filter(c => !c.contains(elements.container)).forEach(child => {\n this.bind(child, 'mouseenter mouseleave', event => {\n if (elements.controls) {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }\n });\n });\n } // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting)\n\n\n this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', event => {\n elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type);\n }); // Show controls when they receive focus (e.g., when using keyboard tab key)\n\n this.bind(elements.controls, 'focusin', () => {\n const {\n config,\n timers\n } = player; // Skip transition to prevent focus from scrolling the parent element\n\n toggleClass(elements.controls, config.classNames.noTransition, true); // Toggle\n\n ui.toggleControls.call(player, true); // Restore transition\n\n setTimeout(() => {\n toggleClass(elements.controls, config.classNames.noTransition, false);\n }, 0); // Delay a little more for mouse users\n\n const delay = this.touch ? 3000 : 4000; // Clear timer\n\n clearTimeout(timers.controls); // Hide again after delay\n\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n }); // Mouse wheel for volume\n\n this.bind(elements.inputs.volume, 'wheel', event => {\n // Detect \"natural\" scroll - suppored on OS X Safari only\n // Other browsers on OS X will be inverted until support improves\n const inverted = event.webkitDirectionInvertedFromDevice; // Get delta from event. Invert if `inverted` is true\n\n const [x, y] = [event.deltaX, -event.deltaY].map(value => inverted ? -value : value); // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta)\n\n const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y); // Change the volume by 2%\n\n player.increaseVolume(direction / 50); // Don't break page scrolling at max and min\n\n const {\n volume\n } = player.media;\n\n if (direction === 1 && volume < 1 || direction === -1 && volume > 0) {\n event.preventDefault();\n }\n }, 'volume', false);\n });\n\n this.player = _player;\n this.lastKey = null;\n this.focusTimer = null;\n this.lastKeyDown = null;\n this.handleKey = this.handleKey.bind(this);\n this.toggleMenu = this.toggleMenu.bind(this);\n this.setTabFocus = this.setTabFocus.bind(this);\n this.firstTouch = this.firstTouch.bind(this);\n } // Handle key presses\n\n\n handleKey(event) {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n const code = event.keyCode ? event.keyCode : event.which;\n const pressed = event.type === 'keydown';\n const repeat = pressed && code === this.lastKey; // Bail if a modifier key is set\n\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {\n return;\n } // If the event is bubbled from the media element\n // Firefox doesn't get the keycode for whatever reason\n\n\n if (!is.number(code)) {\n return;\n } // Seek by the number keys\n\n\n const seekByKey = () => {\n // Divide the max duration into 10th's and times by the number value\n player.currentTime = player.duration / 10 * (code - 48);\n }; // Handle the key on keydown\n // Reset on keyup\n\n\n if (pressed) {\n // Check focused element\n // and if the focused element is not editable (e.g. text input)\n // and any that accept key input http://webaim.org/techniques/keyboard/\n const focused = document.activeElement;\n\n if (is.element(focused)) {\n const {\n editable\n } = player.config.selectors;\n const {\n seek\n } = elements.inputs;\n\n if (focused !== seek && matches(focused, editable)) {\n return;\n }\n\n if (event.which === 32 && matches(focused, 'button, [role^=\"menuitem\"]')) {\n return;\n }\n } // Which keycodes should we prevent default\n\n\n const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79]; // If the code is found prevent default (e.g. prevent scrolling for arrows)\n\n if (preventDefault.includes(code)) {\n event.preventDefault();\n event.stopPropagation();\n }\n\n switch (code) {\n case 48:\n case 49:\n case 50:\n case 51:\n case 52:\n case 53:\n case 54:\n case 55:\n case 56:\n case 57:\n // 0-9\n if (!repeat) {\n seekByKey();\n }\n\n break;\n\n case 32:\n case 75:\n // Space and K key\n if (!repeat) {\n silencePromise(player.togglePlay());\n }\n\n break;\n\n case 38:\n // Arrow up\n player.increaseVolume(0.1);\n break;\n\n case 40:\n // Arrow down\n player.decreaseVolume(0.1);\n break;\n\n case 77:\n // M key\n if (!repeat) {\n player.muted = !player.muted;\n }\n\n break;\n\n case 39:\n // Arrow forward\n player.forward();\n break;\n\n case 37:\n // Arrow back\n player.rewind();\n break;\n\n case 70:\n // F key\n player.fullscreen.toggle();\n break;\n\n case 67:\n // C key\n if (!repeat) {\n player.toggleCaptions();\n }\n\n break;\n\n case 76:\n // L key\n player.loop = !player.loop;\n break;\n } // Escape is handle natively when in full screen\n // So we only need to worry about non native\n\n\n if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) {\n player.fullscreen.toggle();\n } // Store last code for next cycle\n\n\n this.lastKey = code;\n } else {\n this.lastKey = null;\n }\n } // Toggle menu\n\n\n toggleMenu(event) {\n controls.toggleMenu.call(this.player, event);\n } // Device is touch enabled\n\n\n }\n\n var loadjs_umd = createCommonjsModule(function (module, exports) {\n (function (root, factory) {\n {\n module.exports = factory();\n }\n })(commonjsGlobal, function () {\n /**\n * Global dependencies.\n * @global {Object} document - DOM\n */\n var devnull = function () {},\n bundleIdCache = {},\n bundleResultCache = {},\n bundleCallbackQueue = {};\n /**\n * Subscribe to bundle load event.\n * @param {string[]} bundleIds - Bundle ids\n * @param {Function} callbackFn - The callback function\n */\n\n\n function subscribe(bundleIds, callbackFn) {\n // listify\n bundleIds = bundleIds.push ? bundleIds : [bundleIds];\n var depsNotFound = [],\n i = bundleIds.length,\n numWaiting = i,\n fn,\n bundleId,\n r,\n q; // define callback function\n\n fn = function (bundleId, pathsNotFound) {\n if (pathsNotFound.length) depsNotFound.push(bundleId);\n numWaiting--;\n if (!numWaiting) callbackFn(depsNotFound);\n }; // register callback\n\n\n while (i--) {\n bundleId = bundleIds[i]; // execute callback if in result cache\n\n r = bundleResultCache[bundleId];\n\n if (r) {\n fn(bundleId, r);\n continue;\n } // add to callback queue\n\n\n q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];\n q.push(fn);\n }\n }\n /**\n * Publish bundle load event.\n * @param {string} bundleId - Bundle id\n * @param {string[]} pathsNotFound - List of files not found\n */\n\n\n function publish(bundleId, pathsNotFound) {\n // exit if id isn't defined\n if (!bundleId) return;\n var q = bundleCallbackQueue[bundleId]; // cache result\n\n bundleResultCache[bundleId] = pathsNotFound; // exit if queue is empty\n\n if (!q) return; // empty callback queue\n\n while (q.length) {\n q[0](bundleId, pathsNotFound);\n q.splice(0, 1);\n }\n }\n /**\n * Execute callbacks.\n * @param {Object or Function} args - The callback args\n * @param {string[]} depsNotFound - List of dependencies not found\n */\n\n\n function executeCallbacks(args, depsNotFound) {\n // accept function as argument\n if (args.call) args = {\n success: args\n }; // success and error callbacks\n\n if (depsNotFound.length) (args.error || devnull)(depsNotFound);else (args.success || devnull)(args);\n }\n /**\n * Load individual file.\n * @param {string} path - The file path\n * @param {Function} callbackFn - The callback function\n */\n\n\n function loadFile(path, callbackFn, args, numTries) {\n var doc = document,\n async = args.async,\n maxTries = (args.numRetries || 0) + 1,\n beforeCallbackFn = args.before || devnull,\n pathname = path.replace(/[\\?|#].*$/, ''),\n pathStripped = path.replace(/^(css|img)!/, ''),\n isLegacyIECss,\n e;\n numTries = numTries || 0;\n\n if (/(^css!|\\.css$)/.test(pathname)) {\n // css\n e = doc.createElement('link');\n e.rel = 'stylesheet';\n e.href = pathStripped; // tag IE9+\n\n isLegacyIECss = 'hideFocus' in e; // use preload in IE Edge (to detect load errors)\n\n if (isLegacyIECss && e.relList) {\n isLegacyIECss = 0;\n e.rel = 'preload';\n e.as = 'style';\n }\n } else if (/(^img!|\\.(png|gif|jpg|svg|webp)$)/.test(pathname)) {\n // image\n e = doc.createElement('img');\n e.src = pathStripped;\n } else {\n // javascript\n e = doc.createElement('script');\n e.src = path;\n e.async = async === undefined ? true : async;\n }\n\n e.onload = e.onerror = e.onbeforeload = function (ev) {\n var result = ev.type[0]; // treat empty stylesheets as failures to get around lack of onerror\n // support in IE9-11\n\n if (isLegacyIECss) {\n try {\n if (!e.sheet.cssText.length) result = 'e';\n } catch (x) {\n // sheets objects created from load errors don't allow access to\n // `cssText` (unless error is Code:18 SecurityError)\n if (x.code != 18) result = 'e';\n }\n } // handle retries in case of load failure\n\n\n if (result == 'e') {\n // increment counter\n numTries += 1; // exit function and try again\n\n if (numTries < maxTries) {\n return loadFile(path, callbackFn, args, numTries);\n }\n } else if (e.rel == 'preload' && e.as == 'style') {\n // activate preloaded stylesheets\n return e.rel = 'stylesheet'; // jshint ignore:line\n } // execute callback\n\n\n callbackFn(path, result, ev.defaultPrevented);\n }; // add to document (unless callback returns `false`)\n\n\n if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);\n }\n /**\n * Load multiple files.\n * @param {string[]} paths - The file paths\n * @param {Function} callbackFn - The callback function\n */\n\n\n function loadFiles(paths, callbackFn, args) {\n // listify paths\n paths = paths.push ? paths : [paths];\n var numWaiting = paths.length,\n x = numWaiting,\n pathsNotFound = [],\n fn,\n i; // define callback function\n\n fn = function (path, result, defaultPrevented) {\n // handle error\n if (result == 'e') pathsNotFound.push(path); // handle beforeload event. If defaultPrevented then that means the load\n // will be blocked (ex. Ghostery/ABP on Safari)\n\n if (result == 'b') {\n if (defaultPrevented) pathsNotFound.push(path);else return;\n }\n\n numWaiting--;\n if (!numWaiting) callbackFn(pathsNotFound);\n }; // load scripts\n\n\n for (i = 0; i < x; i++) loadFile(paths[i], fn, args);\n }\n /**\n * Initiate script load and register bundle.\n * @param {(string|string[])} paths - The file paths\n * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success\n * callback or (3) object literal with success/error arguments, numRetries,\n * etc.\n * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object\n * literal with success/error arguments, numRetries, etc.\n */\n\n\n function loadjs(paths, arg1, arg2) {\n var bundleId, args; // bundleId (if string)\n\n if (arg1 && arg1.trim) bundleId = arg1; // args (default is {})\n\n args = (bundleId ? arg2 : arg1) || {}; // throw error if bundle is already defined\n\n if (bundleId) {\n if (bundleId in bundleIdCache) {\n throw \"LoadJS\";\n } else {\n bundleIdCache[bundleId] = true;\n }\n }\n\n function loadFn(resolve, reject) {\n loadFiles(paths, function (pathsNotFound) {\n // execute callbacks\n executeCallbacks(args, pathsNotFound); // resolve Promise\n\n if (resolve) {\n executeCallbacks({\n success: resolve,\n error: reject\n }, pathsNotFound);\n } // publish bundle load event\n\n\n publish(bundleId, pathsNotFound);\n }, args);\n }\n\n if (args.returnPromise) return new Promise(loadFn);else loadFn();\n }\n /**\n * Execute callbacks when dependencies have been satisfied.\n * @param {(string|string[])} deps - List of bundle ids\n * @param {Object} args - success/error arguments\n */\n\n\n loadjs.ready = function ready(deps, args) {\n // subscribe to bundle load event\n subscribe(deps, function (depsNotFound) {\n // execute callbacks\n executeCallbacks(args, depsNotFound);\n });\n return loadjs;\n };\n /**\n * Manually satisfy bundle dependencies.\n * @param {string} bundleId - The bundle id\n */\n\n\n loadjs.done = function done(bundleId) {\n publish(bundleId, []);\n };\n /**\n * Reset loadjs dependencies statuses\n */\n\n\n loadjs.reset = function reset() {\n bundleIdCache = {};\n bundleResultCache = {};\n bundleCallbackQueue = {};\n };\n /**\n * Determine if bundle has already been defined\n * @param String} bundleId - The bundle id\n */\n\n\n loadjs.isDefined = function isDefined(bundleId) {\n return bundleId in bundleIdCache;\n }; // export\n\n\n return loadjs;\n });\n });\n\n // ==========================================================================\n function loadScript(url) {\n return new Promise((resolve, reject) => {\n loadjs_umd(url, {\n success: resolve,\n error: reject\n });\n });\n }\n\n // ==========================================================================\n\n function parseId$1(url) {\n if (is.empty(url)) {\n return null;\n }\n\n if (is.number(Number(url))) {\n return url;\n }\n\n const regex = /^.*(vimeo.com\\/|video\\/)(\\d+).*/;\n return url.match(regex) ? RegExp.$2 : url;\n } // Try to extract a hash for private videos from the URL\n\n\n function parseHash(url) {\n /* This regex matches a hexadecimal hash if given in any of these forms:\n * - [https://player.]vimeo.com/video/{id}/{hash}[?params]\n * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms]\n * - [https://player.]vimeo.com/video/{id}?[params]&h={hash}\n * - video/{id}/{hash}\n * If matched, the hash is available in the named group `hash`\n */\n const regex = /^.*(?:vimeo.com\\/|video\\/)(?:\\d+)(?:\\?.*&*h=|\\/)+(?<hash>[\\d,a-f]+)/;\n const found = url.match(regex);\n return found ? found.groups.hash : null;\n } // Set playback state and trigger change (only on actual change)\n\n\n function assurePlaybackState$1(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n }\n\n const vimeo = {\n setup() {\n const player = this; // Add embed class for responsive\n\n toggleClass(player.elements.wrapper, player.config.classNames.embed, true); // Set speed options from config\n\n player.options.speed = player.config.speed.options; // Set intial ratio\n\n setAspectRatio.call(player); // Load the SDK if not already\n\n if (!is.object(window.Vimeo)) {\n loadScript(player.config.urls.vimeo.sdk).then(() => {\n vimeo.ready.call(player);\n }).catch(error => {\n player.debug.warn('Vimeo SDK (player.js) failed to load', error);\n });\n } else {\n vimeo.ready.call(player);\n }\n },\n\n // API Ready\n ready() {\n const player = this;\n const config = player.config.vimeo;\n const {\n premium,\n referrerPolicy,\n ...frameParams\n } = config; // Get the source URL or ID\n\n let source = player.media.getAttribute('src');\n let hash = ''; // Get from <div> if needed\n\n if (is.empty(source)) {\n source = player.media.getAttribute(player.config.attributes.embed.id); // hash can also be set as attribute on the <div>\n\n hash = player.media.getAttribute(player.config.attributes.embed.hash);\n } else {\n hash = parseHash(source);\n }\n\n const hashParam = hash ? {\n h: hash\n } : {}; // If the owner has a pro or premium account then we can hide controls etc\n\n if (premium) {\n Object.assign(frameParams, {\n controls: false,\n sidedock: false\n });\n } // Get Vimeo params for the iframe\n\n\n const params = buildUrlParams({\n loop: player.config.loop.active,\n autoplay: player.autoplay,\n muted: player.muted,\n gesture: 'media',\n playsinline: !this.config.fullscreen.iosNative,\n // hash has to be added to iframe-URL\n ...hashParam,\n ...frameParams\n });\n const id = parseId$1(source); // Build an iframe\n\n const iframe = createElement('iframe');\n const src = format(player.config.urls.vimeo.iframe, id, params);\n iframe.setAttribute('src', src);\n iframe.setAttribute('allowfullscreen', '');\n iframe.setAttribute('allow', ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; ')); // Set the referrer policy if required\n\n if (!is.empty(referrerPolicy)) {\n iframe.setAttribute('referrerPolicy', referrerPolicy);\n } // Inject the package\n\n\n if (premium || !config.customControls) {\n iframe.setAttribute('data-poster', player.poster);\n player.media = replaceElement(iframe, player.media);\n } else {\n const wrapper = createElement('div', {\n class: player.config.classNames.embedContainer,\n 'data-poster': player.poster\n });\n wrapper.appendChild(iframe);\n player.media = replaceElement(wrapper, player.media);\n } // Get poster image\n\n\n if (!config.customControls) {\n fetch(format(player.config.urls.vimeo.api, src)).then(response => {\n if (is.empty(response) || !response.thumbnail_url) {\n return;\n } // Set and show poster\n\n\n ui.setPoster.call(player, response.thumbnail_url).catch(() => {});\n });\n } // Setup instance\n // https://github.com/vimeo/player.js\n\n\n player.embed = new window.Vimeo.Player(iframe, {\n autopause: player.config.autopause,\n muted: player.muted\n });\n player.media.paused = true;\n player.media.currentTime = 0; // Disable native text track rendering\n\n if (player.supported.ui) {\n player.embed.disableTextTrack();\n } // Create a faux HTML5 API using the Vimeo API\n\n\n player.media.play = () => {\n assurePlaybackState$1.call(player, true);\n return player.embed.play();\n };\n\n player.media.pause = () => {\n assurePlaybackState$1.call(player, false);\n return player.embed.pause();\n };\n\n player.media.stop = () => {\n player.pause();\n player.currentTime = 0;\n }; // Seeking\n\n\n let {\n currentTime\n } = player.media;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return currentTime;\n },\n\n set(time) {\n // Vimeo will automatically play on seek if the video hasn't been played before\n // Get current paused state and volume etc\n const {\n embed,\n media,\n paused,\n volume\n } = player;\n const restorePause = paused && !embed.hasPlayed; // Set seeking state and trigger event\n\n media.seeking = true;\n triggerEvent.call(player, media, 'seeking'); // If paused, mute until seek is complete\n\n Promise.resolve(restorePause && embed.setVolume(0)) // Seek\n .then(() => embed.setCurrentTime(time)) // Restore paused\n .then(() => restorePause && embed.pause()) // Restore volume\n .then(() => restorePause && embed.setVolume(volume)).catch(() => {// Do nothing\n });\n }\n\n }); // Playback speed\n\n let speed = player.config.speed.selected;\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return speed;\n },\n\n set(input) {\n player.embed.setPlaybackRate(input).then(() => {\n speed = input;\n triggerEvent.call(player, player.media, 'ratechange');\n }).catch(() => {\n // Cannot set Playback Rate, Video is probably not on Pro account\n player.options.speed = [1];\n });\n }\n\n }); // Volume\n\n let {\n volume\n } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n\n set(input) {\n player.embed.setVolume(input).then(() => {\n volume = input;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n }\n\n }); // Muted\n\n let {\n muted\n } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : false;\n player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => {\n muted = toggle;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n }\n\n }); // Loop\n\n let {\n loop\n } = player.config;\n Object.defineProperty(player.media, 'loop', {\n get() {\n return loop;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : player.config.loop.active;\n player.embed.setLoop(toggle).then(() => {\n loop = toggle;\n });\n }\n\n }); // Source\n\n let currentSrc;\n player.embed.getVideoUrl().then(value => {\n currentSrc = value;\n controls.setDownloadUrl.call(player);\n }).catch(error => {\n this.debug.warn(error);\n });\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return currentSrc;\n }\n\n }); // Ended\n\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n }\n\n }); // Set aspect ratio based on video size\n\n Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(dimensions => {\n const [width, height] = dimensions;\n player.embed.ratio = roundAspectRatio(width, height);\n setAspectRatio.call(this);\n }); // Set autopause\n\n player.embed.setAutopause(player.config.autopause).then(state => {\n player.config.autopause = state;\n }); // Get title\n\n player.embed.getVideoTitle().then(title => {\n player.config.title = title;\n ui.setTitle.call(this);\n }); // Get current time\n\n player.embed.getCurrentTime().then(value => {\n currentTime = value;\n triggerEvent.call(player, player.media, 'timeupdate');\n }); // Get duration\n\n player.embed.getDuration().then(value => {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }); // Get captions\n\n player.embed.getTextTracks().then(tracks => {\n player.media.textTracks = tracks;\n captions.setup.call(player);\n });\n player.embed.on('cuechange', ({\n cues = []\n }) => {\n const strippedCues = cues.map(cue => stripHTML(cue.text));\n captions.updateCues.call(player, strippedCues);\n });\n player.embed.on('loaded', () => {\n // Assure state and events are updated on autoplay\n player.embed.getPaused().then(paused => {\n assurePlaybackState$1.call(player, !paused);\n\n if (!paused) {\n triggerEvent.call(player, player.media, 'playing');\n }\n });\n\n if (is.element(player.embed.element) && player.supported.ui) {\n const frame = player.embed.element; // Fix keyboard focus issues\n // https://github.com/sampotts/plyr/issues/317\n\n frame.setAttribute('tabindex', -1);\n }\n });\n player.embed.on('bufferstart', () => {\n triggerEvent.call(player, player.media, 'waiting');\n });\n player.embed.on('bufferend', () => {\n triggerEvent.call(player, player.media, 'playing');\n });\n player.embed.on('play', () => {\n assurePlaybackState$1.call(player, true);\n triggerEvent.call(player, player.media, 'playing');\n });\n player.embed.on('pause', () => {\n assurePlaybackState$1.call(player, false);\n });\n player.embed.on('timeupdate', data => {\n player.media.seeking = false;\n currentTime = data.seconds;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n player.embed.on('progress', data => {\n player.media.buffered = data.percent;\n triggerEvent.call(player, player.media, 'progress'); // Check all loaded\n\n if (parseInt(data.percent, 10) === 1) {\n triggerEvent.call(player, player.media, 'canplaythrough');\n } // Get duration as if we do it before load, it gives an incorrect value\n // https://github.com/sampotts/plyr/issues/891\n\n\n player.embed.getDuration().then(value => {\n if (value !== player.media.duration) {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }\n });\n });\n player.embed.on('seeked', () => {\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n });\n player.embed.on('ended', () => {\n player.media.paused = true;\n triggerEvent.call(player, player.media, 'ended');\n });\n player.embed.on('error', detail => {\n player.media.error = detail;\n triggerEvent.call(player, player.media, 'error');\n }); // Rebuild UI\n\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 0);\n }\n }\n\n };\n\n // ==========================================================================\n\n function parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n const regex = /^.*(youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=|&v=)([^#&?]*).*/;\n return url.match(regex) ? RegExp.$2 : url;\n } // Set playback state and trigger change (only on actual change)\n\n\n function assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n }\n\n function getHost(config) {\n if (config.noCookie) {\n return 'https://www.youtube-nocookie.com';\n }\n\n if (window.location.protocol === 'http:') {\n return 'http://www.youtube.com';\n } // Use YouTube's default\n\n\n return undefined;\n }\n\n const youtube = {\n setup() {\n // Add embed class for responsive\n toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Setup API\n\n if (is.object(window.YT) && is.function(window.YT.Player)) {\n youtube.ready.call(this);\n } else {\n // Reference current global callback\n const callback = window.onYouTubeIframeAPIReady; // Set callback to process queue\n\n window.onYouTubeIframeAPIReady = () => {\n // Call global callback if set\n if (is.function(callback)) {\n callback();\n }\n\n youtube.ready.call(this);\n }; // Load the SDK\n\n\n loadScript(this.config.urls.youtube.sdk).catch(error => {\n this.debug.warn('YouTube API failed to load', error);\n });\n }\n },\n\n // Get the media title\n getTitle(videoId) {\n const url = format(this.config.urls.youtube.api, videoId);\n fetch(url).then(data => {\n if (is.object(data)) {\n const {\n title,\n height,\n width\n } = data; // Set title\n\n this.config.title = title;\n ui.setTitle.call(this); // Set aspect ratio\n\n this.embed.ratio = roundAspectRatio(width, height);\n }\n\n setAspectRatio.call(this);\n }).catch(() => {\n // Set aspect ratio\n setAspectRatio.call(this);\n });\n },\n\n // API ready\n ready() {\n const player = this;\n const config = player.config.youtube; // Ignore already setup (race condition)\n\n const currentId = player.media && player.media.getAttribute('id');\n\n if (!is.empty(currentId) && currentId.startsWith('youtube-')) {\n return;\n } // Get the source URL or ID\n\n\n let source = player.media.getAttribute('src'); // Get from <div> if needed\n\n if (is.empty(source)) {\n source = player.media.getAttribute(this.config.attributes.embed.id);\n } // Replace the <iframe> with a <div> due to YouTube API issues\n\n\n const videoId = parseId(source);\n const id = generateId(player.provider); // Replace media element\n\n const container = createElement('div', {\n id,\n 'data-poster': config.customControls ? player.poster : undefined\n });\n player.media = replaceElement(container, player.media); // Only load the poster when using custom controls\n\n if (config.customControls) {\n const posterSrc = s => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`; // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide)\n\n\n loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded\n .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3\n .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists\n .then(image => ui.setPoster.call(player, image.src)).then(src => {\n // If the image is padded, use background-size \"cover\" instead (like youtube does too with their posters)\n if (!src.includes('maxres')) {\n player.elements.poster.style.backgroundSize = 'cover';\n }\n }).catch(() => {});\n } // Setup instance\n // https://developers.google.com/youtube/iframe_api_reference\n\n\n player.embed = new window.YT.Player(player.media, {\n videoId,\n host: getHost(config),\n playerVars: extend({}, {\n // Autoplay\n autoplay: player.config.autoplay ? 1 : 0,\n // iframe interface language\n hl: player.config.hl,\n // Only show controls if not fully supported or opted out\n controls: player.supported.ui && config.customControls ? 0 : 1,\n // Disable keyboard as we handle it\n disablekb: 1,\n // Allow iOS inline playback\n playsinline: !player.config.fullscreen.iosNative ? 1 : 0,\n // Captions are flaky on YouTube\n cc_load_policy: player.captions.active ? 1 : 0,\n cc_lang_pref: player.config.captions.language,\n // Tracking for stats\n widget_referrer: window ? window.location.href : null\n }, config),\n events: {\n onError(event) {\n // YouTube may fire onError twice, so only handle it once\n if (!player.media.error) {\n const code = event.data; // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError\n\n const message = {\n 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.',\n 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.',\n 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.',\n 101: 'The owner of the requested video does not allow it to be played in embedded players.',\n 150: 'The owner of the requested video does not allow it to be played in embedded players.'\n }[code] || 'An unknown error occured';\n player.media.error = {\n code,\n message\n };\n triggerEvent.call(player, player.media, 'error');\n }\n },\n\n onPlaybackRateChange(event) {\n // Get the instance\n const instance = event.target; // Get current speed\n\n player.media.playbackRate = instance.getPlaybackRate();\n triggerEvent.call(player, player.media, 'ratechange');\n },\n\n onReady(event) {\n // Bail if onReady has already been called. See issue #1108\n if (is.function(player.media.play)) {\n return;\n } // Get the instance\n\n\n const instance = event.target; // Get the title\n\n youtube.getTitle.call(player, videoId); // Create a faux HTML5 API using the YouTube API\n\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n instance.playVideo();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n instance.pauseVideo();\n };\n\n player.media.stop = () => {\n instance.stopVideo();\n };\n\n player.media.duration = instance.getDuration();\n player.media.paused = true; // Seeking\n\n player.media.currentTime = 0;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return Number(instance.getCurrentTime());\n },\n\n set(time) {\n // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet).\n if (player.paused && !player.embed.hasPlayed) {\n player.embed.mute();\n } // Set seeking state and trigger event\n\n\n player.media.seeking = true;\n triggerEvent.call(player, player.media, 'seeking'); // Seek after events sent\n\n instance.seekTo(time);\n }\n\n }); // Playback speed\n\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return instance.getPlaybackRate();\n },\n\n set(input) {\n instance.setPlaybackRate(input);\n }\n\n }); // Volume\n\n let {\n volume\n } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n\n set(input) {\n volume = input;\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n }\n\n }); // Muted\n\n let {\n muted\n } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : muted;\n muted = toggle;\n instance[toggle ? 'mute' : 'unMute']();\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n }\n\n }); // Source\n\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return instance.getVideoUrl();\n }\n\n }); // Ended\n\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n }\n\n }); // Get available speeds\n\n const speeds = instance.getAvailablePlaybackRates(); // Filter based on config\n\n player.options.speed = speeds.filter(s => player.config.speed.options.includes(s)); // Set the tabindex to avoid focus entering iframe\n\n if (player.supported.ui && config.customControls) {\n player.media.setAttribute('tabindex', -1);\n }\n\n triggerEvent.call(player, player.media, 'timeupdate');\n triggerEvent.call(player, player.media, 'durationchange'); // Reset timer\n\n clearInterval(player.timers.buffering); // Setup buffering\n\n player.timers.buffering = setInterval(() => {\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction(); // Trigger progress only when we actually buffer something\n\n if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) {\n triggerEvent.call(player, player.media, 'progress');\n } // Set last buffer point\n\n\n player.media.lastBuffered = player.media.buffered; // Bail if we're at 100%\n\n if (player.media.buffered === 1) {\n clearInterval(player.timers.buffering); // Trigger event\n\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n }, 200); // Rebuild UI\n\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 50);\n }\n },\n\n onStateChange(event) {\n // Get the instance\n const instance = event.target; // Reset timer\n\n clearInterval(player.timers.playing);\n const seeked = player.media.seeking && [1, 2].includes(event.data);\n\n if (seeked) {\n // Unset seeking and fire seeked event\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n } // Handle events\n // -1 Unstarted\n // 0 Ended\n // 1 Playing\n // 2 Paused\n // 3 Buffering\n // 5 Video cued\n\n\n switch (event.data) {\n case -1:\n // Update scrubber\n triggerEvent.call(player, player.media, 'timeupdate'); // Get loaded % from YouTube\n\n player.media.buffered = instance.getVideoLoadedFraction();\n triggerEvent.call(player, player.media, 'progress');\n break;\n\n case 0:\n assurePlaybackState.call(player, false); // YouTube doesn't support loop for a single video, so mimick it.\n\n if (player.media.loop) {\n // YouTube needs a call to `stopVideo` before playing again\n instance.stopVideo();\n instance.playVideo();\n } else {\n triggerEvent.call(player, player.media, 'ended');\n }\n\n break;\n\n case 1:\n // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet)\n if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) {\n player.media.pause();\n } else {\n assurePlaybackState.call(player, true);\n triggerEvent.call(player, player.media, 'playing'); // Poll to get playback progress\n\n player.timers.playing = setInterval(() => {\n triggerEvent.call(player, player.media, 'timeupdate');\n }, 50); // Check duration again due to YouTube bug\n // https://github.com/sampotts/plyr/issues/374\n // https://code.google.com/p/gdata-issues/issues/detail?id=8690\n\n if (player.media.duration !== instance.getDuration()) {\n player.media.duration = instance.getDuration();\n triggerEvent.call(player, player.media, 'durationchange');\n }\n }\n\n break;\n\n case 2:\n // Restore audio (YouTube starts playing on seek if the video hasn't been played yet)\n if (!player.muted) {\n player.embed.unMute();\n }\n\n assurePlaybackState.call(player, false);\n break;\n\n case 3:\n // Trigger waiting event to add loading classes to container as the video buffers.\n triggerEvent.call(player, player.media, 'waiting');\n break;\n }\n\n triggerEvent.call(player, player.elements.container, 'statechange', false, {\n code: event.data\n });\n }\n\n }\n });\n }\n\n };\n\n // ==========================================================================\n const media = {\n // Setup media\n setup() {\n // If there's no media, bail\n if (!this.media) {\n this.debug.warn('No media element found!');\n return;\n } // Add type class\n\n\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true); // Add provider class\n\n toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true); // Add video class for embeds\n // This will require changes if audio embeds are added\n\n if (this.isEmbed) {\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true);\n } // Inject the player wrapper\n\n\n if (this.isVideo) {\n // Create the wrapper div\n this.elements.wrapper = createElement('div', {\n class: this.config.classNames.video\n }); // Wrap the video in a container\n\n wrap(this.media, this.elements.wrapper); // Poster image container\n\n this.elements.poster = createElement('div', {\n class: this.config.classNames.poster\n });\n this.elements.wrapper.appendChild(this.elements.poster);\n }\n\n if (this.isHTML5) {\n html5.setup.call(this);\n } else if (this.isYouTube) {\n youtube.setup.call(this);\n } else if (this.isVimeo) {\n vimeo.setup.call(this);\n }\n }\n\n };\n\n const destroy = instance => {\n // Destroy our adsManager\n if (instance.manager) {\n instance.manager.destroy();\n } // Destroy our adsManager\n\n\n if (instance.elements.displayContainer) {\n instance.elements.displayContainer.destroy();\n }\n\n instance.elements.container.remove();\n };\n\n class Ads {\n /**\n * Ads constructor.\n * @param {Object} player\n * @return {Ads}\n */\n constructor(player) {\n _defineProperty$1(this, \"load\", () => {\n if (!this.enabled) {\n return;\n } // Check if the Google IMA3 SDK is loaded or load it ourselves\n\n\n if (!is.object(window.google) || !is.object(window.google.ima)) {\n loadScript(this.player.config.urls.googleIMA.sdk).then(() => {\n this.ready();\n }).catch(() => {\n // Script failed to load or is blocked\n this.trigger('error', new Error('Google IMA SDK failed to load'));\n });\n } else {\n this.ready();\n }\n });\n\n _defineProperty$1(this, \"ready\", () => {\n // Double check we're enabled\n if (!this.enabled) {\n destroy(this);\n } // Start ticking our safety timer. If the whole advertisement\n // thing doesn't resolve within our set time; we bail\n\n\n this.startSafetyTimer(12000, 'ready()'); // Clear the safety timer\n\n this.managerPromise.then(() => {\n this.clearSafetyTimer('onAdsManagerLoaded()');\n }); // Set listeners on the Plyr instance\n\n this.listeners(); // Setup the IMA SDK\n\n this.setupIMA();\n });\n\n _defineProperty$1(this, \"setupIMA\", () => {\n // Create the container for our advertisements\n this.elements.container = createElement('div', {\n class: this.player.config.classNames.ads\n });\n this.player.elements.container.appendChild(this.elements.container); // So we can run VPAID2\n\n google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED); // Set language\n\n google.ima.settings.setLocale(this.player.config.ads.language); // Set playback for iOS10+\n\n 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\n\n this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container, this.player.media); // Create ads loader\n\n this.loader = new google.ima.AdsLoader(this.elements.displayContainer); // Listen and respond to ads loaded and error events\n\n this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false);\n this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false); // Request video ads to be pre-loaded\n\n this.requestAds();\n });\n\n _defineProperty$1(this, \"requestAds\", () => {\n const {\n container\n } = this.player.elements;\n\n try {\n // Request video ads\n const request = new google.ima.AdsRequest();\n request.adTagUrl = this.tagUrl; // Specify the linear and nonlinear slot sizes. This helps the SDK\n // to select the correct creative if multiple are returned\n\n request.linearAdSlotWidth = container.offsetWidth;\n request.linearAdSlotHeight = container.offsetHeight;\n request.nonLinearAdSlotWidth = container.offsetWidth;\n request.nonLinearAdSlotHeight = container.offsetHeight; // We only overlay ads as we only support video.\n\n request.forceNonLinearFullSlot = false; // Mute based on current state\n\n request.setAdWillPlayMuted(!this.player.muted);\n this.loader.requestAds(request);\n } catch (error) {\n this.onAdError(error);\n }\n });\n\n _defineProperty$1(this, \"pollCountdown\", (start = false) => {\n if (!start) {\n clearInterval(this.countdownTimer);\n this.elements.container.removeAttribute('data-badge-text');\n return;\n }\n\n const update = () => {\n const time = formatTime(Math.max(this.manager.getRemainingTime(), 0));\n const label = `${i18n.get('advertisement', this.player.config)} - ${time}`;\n this.elements.container.setAttribute('data-badge-text', label);\n };\n\n this.countdownTimer = setInterval(update, 100);\n });\n\n _defineProperty$1(this, \"onAdsManagerLoaded\", event => {\n // Load could occur after a source change (race condition)\n if (!this.enabled) {\n return;\n } // Get the ads manager\n\n\n const settings = new google.ima.AdsRenderingSettings(); // Tell the SDK to save and restore content video state on our behalf\n\n settings.restoreCustomPlaybackStateOnAdBreakComplete = true;\n settings.enablePreloading = true; // The SDK is polling currentTime on the contentPlayback. And needs a duration\n // so it can determine when to start the mid- and post-roll\n\n this.manager = event.getAdsManager(this.player, settings); // Get the cue points for any mid-rolls by filtering out the pre- and post-roll\n\n this.cuePoints = this.manager.getCuePoints(); // Add listeners to the required events\n // Advertisement error events\n\n this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error)); // Advertisement regular events\n\n Object.keys(google.ima.AdEvent.Type).forEach(type => {\n this.manager.addEventListener(google.ima.AdEvent.Type[type], e => this.onAdEvent(e));\n }); // Resolve our adsManager\n\n this.trigger('loaded');\n });\n\n _defineProperty$1(this, \"addCuePoints\", () => {\n // Add advertisement cue's within the time line if available\n if (!is.empty(this.cuePoints)) {\n this.cuePoints.forEach(cuePoint => {\n if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {\n const seekElement = this.player.elements.progress;\n\n if (is.element(seekElement)) {\n const cuePercentage = 100 / this.player.duration * cuePoint;\n const cue = createElement('span', {\n class: this.player.config.classNames.cues\n });\n cue.style.left = `${cuePercentage.toString()}%`;\n seekElement.appendChild(cue);\n }\n }\n });\n }\n });\n\n _defineProperty$1(this, \"onAdEvent\", event => {\n const {\n container\n } = this.player.elements; // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)\n // don't have ad object associated\n\n const ad = event.getAd();\n const adData = event.getAdData(); // Proxy event\n\n const dispatchEvent = type => {\n triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`);\n }; // Bubble the event\n\n\n dispatchEvent(event.type);\n\n switch (event.type) {\n case google.ima.AdEvent.Type.LOADED:\n // This is the first event sent for an ad - it is possible to determine whether the\n // ad is a video ad or an overlay\n this.trigger('loaded'); // Start countdown\n\n this.pollCountdown(true);\n\n if (!ad.isLinear()) {\n // Position AdDisplayContainer correctly for overlay\n ad.width = container.offsetWidth;\n ad.height = container.offsetHeight;\n } // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex());\n // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset());\n\n\n break;\n\n case google.ima.AdEvent.Type.STARTED:\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n break;\n\n case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:\n // All ads for the current videos are done. We can now request new advertisements\n // in case the video is re-played\n // TODO: Example for what happens when a next video in a playlist would be loaded.\n // So here we load a new video when all ads are done.\n // Then we load new ads within a new adsManager. When the video\n // Is started - after - the ads are loaded, then we get ads.\n // You can also easily test cancelling and reloading by running\n // player.ads.cancel() and player.ads.play from the console I guess.\n // this.player.source = {\n // type: 'video',\n // title: 'View From A Blue Moon',\n // sources: [{\n // src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type:\n // 'video/mp4', }], poster:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks:\n // [ { kind: 'captions', label: 'English', srclang: 'en', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',\n // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ],\n // };\n // TODO: So there is still this thing where a video should only be allowed to start\n // playing when the IMA SDK is ready or has failed\n if (this.player.ended) {\n this.loadAds();\n } else {\n // The SDK won't allow new ads to be called without receiving a contentComplete()\n this.loader.contentComplete();\n }\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:\n // This event indicates the ad has started - the video player can adjust the UI,\n // for example display a pause button and remaining time. Fired when content should\n // be paused. This usually happens right before an ad is about to cover the content\n this.pauseContent();\n break;\n\n case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:\n // This event indicates the ad has finished - the video player can perform\n // appropriate UI actions, such as removing the timer for remaining time detection.\n // Fired when content should be resumed. This usually happens when an ad finishes\n // or collapses\n this.pollCountdown();\n this.resumeContent();\n break;\n\n case google.ima.AdEvent.Type.LOG:\n if (adData.adError) {\n this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);\n }\n\n break;\n }\n });\n\n _defineProperty$1(this, \"onAdError\", event => {\n this.cancel();\n this.player.debug.warn('Ads error', event);\n });\n\n _defineProperty$1(this, \"listeners\", () => {\n const {\n container\n } = this.player.elements;\n let time;\n this.player.on('canplay', () => {\n this.addCuePoints();\n });\n this.player.on('ended', () => {\n this.loader.contentComplete();\n });\n this.player.on('timeupdate', () => {\n time = this.player.currentTime;\n });\n this.player.on('seeked', () => {\n const seekedTime = this.player.currentTime;\n\n if (is.empty(this.cuePoints)) {\n return;\n }\n\n this.cuePoints.forEach((cuePoint, index) => {\n if (time < cuePoint && cuePoint < seekedTime) {\n this.manager.discardAdBreak();\n this.cuePoints.splice(index, 1);\n }\n });\n }); // Listen to the resizing of the window. And resize ad accordingly\n // TODO: eventually implement ResizeObserver\n\n window.addEventListener('resize', () => {\n if (this.manager) {\n this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n }\n });\n });\n\n _defineProperty$1(this, \"play\", () => {\n const {\n container\n } = this.player.elements;\n\n if (!this.managerPromise) {\n this.resumeContent();\n } // Play the requested advertisement whenever the adsManager is ready\n\n\n this.managerPromise.then(() => {\n // Set volume to match player\n this.manager.setVolume(this.player.volume); // Initialize the container. Must be done via a user action on mobile devices\n\n this.elements.displayContainer.initialize();\n\n try {\n if (!this.initialized) {\n // Initialize the ads manager. Ad rules playlist will start at this time\n this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will\n // start at this time; the call will be ignored for ad rules\n\n this.manager.start();\n }\n\n this.initialized = true;\n } catch (adError) {\n // An error may be thrown if there was a problem with the\n // VAST response\n this.onAdError(adError);\n }\n }).catch(() => {});\n });\n\n _defineProperty$1(this, \"resumeContent\", () => {\n // Hide the advertisement container\n this.elements.container.style.zIndex = ''; // Ad is stopped\n\n this.playing = false; // Play video\n\n silencePromise(this.player.media.play());\n });\n\n _defineProperty$1(this, \"pauseContent\", () => {\n // Show the advertisement container\n this.elements.container.style.zIndex = 3; // Ad is playing\n\n this.playing = true; // Pause our video.\n\n this.player.media.pause();\n });\n\n _defineProperty$1(this, \"cancel\", () => {\n // Pause our video\n if (this.initialized) {\n this.resumeContent();\n } // Tell our instance that we're done for now\n\n\n this.trigger('error'); // Re-create our adsManager\n\n this.loadAds();\n });\n\n _defineProperty$1(this, \"loadAds\", () => {\n // Tell our adsManager to go bye bye\n this.managerPromise.then(() => {\n // Destroy our adsManager\n if (this.manager) {\n this.manager.destroy();\n } // Re-set our adsManager promises\n\n\n this.managerPromise = new Promise(resolve => {\n this.on('loaded', resolve);\n this.player.debug.log(this.manager);\n }); // Now that the manager has been destroyed set it to also be un-initialized\n\n this.initialized = false; // Now request some new advertisements\n\n this.requestAds();\n }).catch(() => {});\n });\n\n _defineProperty$1(this, \"trigger\", (event, ...args) => {\n const handlers = this.events[event];\n\n if (is.array(handlers)) {\n handlers.forEach(handler => {\n if (is.function(handler)) {\n handler.apply(this, args);\n }\n });\n }\n });\n\n _defineProperty$1(this, \"on\", (event, callback) => {\n if (!is.array(this.events[event])) {\n this.events[event] = [];\n }\n\n this.events[event].push(callback);\n return this;\n });\n\n _defineProperty$1(this, \"startSafetyTimer\", (time, from) => {\n this.player.debug.log(`Safety timer invoked from: ${from}`);\n this.safetyTimer = setTimeout(() => {\n this.cancel();\n this.clearSafetyTimer('startSafetyTimer()');\n }, time);\n });\n\n _defineProperty$1(this, \"clearSafetyTimer\", from => {\n if (!is.nullOrUndefined(this.safetyTimer)) {\n this.player.debug.log(`Safety timer cleared from: ${from}`);\n clearTimeout(this.safetyTimer);\n this.safetyTimer = null;\n }\n });\n\n this.player = player;\n this.config = player.config.ads;\n this.playing = false;\n this.initialized = false;\n this.elements = {\n container: null,\n displayContainer: null\n };\n this.manager = null;\n this.loader = null;\n this.cuePoints = null;\n this.events = {};\n this.safetyTimer = null;\n this.countdownTimer = null; // Setup a promise to resolve when the IMA manager is ready\n\n this.managerPromise = new Promise((resolve, reject) => {\n // The ad is loaded and ready\n this.on('loaded', resolve); // Ads failed\n\n this.on('error', reject);\n });\n this.load();\n }\n\n get enabled() {\n const {\n config\n } = this;\n return this.player.isHTML5 && this.player.isVideo && config.enabled && (!is.empty(config.publisherId) || is.url(config.tagUrl));\n }\n /**\n * Load the IMA SDK\n */\n\n\n // Build the tag URL\n get tagUrl() {\n const {\n config\n } = this;\n\n if (is.url(config.tagUrl)) {\n return config.tagUrl;\n }\n\n const params = {\n AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',\n AV_CHANNELID: '5a0458dc28a06145e4519d21',\n AV_URL: window.location.hostname,\n cb: Date.now(),\n AV_WIDTH: 640,\n AV_HEIGHT: 480,\n AV_CDIM2: config.publisherId\n };\n const base = 'https://go.aniview.com/api/adserver6/vast/';\n return `${base}?${buildUrlParams(params)}`;\n }\n /**\n * In order for the SDK to display ads for our video, we need to tell it where to put them,\n * so here we define our ad container. This div is set up to render on top of the video player.\n * Using the code below, we tell the SDK to render ads within that div. We also provide a\n * handle to the content video player - the SDK will poll the current time of our player to\n * properly place mid-rolls. After we create the ad display container, we initialize it. On\n * mobile devices, this initialization is done as the result of a user action.\n */\n\n\n }\n\n const parseVtt = vttDataString => {\n const processedList = [];\n const frames = vttDataString.split(/\\r\\n\\r\\n|\\n\\n|\\r\\r/);\n frames.forEach(frame => {\n const result = {};\n const lines = frame.split(/\\r\\n|\\n|\\r/);\n lines.forEach(line => {\n if (!is.number(result.startTime)) {\n // The line with start and end times on it is the first line of interest\n 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\n\n if (matchTimes) {\n result.startTime = Number(matchTimes[1] || 0) * 60 * 60 + Number(matchTimes[2]) * 60 + Number(matchTimes[3]) + Number(`0.${matchTimes[4]}`);\n result.endTime = Number(matchTimes[6] || 0) * 60 * 60 + Number(matchTimes[7]) * 60 + Number(matchTimes[8]) + Number(`0.${matchTimes[9]}`);\n }\n } else if (!is.empty(line.trim()) && is.empty(result.text)) {\n // If we already have the startTime, then we're definitely up to the text line(s)\n const lineSplit = line.trim().split('#xywh=');\n [result.text] = lineSplit; // If there's content in lineSplit[1], then we have sprites. If not, then it's just one frame per image\n\n if (lineSplit[1]) {\n [result.x, result.y, result.w, result.h] = lineSplit[1].split(',');\n }\n }\n });\n\n if (result.text) {\n processedList.push(result);\n }\n });\n return processedList;\n };\n /**\n * Preview thumbnails for seek hover and scrubbing\n * Seeking: Hover over the seek bar (desktop only): shows a small preview container above the seek bar\n * 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\n *\n * Notes:\n * - 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\n * - 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\n * - 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\n */\n\n\n const fitRatio = (ratio, outer) => {\n const targetRatio = outer.width / outer.height;\n const result = {};\n\n if (ratio > targetRatio) {\n result.width = outer.width;\n result.height = 1 / ratio * outer.width;\n } else {\n result.height = outer.height;\n result.width = ratio * outer.height;\n }\n\n return result;\n };\n\n class PreviewThumbnails {\n /**\n * PreviewThumbnails constructor.\n * @param {Plyr} player\n * @return {PreviewThumbnails}\n */\n constructor(player) {\n _defineProperty$1(this, \"load\", () => {\n // Toggle the regular seek tooltip\n if (this.player.elements.display.seekTooltip) {\n this.player.elements.display.seekTooltip.hidden = this.enabled;\n }\n\n if (!this.enabled) {\n return;\n }\n\n this.getThumbnails().then(() => {\n if (!this.enabled) {\n return;\n } // Render DOM elements\n\n\n this.render(); // Check to see if thumb container size was specified manually in CSS\n\n this.determineContainerAutoSizing();\n this.loaded = true;\n });\n });\n\n _defineProperty$1(this, \"getThumbnails\", () => {\n return new Promise(resolve => {\n const {\n src\n } = this.player.config.previewThumbnails;\n\n if (is.empty(src)) {\n throw new Error('Missing previewThumbnails.src config attribute');\n } // Resolve promise\n\n\n const sortAndResolve = () => {\n // Sort smallest to biggest (e.g., [120p, 480p, 1080p])\n this.thumbnails.sort((x, y) => x.height - y.height);\n this.player.debug.log('Preview thumbnails', this.thumbnails);\n resolve();\n }; // Via callback()\n\n\n if (is.function(src)) {\n src(thumbnails => {\n this.thumbnails = thumbnails;\n sortAndResolve();\n });\n } // VTT urls\n else {\n // If string, convert into single-element list\n 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\n\n const promises = urls.map(u => this.getThumbnail(u)); // Resolve\n\n Promise.all(promises).then(sortAndResolve);\n }\n });\n });\n\n _defineProperty$1(this, \"getThumbnail\", url => {\n return new Promise(resolve => {\n fetch(url).then(response => {\n const thumbnail = {\n frames: parseVtt(response),\n height: null,\n urlPrefix: ''\n }; // If the URLs don't start with '/', then we need to set their relative path to be the location of the VTT file\n // If the URLs do start with '/', then they obviously don't need a prefix, so it will remain blank\n // If the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file\n\n if (!thumbnail.frames[0].text.startsWith('/') && !thumbnail.frames[0].text.startsWith('http://') && !thumbnail.frames[0].text.startsWith('https://')) {\n thumbnail.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1);\n } // Download the first frame, so that we can determine/set the height of this thumbnailsDef\n\n\n const tempImage = new Image();\n\n tempImage.onload = () => {\n thumbnail.height = tempImage.naturalHeight;\n thumbnail.width = tempImage.naturalWidth;\n this.thumbnails.push(thumbnail);\n resolve();\n };\n\n tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;\n });\n });\n });\n\n _defineProperty$1(this, \"startMove\", event => {\n if (!this.loaded) {\n return;\n }\n\n if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {\n return;\n } // Wait until media has a duration\n\n\n if (!this.player.media.duration) {\n return;\n }\n\n if (event.type === 'touchmove') {\n // Calculate seek hover position as approx video seconds\n this.seekTime = this.player.media.duration * (this.player.elements.inputs.seek.value / 100);\n } else {\n // Calculate seek hover position as approx video seconds\n const clientRect = this.player.elements.progress.getBoundingClientRect();\n const percentage = 100 / clientRect.width * (event.pageX - clientRect.left);\n this.seekTime = this.player.media.duration * (percentage / 100);\n\n if (this.seekTime < 0) {\n // The mousemove fires for 10+px out to the left\n this.seekTime = 0;\n }\n\n if (this.seekTime > this.player.media.duration - 1) {\n // Took 1 second off the duration for safety, because different players can disagree on the real duration of a video\n this.seekTime = this.player.media.duration - 1;\n }\n\n this.mousePosX = event.pageX; // Set time text inside image container\n\n this.elements.thumb.time.innerText = formatTime(this.seekTime);\n } // Download and show image\n\n\n this.showImageAtCurrentTime();\n });\n\n _defineProperty$1(this, \"endMove\", () => {\n this.toggleThumbContainer(false, true);\n });\n\n _defineProperty$1(this, \"startScrubbing\", event => {\n // Only act on left mouse button (0), or touch device (event.button does not exist or is false)\n if (is.nullOrUndefined(event.button) || event.button === false || event.button === 0) {\n this.mouseDown = true; // Wait until media has a duration\n\n if (this.player.media.duration) {\n this.toggleScrubbingContainer(true);\n this.toggleThumbContainer(false, true); // Download and show image\n\n this.showImageAtCurrentTime();\n }\n }\n });\n\n _defineProperty$1(this, \"endScrubbing\", () => {\n this.mouseDown = false; // Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview\n\n if (Math.ceil(this.lastTime) === Math.ceil(this.player.media.currentTime)) {\n // The video was already seeked/loaded at the chosen time - hide immediately\n this.toggleScrubbingContainer(false);\n } else {\n // The video hasn't seeked yet. Wait for that\n once.call(this.player, this.player.media, 'timeupdate', () => {\n // Re-check mousedown - we might have already started scrubbing again\n if (!this.mouseDown) {\n this.toggleScrubbingContainer(false);\n }\n });\n }\n });\n\n _defineProperty$1(this, \"listeners\", () => {\n // 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\n this.player.on('play', () => {\n this.toggleThumbContainer(false, true);\n });\n this.player.on('seeked', () => {\n this.toggleThumbContainer(false);\n });\n this.player.on('timeupdate', () => {\n this.lastTime = this.player.media.currentTime;\n });\n });\n\n _defineProperty$1(this, \"render\", () => {\n // Create HTML element: plyr__preview-thumbnail-container\n this.elements.thumb.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.thumbContainer\n }); // Wrapper for the image for styling\n\n this.elements.thumb.imageContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.imageContainer\n });\n this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer); // Create HTML element, parent+span: time text (e.g., 01:32:00)\n\n const timeContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.timeContainer\n });\n this.elements.thumb.time = createElement('span', {}, '00:00');\n timeContainer.appendChild(this.elements.thumb.time);\n this.elements.thumb.container.appendChild(timeContainer); // Inject the whole thumb\n\n if (is.element(this.player.elements.progress)) {\n this.player.elements.progress.appendChild(this.elements.thumb.container);\n } // Create HTML element: plyr__preview-scrubbing-container\n\n\n this.elements.scrubbing.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.scrubbingContainer\n });\n this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);\n });\n\n _defineProperty$1(this, \"destroy\", () => {\n if (this.elements.thumb.container) {\n this.elements.thumb.container.remove();\n }\n\n if (this.elements.scrubbing.container) {\n this.elements.scrubbing.container.remove();\n }\n });\n\n _defineProperty$1(this, \"showImageAtCurrentTime\", () => {\n if (this.mouseDown) {\n this.setScrubbingContainerSize();\n } else {\n this.setThumbContainerSizeAndPos();\n } // Find the desired thumbnail index\n // TODO: Handle a video longer than the thumbs where thumbNum is null\n\n\n const thumbNum = this.thumbnails[0].frames.findIndex(frame => this.seekTime >= frame.startTime && this.seekTime <= frame.endTime);\n const hasThumb = thumbNum >= 0;\n let qualityIndex = 0; // Show the thumb container if we're not scrubbing\n\n if (!this.mouseDown) {\n this.toggleThumbContainer(hasThumb);\n } // No matching thumb found\n\n\n if (!hasThumb) {\n return;\n } // Check to see if we've already downloaded higher quality versions of this image\n\n\n this.thumbnails.forEach((thumbnail, index) => {\n if (this.loadedImages.includes(thumbnail.frames[thumbNum].text)) {\n qualityIndex = index;\n }\n }); // Only proceed if either thumbnum or thumbfilename has changed\n\n if (thumbNum !== this.showingThumb) {\n this.showingThumb = thumbNum;\n this.loadImage(qualityIndex);\n }\n });\n\n _defineProperty$1(this, \"loadImage\", (qualityIndex = 0) => {\n const thumbNum = this.showingThumb;\n const thumbnail = this.thumbnails[qualityIndex];\n const {\n urlPrefix\n } = thumbnail;\n const frame = thumbnail.frames[thumbNum];\n const thumbFilename = thumbnail.frames[thumbNum].text;\n const thumbUrl = urlPrefix + thumbFilename;\n\n if (!this.currentImageElement || this.currentImageElement.dataset.filename !== thumbFilename) {\n // If we're already loading a previous image, remove its onload handler - we don't want it to load after this one\n // Only do this if not using sprites. Without sprites we really want to show as many images as possible, as a best-effort\n if (this.loadingImage && this.usingSprites) {\n this.loadingImage.onload = null;\n } // We're building and adding a new image. In other implementations of similar functionality (YouTube), background image\n // is instead used. But this causes issues with larger images in Firefox and Safari - switching between background\n // images causes a flicker. Putting a new image over the top does not\n\n\n const previewImage = new Image();\n previewImage.src = thumbUrl;\n previewImage.dataset.index = thumbNum;\n previewImage.dataset.filename = thumbFilename;\n this.showingThumbFilename = thumbFilename;\n 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...\n\n previewImage.onload = () => this.showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, true);\n\n this.loadingImage = previewImage;\n this.removeOldImages(previewImage);\n } else {\n // Update the existing image\n this.showImage(this.currentImageElement, frame, qualityIndex, thumbNum, thumbFilename, false);\n this.currentImageElement.dataset.index = thumbNum;\n this.removeOldImages(this.currentImageElement);\n }\n });\n\n _defineProperty$1(this, \"showImage\", (previewImage, frame, qualityIndex, thumbNum, thumbFilename, newImage = true) => {\n this.player.debug.log(`Showing thumb: ${thumbFilename}. num: ${thumbNum}. qual: ${qualityIndex}. newimg: ${newImage}`);\n this.setImageSizeAndOffset(previewImage, frame);\n\n if (newImage) {\n this.currentImageContainer.appendChild(previewImage);\n this.currentImageElement = previewImage;\n\n if (!this.loadedImages.includes(thumbFilename)) {\n this.loadedImages.push(thumbFilename);\n }\n } // Preload images before and after the current one\n // Show higher quality of the same frame\n // 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\n\n\n this.preloadNearby(thumbNum, true).then(this.preloadNearby(thumbNum, false)).then(this.getHigherQuality(qualityIndex, previewImage, frame, thumbFilename));\n });\n\n _defineProperty$1(this, \"removeOldImages\", currentImage => {\n // Get a list of all images, convert it from a DOM list to an array\n Array.from(this.currentImageContainer.children).forEach(image => {\n if (image.tagName.toLowerCase() !== 'img') {\n return;\n }\n\n const removeDelay = this.usingSprites ? 500 : 1000;\n\n if (image.dataset.index !== currentImage.dataset.index && !image.dataset.deleting) {\n // 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\n // First set attribute 'deleting' to prevent multi-handling of this on repeat firing of this function\n // eslint-disable-next-line no-param-reassign\n image.dataset.deleting = true; // This has to be set before the timeout - to prevent issues switching between hover and scrub\n\n const {\n currentImageContainer\n } = this;\n setTimeout(() => {\n currentImageContainer.removeChild(image);\n this.player.debug.log(`Removing thumb: ${image.dataset.filename}`);\n }, removeDelay);\n }\n });\n });\n\n _defineProperty$1(this, \"preloadNearby\", (thumbNum, forward = true) => {\n return new Promise(resolve => {\n setTimeout(() => {\n const oldThumbFilename = this.thumbnails[0].frames[thumbNum].text;\n\n if (this.showingThumbFilename === oldThumbFilename) {\n // 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\n let thumbnailsClone;\n\n if (forward) {\n thumbnailsClone = this.thumbnails[0].frames.slice(thumbNum);\n } else {\n thumbnailsClone = this.thumbnails[0].frames.slice(0, thumbNum).reverse();\n }\n\n let foundOne = false;\n thumbnailsClone.forEach(frame => {\n const newThumbFilename = frame.text;\n\n if (newThumbFilename !== oldThumbFilename) {\n // Found one with a different filename. Make sure it hasn't already been loaded on this page visit\n if (!this.loadedImages.includes(newThumbFilename)) {\n foundOne = true;\n this.player.debug.log(`Preloading thumb filename: ${newThumbFilename}`);\n const {\n urlPrefix\n } = this.thumbnails[0];\n const thumbURL = urlPrefix + newThumbFilename;\n const previewImage = new Image();\n previewImage.src = thumbURL;\n\n previewImage.onload = () => {\n this.player.debug.log(`Preloaded thumb filename: ${newThumbFilename}`);\n if (!this.loadedImages.includes(newThumbFilename)) this.loadedImages.push(newThumbFilename); // We don't resolve until the thumb is loaded\n\n resolve();\n };\n }\n }\n }); // If there are none to preload then we want to resolve immediately\n\n if (!foundOne) {\n resolve();\n }\n }\n }, 300);\n });\n });\n\n _defineProperty$1(this, \"getHigherQuality\", (currentQualityIndex, previewImage, frame, thumbFilename) => {\n if (currentQualityIndex < this.thumbnails.length - 1) {\n // 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\n let previewImageHeight = previewImage.naturalHeight;\n\n if (this.usingSprites) {\n previewImageHeight = frame.h;\n }\n\n if (previewImageHeight < this.thumbContainerHeight) {\n // Recurse back to the loadImage function - show a higher quality one, but only if the viewer is on this frame for a while\n setTimeout(() => {\n // Make sure the mouse hasn't already moved on and started hovering at another image\n if (this.showingThumbFilename === thumbFilename) {\n this.player.debug.log(`Showing higher quality thumb for: ${thumbFilename}`);\n this.loadImage(currentQualityIndex + 1);\n }\n }, 300);\n }\n }\n });\n\n _defineProperty$1(this, \"toggleThumbContainer\", (toggle = false, clearShowing = false) => {\n const className = this.player.config.classNames.previewThumbnails.thumbContainerShown;\n this.elements.thumb.container.classList.toggle(className, toggle);\n\n if (!toggle && clearShowing) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n });\n\n _defineProperty$1(this, \"toggleScrubbingContainer\", (toggle = false) => {\n const className = this.player.config.classNames.previewThumbnails.scrubbingContainerShown;\n this.elements.scrubbing.container.classList.toggle(className, toggle);\n\n if (!toggle) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n });\n\n _defineProperty$1(this, \"determineContainerAutoSizing\", () => {\n if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) {\n // This will prevent auto sizing in this.setThumbContainerSizeAndPos()\n this.sizeSpecifiedInCSS = true;\n }\n });\n\n _defineProperty$1(this, \"setThumbContainerSizeAndPos\", () => {\n if (!this.sizeSpecifiedInCSS) {\n const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${this.thumbContainerHeight}px`;\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (this.elements.thumb.imageContainer.clientHeight > 20 && this.elements.thumb.imageContainer.clientWidth < 20) {\n const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (this.elements.thumb.imageContainer.clientHeight < 20 && this.elements.thumb.imageContainer.clientWidth > 20) {\n const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`;\n }\n\n this.setThumbContainerPos();\n });\n\n _defineProperty$1(this, \"setThumbContainerPos\", () => {\n const seekbarRect = this.player.elements.progress.getBoundingClientRect();\n const plyrRect = this.player.elements.container.getBoundingClientRect();\n const {\n container\n } = this.elements.thumb; // Find the lowest and highest desired left-position, so we don't slide out the side of the video container\n\n const minVal = plyrRect.left - seekbarRect.left + 10;\n const maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10; // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth\n\n let previewPos = this.mousePosX - seekbarRect.left - container.clientWidth / 2;\n\n if (previewPos < minVal) {\n previewPos = minVal;\n }\n\n if (previewPos > maxVal) {\n previewPos = maxVal;\n }\n\n container.style.left = `${previewPos}px`;\n });\n\n _defineProperty$1(this, \"setScrubbingContainerSize\", () => {\n const {\n width,\n height\n } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight\n });\n this.elements.scrubbing.container.style.width = `${width}px`;\n this.elements.scrubbing.container.style.height = `${height}px`;\n });\n\n _defineProperty$1(this, \"setImageSizeAndOffset\", (previewImage, frame) => {\n if (!this.usingSprites) {\n return;\n } // Find difference between height and preview container height\n\n\n const multiplier = this.thumbContainerHeight / frame.h; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.left = `-${frame.x * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.top = `-${frame.y * multiplier}px`;\n });\n\n this.player = player;\n this.thumbnails = [];\n this.loaded = false;\n this.lastMouseMoveTime = Date.now();\n this.mouseDown = false;\n this.loadedImages = [];\n this.elements = {\n thumb: {},\n scrubbing: {}\n };\n this.load();\n }\n\n get enabled() {\n return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;\n }\n\n get currentImageContainer() {\n if (this.mouseDown) {\n return this.elements.scrubbing.container;\n }\n\n return this.elements.thumb.imageContainer;\n }\n\n get usingSprites() {\n return Object.keys(this.thumbnails[0].frames[0]).includes('w');\n }\n\n get thumbAspectRatio() {\n if (this.usingSprites) {\n return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;\n }\n\n return this.thumbnails[0].width / this.thumbnails[0].height;\n }\n\n get thumbContainerHeight() {\n if (this.mouseDown) {\n const {\n height\n } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight\n });\n return height;\n } // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset)\n\n\n if (this.sizeSpecifiedInCSS) {\n return this.elements.thumb.imageContainer.clientHeight;\n }\n\n return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);\n }\n\n get currentImageElement() {\n if (this.mouseDown) {\n return this.currentScrubbingImageElement;\n }\n\n return this.currentThumbnailImageElement;\n }\n\n set currentImageElement(element) {\n if (this.mouseDown) {\n this.currentScrubbingImageElement = element;\n } else {\n this.currentThumbnailImageElement = element;\n }\n }\n\n }\n\n // ==========================================================================\n const source = {\n // Add elements to HTML5 media (source, tracks, etc)\n insertElements(type, attributes) {\n if (is.string(attributes)) {\n insertElement(type, this.media, {\n src: attributes\n });\n } else if (is.array(attributes)) {\n attributes.forEach(attribute => {\n insertElement(type, this.media, attribute);\n });\n }\n },\n\n // Update source\n // Sources are not checked for support so be careful\n change(input) {\n if (!getDeep(input, 'sources.length')) {\n this.debug.warn('Invalid source format');\n return;\n } // Cancel current network requests\n\n\n html5.cancelRequests.call(this); // Destroy instance and re-setup\n\n this.destroy.call(this, () => {\n // Reset quality options\n this.options.quality = []; // Remove elements\n\n removeElement(this.media);\n this.media = null; // Reset class name\n\n if (is.element(this.elements.container)) {\n this.elements.container.removeAttribute('class');\n } // Set the type and provider\n\n\n const {\n sources,\n type\n } = input;\n const [{\n provider = providers.html5,\n src\n }] = sources;\n const tagName = provider === 'html5' ? type : 'div';\n const attributes = provider === 'html5' ? {} : {\n src\n };\n Object.assign(this, {\n provider,\n type,\n // Check for support\n supported: support.check(type, provider, this.config.playsinline),\n // Create new element\n media: createElement(tagName, attributes)\n }); // Inject the new element\n\n this.elements.container.appendChild(this.media); // Autoplay the new source?\n\n if (is.boolean(input.autoplay)) {\n this.config.autoplay = input.autoplay;\n } // Set attributes for audio and video\n\n\n if (this.isHTML5) {\n if (this.config.crossorigin) {\n this.media.setAttribute('crossorigin', '');\n }\n\n if (this.config.autoplay) {\n this.media.setAttribute('autoplay', '');\n }\n\n if (!is.empty(input.poster)) {\n this.poster = input.poster;\n }\n\n if (this.config.loop.active) {\n this.media.setAttribute('loop', '');\n }\n\n if (this.config.muted) {\n this.media.setAttribute('muted', '');\n }\n\n if (this.config.playsinline) {\n this.media.setAttribute('playsinline', '');\n }\n } // Restore class hook\n\n\n ui.addStyleHook.call(this); // Set new sources for html5\n\n if (this.isHTML5) {\n source.insertElements.call(this, 'source', sources);\n } // Set video title\n\n\n this.config.title = input.title; // Set up from scratch\n\n media.setup.call(this); // HTML5 stuff\n\n if (this.isHTML5) {\n // Setup captions\n if (Object.keys(input).includes('tracks')) {\n source.insertElements.call(this, 'track', input.tracks);\n }\n } // If HTML5 or embed but not fully supported, setupInterface and call ready now\n\n\n if (this.isHTML5 || this.isEmbed && !this.supported.ui) {\n // Setup interface\n ui.build.call(this);\n } // Load HTML5 sources\n\n\n if (this.isHTML5) {\n this.media.load();\n } // Update previewThumbnails config & reload plugin\n\n\n if (!is.empty(input.previewThumbnails)) {\n Object.assign(this.config.previewThumbnails, input.previewThumbnails); // Cleanup previewThumbnails plugin if it was loaded\n\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n } // Create new instance if it is still enabled\n\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n } // Update the fullscreen support\n\n\n this.fullscreen.update();\n }, true);\n }\n\n };\n\n /**\n * Returns a number whose value is limited to the given range.\n *\n * Example: limit the output of this computation to between 0 and 255\n * (x * 255).clamp(0, 255)\n *\n * @param {Number} input\n * @param {Number} min The lower boundary of the output range\n * @param {Number} max The upper boundary of the output range\n * @returns A number in the range [min, max]\n * @type Number\n */\n function clamp(input = 0, min = 0, max = 255) {\n return Math.min(Math.max(input, min), max);\n }\n\n // TODO: Use a WeakMap for private globals\n // const globals = new WeakMap();\n // Plyr instance\n\n class Plyr {\n constructor(target, options) {\n _defineProperty$1(this, \"play\", () => {\n if (!is.function(this.media.play)) {\n return null;\n } // Intecept play with ads\n\n\n if (this.ads && this.ads.enabled) {\n this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play()));\n } // Return the promise (for HTML5)\n\n\n return this.media.play();\n });\n\n _defineProperty$1(this, \"pause\", () => {\n if (!this.playing || !is.function(this.media.pause)) {\n return null;\n }\n\n return this.media.pause();\n });\n\n _defineProperty$1(this, \"togglePlay\", input => {\n // Toggle based on current state if nothing passed\n const toggle = is.boolean(input) ? input : !this.playing;\n\n if (toggle) {\n return this.play();\n }\n\n return this.pause();\n });\n\n _defineProperty$1(this, \"stop\", () => {\n if (this.isHTML5) {\n this.pause();\n this.restart();\n } else if (is.function(this.media.stop)) {\n this.media.stop();\n }\n });\n\n _defineProperty$1(this, \"restart\", () => {\n this.currentTime = 0;\n });\n\n _defineProperty$1(this, \"rewind\", seekTime => {\n this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime;\n });\n\n _defineProperty$1(this, \"forward\", seekTime => {\n this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime;\n });\n\n _defineProperty$1(this, \"increaseVolume\", step => {\n const volume = this.media.muted ? 0 : this.volume;\n this.volume = volume + (is.number(step) ? step : 0);\n });\n\n _defineProperty$1(this, \"decreaseVolume\", step => {\n this.increaseVolume(-step);\n });\n\n _defineProperty$1(this, \"airplay\", () => {\n // Show dialog if supported\n if (support.airplay) {\n this.media.webkitShowPlaybackTargetPicker();\n }\n });\n\n _defineProperty$1(this, \"toggleControls\", toggle => {\n // Don't toggle if missing UI support or if it's audio\n if (this.supported.ui && !this.isAudio) {\n // Get state before change\n const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls); // Negate the argument if not undefined since adding the class to hides the controls\n\n const force = typeof toggle === 'undefined' ? undefined : !toggle; // Apply and get updated state\n\n const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force); // Close menu\n\n if (hiding && is.array(this.config.controls) && this.config.controls.includes('settings') && !is.empty(this.config.settings)) {\n controls.toggleMenu.call(this, false);\n } // Trigger event on change\n\n\n if (hiding !== isHidden) {\n const eventName = hiding ? 'controlshidden' : 'controlsshown';\n triggerEvent.call(this, this.media, eventName);\n }\n\n return !hiding;\n }\n\n return false;\n });\n\n _defineProperty$1(this, \"on\", (event, callback) => {\n on.call(this, this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"once\", (event, callback) => {\n once.call(this, this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"off\", (event, callback) => {\n off(this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"destroy\", (callback, soft = false) => {\n if (!this.ready) {\n return;\n }\n\n const done = () => {\n // Reset overflow (incase destroyed while in fullscreen)\n document.body.style.overflow = ''; // GC for embed\n\n this.embed = null; // If it's a soft destroy, make minimal changes\n\n if (soft) {\n if (Object.keys(this.elements).length) {\n // Remove elements\n removeElement(this.elements.buttons.play);\n removeElement(this.elements.captions);\n removeElement(this.elements.controls);\n removeElement(this.elements.wrapper); // Clear for GC\n\n this.elements.buttons.play = null;\n this.elements.captions = null;\n this.elements.controls = null;\n this.elements.wrapper = null;\n } // Callback\n\n\n if (is.function(callback)) {\n callback();\n }\n } else {\n // Unbind listeners\n unbindListeners.call(this); // Cancel current network requests\n\n html5.cancelRequests.call(this); // Replace the container with the original element provided\n\n replaceElement(this.elements.original, this.elements.container); // Event\n\n triggerEvent.call(this, this.elements.original, 'destroyed', true); // Callback\n\n if (is.function(callback)) {\n callback.call(this.elements.original);\n } // Reset state\n\n\n this.ready = false; // Clear for garbage collection\n\n setTimeout(() => {\n this.elements = null;\n this.media = null;\n }, 200);\n }\n }; // Stop playback\n\n\n this.stop(); // Clear timeouts\n\n clearTimeout(this.timers.loading);\n clearTimeout(this.timers.controls);\n clearTimeout(this.timers.resized); // Provider specific stuff\n\n if (this.isHTML5) {\n // Restore native video controls\n ui.toggleNativeControls.call(this, true); // Clean up\n\n done();\n } else if (this.isYouTube) {\n // Clear timers\n clearInterval(this.timers.buffering);\n clearInterval(this.timers.playing); // Destroy YouTube API\n\n if (this.embed !== null && is.function(this.embed.destroy)) {\n this.embed.destroy();\n } // Clean up\n\n\n done();\n } else if (this.isVimeo) {\n // Destroy Vimeo API\n // then clean up (wait, to prevent postmessage errors)\n if (this.embed !== null) {\n this.embed.unload().then(done);\n } // Vimeo does not always return\n\n\n setTimeout(done, 200);\n }\n });\n\n _defineProperty$1(this, \"supports\", type => support.mime.call(this, type));\n\n this.timers = {}; // State\n\n this.ready = false;\n this.loading = false;\n this.failed = false; // Touch device\n\n this.touch = support.touch; // Set the media element\n\n this.media = target; // String selector passed\n\n if (is.string(this.media)) {\n this.media = document.querySelectorAll(this.media);\n } // jQuery, NodeList or Array passed, use first element\n\n\n if (window.jQuery && this.media instanceof jQuery || is.nodeList(this.media) || is.array(this.media)) {\n // eslint-disable-next-line\n this.media = this.media[0];\n } // Set config\n\n\n this.config = extend({}, defaults, Plyr.defaults, options || {}, (() => {\n try {\n return JSON.parse(this.media.getAttribute('data-plyr-config'));\n } catch (_) {\n return {};\n }\n })()); // Elements cache\n\n this.elements = {\n container: null,\n fullscreen: null,\n captions: null,\n buttons: {},\n display: {},\n progress: {},\n inputs: {},\n settings: {\n popup: null,\n menu: null,\n panels: {},\n buttons: {}\n }\n }; // Captions\n\n this.captions = {\n active: null,\n currentTrack: -1,\n meta: new WeakMap()\n }; // Fullscreen\n\n this.fullscreen = {\n active: false\n }; // Options\n\n this.options = {\n speed: [],\n quality: []\n }; // Debugging\n // TODO: move to globals\n\n this.debug = new Console(this.config.debug); // Log config options and support\n\n this.debug.log('Config', this.config);\n this.debug.log('Support', support); // We need an element to setup\n\n if (is.nullOrUndefined(this.media) || !is.element(this.media)) {\n this.debug.error('Setup failed: no suitable element passed');\n return;\n } // Bail if the element is initialized\n\n\n if (this.media.plyr) {\n this.debug.warn('Target already setup');\n return;\n } // Bail if not enabled\n\n\n if (!this.config.enabled) {\n this.debug.error('Setup failed: disabled by config');\n return;\n } // Bail if disabled or no basic support\n // You may want to disable certain UAs etc\n\n\n if (!support.check().api) {\n this.debug.error('Setup failed: no support');\n return;\n } // Cache original element state for .destroy()\n\n\n const clone = this.media.cloneNode(true);\n clone.autoplay = false;\n this.elements.original = clone; // Set media type based on tag or data attribute\n // Supported: video, audio, vimeo, youtube\n\n const _type = this.media.tagName.toLowerCase(); // Embed properties\n\n\n let iframe = null;\n let url = null; // Different setup based on type\n\n switch (_type) {\n case 'div':\n // Find the frame\n iframe = this.media.querySelector('iframe'); // <iframe> type\n\n if (is.element(iframe)) {\n // Detect provider\n url = parseUrl(iframe.getAttribute('src'));\n this.provider = getProviderByUrl(url.toString()); // Rework elements\n\n this.elements.container = this.media;\n this.media = iframe; // Reset classname\n\n this.elements.container.className = ''; // Get attributes from URL and set config\n\n if (url.search.length) {\n const truthy = ['1', 'true'];\n\n if (truthy.includes(url.searchParams.get('autoplay'))) {\n this.config.autoplay = true;\n }\n\n if (truthy.includes(url.searchParams.get('loop'))) {\n this.config.loop.active = true;\n } // TODO: replace fullscreen.iosNative with this playsinline config option\n // YouTube requires the playsinline in the URL\n\n\n if (this.isYouTube) {\n this.config.playsinline = truthy.includes(url.searchParams.get('playsinline'));\n this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language?\n } else {\n this.config.playsinline = true;\n }\n }\n } else {\n // <div> with attributes\n this.provider = this.media.getAttribute(this.config.attributes.embed.provider); // Remove attribute\n\n this.media.removeAttribute(this.config.attributes.embed.provider);\n } // Unsupported or missing provider\n\n\n if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) {\n this.debug.error('Setup failed: Invalid provider');\n return;\n } // Audio will come later for external providers\n\n\n this.type = types.video;\n break;\n\n case 'video':\n case 'audio':\n this.type = _type;\n this.provider = providers.html5; // Get config from attributes\n\n if (this.media.hasAttribute('crossorigin')) {\n this.config.crossorigin = true;\n }\n\n if (this.media.hasAttribute('autoplay')) {\n this.config.autoplay = true;\n }\n\n if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) {\n this.config.playsinline = true;\n }\n\n if (this.media.hasAttribute('muted')) {\n this.config.muted = true;\n }\n\n if (this.media.hasAttribute('loop')) {\n this.config.loop.active = true;\n }\n\n break;\n\n default:\n this.debug.error('Setup failed: unsupported type');\n return;\n } // Check for support again but with type\n\n\n this.supported = support.check(this.type, this.provider, this.config.playsinline); // If no support for even API, bail\n\n if (!this.supported.api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n this.eventListeners = []; // Create listeners\n\n this.listeners = new Listeners(this); // Setup local storage for user settings\n\n this.storage = new Storage(this); // Store reference\n\n this.media.plyr = this; // Wrap media\n\n if (!is.element(this.elements.container)) {\n this.elements.container = createElement('div', {\n tabindex: 0\n });\n wrap(this.media, this.elements.container);\n } // Migrate custom properties from media to container (so they work 😉)\n\n\n ui.migrateStyles.call(this); // Add style hook\n\n ui.addStyleHook.call(this); // Setup media\n\n media.setup.call(this); // Listen for events if debugging\n\n if (this.config.debug) {\n on.call(this, this.elements.container, this.config.events.join(' '), event => {\n this.debug.log(`event: ${event.type}`);\n });\n } // Setup fullscreen\n\n\n this.fullscreen = new Fullscreen(this); // Setup interface\n // If embed but not fully supported, build interface now to avoid flash of controls\n\n if (this.isHTML5 || this.isEmbed && !this.supported.ui) {\n ui.build.call(this);\n } // Container listeners\n\n\n this.listeners.container(); // Global listeners\n\n this.listeners.global(); // Setup ads if provided\n\n if (this.config.ads.enabled) {\n this.ads = new Ads(this);\n } // Autoplay if required\n\n\n if (this.isHTML5 && this.config.autoplay) {\n this.once('canplay', () => silencePromise(this.play()));\n } // Seek time will be recorded (in listeners.js) so we can prevent hiding controls for a few seconds after seek\n\n\n this.lastSeekTime = 0; // Setup preview thumbnails if enabled\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n } // ---------------------------------------\n // API\n // ---------------------------------------\n\n /**\n * Types and provider helpers\n */\n\n\n get isHTML5() {\n return this.provider === providers.html5;\n }\n\n get isEmbed() {\n return this.isYouTube || this.isVimeo;\n }\n\n get isYouTube() {\n return this.provider === providers.youtube;\n }\n\n get isVimeo() {\n return this.provider === providers.vimeo;\n }\n\n get isVideo() {\n return this.type === types.video;\n }\n\n get isAudio() {\n return this.type === types.audio;\n }\n /**\n * Play the media, or play the advertisement (if they are not blocked)\n */\n\n\n /**\n * Get playing state\n */\n get playing() {\n return Boolean(this.ready && !this.paused && !this.ended);\n }\n /**\n * Get paused state\n */\n\n\n get paused() {\n return Boolean(this.media.paused);\n }\n /**\n * Get stopped state\n */\n\n\n get stopped() {\n return Boolean(this.paused && this.currentTime === 0);\n }\n /**\n * Get ended state\n */\n\n\n get ended() {\n return Boolean(this.media.ended);\n }\n /**\n * Toggle playback based on current status\n * @param {Boolean} input\n */\n\n\n /**\n * Seek to a time\n * @param {Number} input - where to seek to in seconds. Defaults to 0 (the start)\n */\n set currentTime(input) {\n // Bail if media duration isn't available yet\n if (!this.duration) {\n return;\n } // Validate input\n\n\n const inputIsValid = is.number(input) && input > 0; // Set\n\n this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0; // Logging\n\n this.debug.log(`Seeking to ${this.currentTime} seconds`);\n }\n /**\n * Get current time\n */\n\n\n get currentTime() {\n return Number(this.media.currentTime);\n }\n /**\n * Get buffered\n */\n\n\n get buffered() {\n const {\n buffered\n } = this.media; // YouTube / Vimeo return a float between 0-1\n\n if (is.number(buffered)) {\n return buffered;\n } // HTML5\n // TODO: Handle buffered chunks of the media\n // (i.e. seek to another section buffers only that section)\n\n\n if (buffered && buffered.length && this.duration > 0) {\n return buffered.end(0) / this.duration;\n }\n\n return 0;\n }\n /**\n * Get seeking status\n */\n\n\n get seeking() {\n return Boolean(this.media.seeking);\n }\n /**\n * Get the duration of the current media\n */\n\n\n get duration() {\n // Faux duration set via config\n const fauxDuration = parseFloat(this.config.duration); // Media duration can be NaN or Infinity before the media has loaded\n\n const realDuration = (this.media || {}).duration;\n const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration; // If config duration is funky, use regular duration\n\n return fauxDuration || duration;\n }\n /**\n * Set the player volume\n * @param {Number} value - must be between 0 and 1. Defaults to the value from local storage and config.volume if not set in storage\n */\n\n\n set volume(value) {\n let volume = value;\n const max = 1;\n const min = 0;\n\n if (is.string(volume)) {\n volume = Number(volume);\n } // Load volume from storage if no value specified\n\n\n if (!is.number(volume)) {\n volume = this.storage.get('volume');\n } // Use config if all else fails\n\n\n if (!is.number(volume)) {\n ({\n volume\n } = this.config);\n } // Maximum is volumeMax\n\n\n if (volume > max) {\n volume = max;\n } // Minimum is volumeMin\n\n\n if (volume < min) {\n volume = min;\n } // Update config\n\n\n this.config.volume = volume; // Set the player volume\n\n this.media.volume = volume; // If muted, and we're increasing volume manually, reset muted state\n\n if (!is.empty(value) && this.muted && volume > 0) {\n this.muted = false;\n }\n }\n /**\n * Get the current player volume\n */\n\n\n get volume() {\n return Number(this.media.volume);\n }\n /**\n * Increase volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n\n\n /**\n * Set muted state\n * @param {Boolean} mute\n */\n set muted(mute) {\n let toggle = mute; // Load muted state from storage\n\n if (!is.boolean(toggle)) {\n toggle = this.storage.get('muted');\n } // Use config if all else fails\n\n\n if (!is.boolean(toggle)) {\n toggle = this.config.muted;\n } // Update config\n\n\n this.config.muted = toggle; // Set mute on the player\n\n this.media.muted = toggle;\n }\n /**\n * Get current muted state\n */\n\n\n get muted() {\n return Boolean(this.media.muted);\n }\n /**\n * Check if the media has audio\n */\n\n\n get hasAudio() {\n // Assume yes for all non HTML5 (as we can't tell...)\n if (!this.isHTML5) {\n return true;\n }\n\n if (this.isAudio) {\n return true;\n } // Get audio tracks\n\n\n return Boolean(this.media.mozHasAudio) || Boolean(this.media.webkitAudioDecodedByteCount) || Boolean(this.media.audioTracks && this.media.audioTracks.length);\n }\n /**\n * Set playback speed\n * @param {Number} speed - the speed of playback (0.5-2.0)\n */\n\n\n set speed(input) {\n let speed = null;\n\n if (is.number(input)) {\n speed = input;\n }\n\n if (!is.number(speed)) {\n speed = this.storage.get('speed');\n }\n\n if (!is.number(speed)) {\n speed = this.config.speed.selected;\n } // Clamp to min/max\n\n\n const {\n minimumSpeed: min,\n maximumSpeed: max\n } = this;\n speed = clamp(speed, min, max); // Update config\n\n this.config.speed.selected = speed; // Set media speed\n\n setTimeout(() => {\n if (this.media) {\n this.media.playbackRate = speed;\n }\n }, 0);\n }\n /**\n * Get current playback speed\n */\n\n\n get speed() {\n return Number(this.media.playbackRate);\n }\n /**\n * Get the minimum allowed speed\n */\n\n\n get minimumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.min(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 0.5;\n } // https://stackoverflow.com/a/32320020/1191319\n\n\n return 0.0625;\n }\n /**\n * Get the maximum allowed speed\n */\n\n\n get maximumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.max(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 2;\n } // https://stackoverflow.com/a/32320020/1191319\n\n\n return 16;\n }\n /**\n * Set playback quality\n * Currently HTML5 & YouTube only\n * @param {Number} input - Quality level\n */\n\n\n set quality(input) {\n const config = this.config.quality;\n const options = this.options.quality;\n\n if (!options.length) {\n return;\n }\n\n let quality = [!is.empty(input) && Number(input), this.storage.get('quality'), config.selected, config.default].find(is.number);\n let updateStorage = true;\n\n if (!options.includes(quality)) {\n const value = closest(options, quality);\n this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`);\n quality = value; // Don't update storage if quality is not supported\n\n updateStorage = false;\n } // Update config\n\n\n config.selected = quality; // Set quality\n\n this.media.quality = quality; // Save to storage\n\n if (updateStorage) {\n this.storage.set({\n quality\n });\n }\n }\n /**\n * Get current quality level\n */\n\n\n get quality() {\n return this.media.quality;\n }\n /**\n * Toggle loop\n * TODO: Finish fancy new logic. Set the indicator on load as user may pass loop as config\n * @param {Boolean} input - Whether to loop or not\n */\n\n\n set loop(input) {\n const toggle = is.boolean(input) ? input : this.config.loop.active;\n this.config.loop.active = toggle;\n this.media.loop = toggle; // Set default to be a true toggle\n\n /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle';\n switch (type) {\n case 'start':\n if (this.config.loop.end && this.config.loop.end <= this.currentTime) {\n this.config.loop.end = null;\n }\n this.config.loop.start = this.currentTime;\n // this.config.loop.indicator.start = this.elements.display.played.value;\n break;\n case 'end':\n if (this.config.loop.start >= this.currentTime) {\n return this;\n }\n this.config.loop.end = this.currentTime;\n // this.config.loop.indicator.end = this.elements.display.played.value;\n break;\n case 'all':\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n this.config.loop.indicator.start = 0;\n this.config.loop.indicator.end = 100;\n break;\n case 'toggle':\n if (this.config.loop.active) {\n this.config.loop.start = 0;\n this.config.loop.end = null;\n } else {\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n }\n break;\n default:\n this.config.loop.start = 0;\n this.config.loop.end = null;\n break;\n } */\n }\n /**\n * Get current loop state\n */\n\n\n get loop() {\n return Boolean(this.media.loop);\n }\n /**\n * Set new media source\n * @param {Object} input - The new source object (see docs)\n */\n\n\n set source(input) {\n source.change.call(this, input);\n }\n /**\n * Get current source\n */\n\n\n get source() {\n return this.media.currentSrc;\n }\n /**\n * Get a download URL (either source or custom)\n */\n\n\n get download() {\n const {\n download\n } = this.config.urls;\n return is.url(download) ? download : this.source;\n }\n /**\n * Set the download URL\n */\n\n\n set download(input) {\n if (!is.url(input)) {\n return;\n }\n\n this.config.urls.download = input;\n controls.setDownloadUrl.call(this);\n }\n /**\n * Set the poster image for a video\n * @param {String} input - the URL for the new poster image\n */\n\n\n set poster(input) {\n if (!this.isVideo) {\n this.debug.warn('Poster can only be set for video');\n return;\n }\n\n ui.setPoster.call(this, input, false).catch(() => {});\n }\n /**\n * Get the current poster image\n */\n\n\n get poster() {\n if (!this.isVideo) {\n return null;\n }\n\n return this.media.getAttribute('poster') || this.media.getAttribute('data-poster');\n }\n /**\n * Get the current aspect ratio in use\n */\n\n\n get ratio() {\n if (!this.isVideo) {\n return null;\n }\n\n const ratio = reduceAspectRatio(getAspectRatio.call(this));\n return is.array(ratio) ? ratio.join(':') : ratio;\n }\n /**\n * Set video aspect ratio\n */\n\n\n set ratio(input) {\n if (!this.isVideo) {\n this.debug.warn('Aspect ratio can only be set for video');\n return;\n }\n\n if (!is.string(input) || !validateAspectRatio(input)) {\n this.debug.error(`Invalid aspect ratio specified (${input})`);\n return;\n }\n\n this.config.ratio = reduceAspectRatio(input);\n setAspectRatio.call(this);\n }\n /**\n * Set the autoplay state\n * @param {Boolean} input - Whether to autoplay or not\n */\n\n\n set autoplay(input) {\n const toggle = is.boolean(input) ? input : this.config.autoplay;\n this.config.autoplay = toggle;\n }\n /**\n * Get the current autoplay state\n */\n\n\n get autoplay() {\n return Boolean(this.config.autoplay);\n }\n /**\n * Toggle captions\n * @param {Boolean} input - Whether to enable captions\n */\n\n\n toggleCaptions(input) {\n captions.toggle.call(this, input, false);\n }\n /**\n * Set the caption track by index\n * @param {Number} - Caption index\n */\n\n\n set currentTrack(input) {\n captions.set.call(this, input, false);\n captions.setup();\n }\n /**\n * Get the current caption track index (-1 if disabled)\n */\n\n\n get currentTrack() {\n const {\n toggled,\n currentTrack\n } = this.captions;\n return toggled ? currentTrack : -1;\n }\n /**\n * Set the wanted language for captions\n * Since tracks can be added later it won't update the actual caption track until there is a matching track\n * @param {String} - Two character ISO language code (e.g. EN, FR, PT, etc)\n */\n\n\n set language(input) {\n captions.setLanguage.call(this, input, false);\n }\n /**\n * Get the current track's language\n */\n\n\n get language() {\n return (captions.getCurrentTrack.call(this) || {}).language;\n }\n /**\n * Toggle picture-in-picture playback on WebKit/MacOS\n * TODO: update player with state, support, enabled\n * TODO: detect outside changes\n */\n\n\n set pip(input) {\n // Bail if no support\n if (!support.pip) {\n return;\n } // Toggle based on current state if not passed\n\n\n const toggle = is.boolean(input) ? input : !this.pip; // Toggle based on current state\n // Safari\n\n if (is.function(this.media.webkitSetPresentationMode)) {\n this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive);\n } // Chrome\n\n\n if (is.function(this.media.requestPictureInPicture)) {\n if (!this.pip && toggle) {\n this.media.requestPictureInPicture();\n } else if (this.pip && !toggle) {\n document.exitPictureInPicture();\n }\n }\n }\n /**\n * Get the current picture-in-picture state\n */\n\n\n get pip() {\n if (!support.pip) {\n return null;\n } // Safari\n\n\n if (!is.empty(this.media.webkitPresentationMode)) {\n return this.media.webkitPresentationMode === pip.active;\n } // Chrome\n\n\n return this.media === document.pictureInPictureElement;\n }\n /**\n * Sets the preview thubmnails for the current source\n */\n\n\n setPreviewThumbnails(thumbnailSource) {\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n Object.assign(this.config.previewThumbnails, thumbnailSource); // Create new instance if it is still enabled\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n /**\n * Trigger the airplay dialog\n * TODO: update player with state, support, enabled\n */\n\n\n /**\n * Check for support\n * @param {String} type - Player type (audio/video)\n * @param {String} provider - Provider (html5/youtube/vimeo)\n * @param {Boolean} inline - Where player has `playsinline` sttribute\n */\n static supported(type, provider, inline) {\n return support.check(type, provider, inline);\n }\n /**\n * Load an SVG sprite into the page\n * @param {String} url - URL for the SVG sprite\n * @param {String} [id] - Unique ID\n */\n\n\n static loadSprite(url, id) {\n return loadSprite(url, id);\n }\n /**\n * Setup multiple instances\n * @param {*} selector\n * @param {Object} options\n */\n\n\n static setup(selector, options = {}) {\n let targets = null;\n\n if (is.string(selector)) {\n targets = Array.from(document.querySelectorAll(selector));\n } else if (is.nodeList(selector)) {\n targets = Array.from(selector);\n } else if (is.array(selector)) {\n targets = selector.filter(is.element);\n }\n\n if (is.empty(targets)) {\n return null;\n }\n\n return targets.map(t => new Plyr(t, options));\n }\n\n }\n\n Plyr.defaults = cloneDeep(defaults);\n\n // ==========================================================================\n\n return Plyr;\n\n}));\n","// Polyfill for creating CustomEvents on IE9/10/11\n\n// code pulled from:\n// https://github.com/d4tocchini/customevent-polyfill\n// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill\n\n(function() {\n if (typeof window === 'undefined') {\n return;\n }\n\n try {\n var ce = new window.CustomEvent('test', { cancelable: true });\n ce.preventDefault();\n if (ce.defaultPrevented !== true) {\n // IE has problems with .preventDefault() on custom events\n // http://stackoverflow.com/questions/23349191\n throw new Error('Could not prevent default');\n }\n } catch (e) {\n var CustomEvent = function(event, params) {\n var evt, origPrevent;\n params = params || {};\n params.bubbles = !!params.bubbles;\n params.cancelable = !!params.cancelable;\n\n evt = document.createEvent('CustomEvent');\n evt.initCustomEvent(\n event,\n params.bubbles,\n params.cancelable,\n params.detail\n );\n origPrevent = evt.preventDefault;\n evt.preventDefault = function() {\n origPrevent.call(this);\n try {\n Object.defineProperty(this, 'defaultPrevented', {\n get: function() {\n return true;\n }\n });\n } catch (e) {\n this.defaultPrevented = true;\n }\n };\n return evt;\n };\n\n CustomEvent.prototype = window.Event.prototype;\n window.CustomEvent = CustomEvent; // expose definition to window\n }\n})();\n","function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var defaults={addCSS:!0,thumbWidth:15,watch:!0};function matches(e,t){return function(){return Array.from(document.querySelectorAll(t)).includes(this)}.call(e,t)}function trigger(e,t){if(e&&t){var n=new Event(t,{bubbles:!0});e.dispatchEvent(n)}}var getConstructor=function(e){return null!=e?e.constructor:null},instanceOf=function(e,t){return!!(e&&t&&e instanceof t)},isNullOrUndefined=function(e){return null==e},isObject=function(e){return getConstructor(e)===Object},isNumber=function(e){return getConstructor(e)===Number&&!Number.isNaN(e)},isString=function(e){return getConstructor(e)===String},isBoolean=function(e){return getConstructor(e)===Boolean},isFunction=function(e){return getConstructor(e)===Function},isArray=function(e){return Array.isArray(e)},isNodeList=function(e){return instanceOf(e,NodeList)},isElement=function(e){return instanceOf(e,Element)},isEvent=function(e){return instanceOf(e,Event)},isEmpty=function(e){return isNullOrUndefined(e)||(isString(e)||isArray(e)||isNodeList(e))&&!e.length||isObject(e)&&!Object.keys(e).length},is={nullOrUndefined:isNullOrUndefined,object:isObject,number:isNumber,string:isString,boolean:isBoolean,function:isFunction,array:isArray,nodeList:isNodeList,element:isElement,event:isEvent,empty:isEmpty};function getDecimalPlaces(e){var t=\"\".concat(e).match(/(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0}function round(e,t){if(1>t){var n=getDecimalPlaces(t);return parseFloat(e.toFixed(n))}return Math.round(e/t)*t}var RangeTouch=function(){function e(t,n){_classCallCheck(this,e),is.element(t)?this.element=t:is.string(t)&&(this.element=document.querySelector(t)),is.element(this.element)&&is.empty(this.element.rangeTouch)&&(this.config=_objectSpread2({},defaults,{},n),this.init())}return _createClass(e,[{key:\"init\",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect=\"none\",this.element.style.webKitUserSelect=\"none\",this.element.style.touchAction=\"manipulation\"),this.listeners(!0),this.element.rangeTouch=this)}},{key:\"destroy\",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect=\"\",this.element.style.webKitUserSelect=\"\",this.element.style.touchAction=\"\"),this.listeners(!1),this.element.rangeTouch=null)}},{key:\"listeners\",value:function(e){var t=this,n=e?\"addEventListener\":\"removeEventListener\";[\"touchstart\",\"touchmove\",\"touchend\"].forEach((function(e){t.element[n](e,(function(e){return t.set(e)}),!1)}))}},{key:\"get\",value:function(t){if(!e.enabled||!is.event(t))return null;var n,r=t.target,i=t.changedTouches[0],o=parseFloat(r.getAttribute(\"min\"))||0,s=parseFloat(r.getAttribute(\"max\"))||100,u=parseFloat(r.getAttribute(\"step\"))||1,c=r.getBoundingClientRect(),a=100/c.width*(this.config.thumbWidth/2)/100;return 0>(n=100/c.width*(i.clientX-c.left))?n=0:100<n&&(n=100),50>n?n-=(100-2*n)*a:50<n&&(n+=2*(n-50)*a),o+round(n/100*(s-o),u)}},{key:\"set\",value:function(t){e.enabled&&is.event(t)&&!t.target.disabled&&(t.preventDefault(),t.target.value=this.get(t),trigger(t.target,\"touchend\"===t.type?\"change\":\"input\"))}}],[{key:\"setup\",value:function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r=null;if(is.empty(t)||is.string(t)?r=Array.from(document.querySelectorAll(is.string(t)?t:'input[type=\"range\"]')):is.element(t)?r=[t]:is.nodeList(t)?r=Array.from(t):is.array(t)&&(r=t.filter(is.element)),is.empty(r))return null;var i=_objectSpread2({},defaults,{},n);if(is.string(t)&&i.watch){var o=new MutationObserver((function(n){Array.from(n).forEach((function(n){Array.from(n.addedNodes).forEach((function(n){is.element(n)&&matches(n,t)&&new e(n,i)}))}))}));o.observe(document.body,{childList:!0,subtree:!0})}return r.map((function(t){return new e(t,n)}))}},{key:\"enabled\",get:function(){return\"ontouchstart\"in document.documentElement}}]),e}();export default RangeTouch;","(function(global) {\r\n /**\r\n * Polyfill URLSearchParams\r\n *\r\n * Inspired from : https://github.com/WebReflection/url-search-params/blob/master/src/url-search-params.js\r\n */\r\n\r\n var checkIfIteratorIsSupported = function() {\r\n try {\r\n return !!Symbol.iterator;\r\n } catch (error) {\r\n return false;\r\n }\r\n };\r\n\r\n\r\n var iteratorSupported = checkIfIteratorIsSupported();\r\n\r\n var createIterator = function(items) {\r\n var iterator = {\r\n next: function() {\r\n var value = items.shift();\r\n return { done: value === void 0, value: value };\r\n }\r\n };\r\n\r\n if (iteratorSupported) {\r\n iterator[Symbol.iterator] = function() {\r\n return iterator;\r\n };\r\n }\r\n\r\n return iterator;\r\n };\r\n\r\n /**\r\n * Search param name and values should be encoded according to https://url.spec.whatwg.org/#urlencoded-serializing\r\n * encodeURIComponent() produces the same result except encoding spaces as `%20` instead of `+`.\r\n */\r\n var serializeParam = function(value) {\r\n return encodeURIComponent(value).replace(/%20/g, '+');\r\n };\r\n\r\n var deserializeParam = function(value) {\r\n return decodeURIComponent(String(value).replace(/\\+/g, ' '));\r\n };\r\n\r\n var polyfillURLSearchParams = function() {\r\n\r\n var URLSearchParams = function(searchString) {\r\n Object.defineProperty(this, '_entries', { writable: true, value: {} });\r\n var typeofSearchString = typeof searchString;\r\n\r\n if (typeofSearchString === 'undefined') {\r\n // do nothing\r\n } else if (typeofSearchString === 'string') {\r\n if (searchString !== '') {\r\n this._fromString(searchString);\r\n }\r\n } else if (searchString instanceof URLSearchParams) {\r\n var _this = this;\r\n searchString.forEach(function(value, name) {\r\n _this.append(name, value);\r\n });\r\n } else if ((searchString !== null) && (typeofSearchString === 'object')) {\r\n if (Object.prototype.toString.call(searchString) === '[object Array]') {\r\n for (var i = 0; i < searchString.length; i++) {\r\n var entry = searchString[i];\r\n if ((Object.prototype.toString.call(entry) === '[object Array]') || (entry.length !== 2)) {\r\n this.append(entry[0], entry[1]);\r\n } else {\r\n throw new TypeError('Expected [string, any] as entry at index ' + i + ' of URLSearchParams\\'s input');\r\n }\r\n }\r\n } else {\r\n for (var key in searchString) {\r\n if (searchString.hasOwnProperty(key)) {\r\n this.append(key, searchString[key]);\r\n }\r\n }\r\n }\r\n } else {\r\n throw new TypeError('Unsupported input\\'s type for URLSearchParams');\r\n }\r\n };\r\n\r\n var proto = URLSearchParams.prototype;\r\n\r\n proto.append = function(name, value) {\r\n if (name in this._entries) {\r\n this._entries[name].push(String(value));\r\n } else {\r\n this._entries[name] = [String(value)];\r\n }\r\n };\r\n\r\n proto.delete = function(name) {\r\n delete this._entries[name];\r\n };\r\n\r\n proto.get = function(name) {\r\n return (name in this._entries) ? this._entries[name][0] : null;\r\n };\r\n\r\n proto.getAll = function(name) {\r\n return (name in this._entries) ? this._entries[name].slice(0) : [];\r\n };\r\n\r\n proto.has = function(name) {\r\n return (name in this._entries);\r\n };\r\n\r\n proto.set = function(name, value) {\r\n this._entries[name] = [String(value)];\r\n };\r\n\r\n proto.forEach = function(callback, thisArg) {\r\n var entries;\r\n for (var name in this._entries) {\r\n if (this._entries.hasOwnProperty(name)) {\r\n entries = this._entries[name];\r\n for (var i = 0; i < entries.length; i++) {\r\n callback.call(thisArg, entries[i], name, this);\r\n }\r\n }\r\n }\r\n };\r\n\r\n proto.keys = function() {\r\n var items = [];\r\n this.forEach(function(value, name) {\r\n items.push(name);\r\n });\r\n return createIterator(items);\r\n };\r\n\r\n proto.values = function() {\r\n var items = [];\r\n this.forEach(function(value) {\r\n items.push(value);\r\n });\r\n return createIterator(items);\r\n };\r\n\r\n proto.entries = function() {\r\n var items = [];\r\n this.forEach(function(value, name) {\r\n items.push([name, value]);\r\n });\r\n return createIterator(items);\r\n };\r\n\r\n if (iteratorSupported) {\r\n proto[Symbol.iterator] = proto.entries;\r\n }\r\n\r\n proto.toString = function() {\r\n var searchArray = [];\r\n this.forEach(function(value, name) {\r\n searchArray.push(serializeParam(name) + '=' + serializeParam(value));\r\n });\r\n return searchArray.join('&');\r\n };\r\n\r\n\r\n global.URLSearchParams = URLSearchParams;\r\n };\r\n\r\n var checkIfURLSearchParamsSupported = function() {\r\n try {\r\n var URLSearchParams = global.URLSearchParams;\r\n\r\n return (\r\n (new URLSearchParams('?a=1').toString() === 'a=1') &&\r\n (typeof URLSearchParams.prototype.set === 'function') &&\r\n (typeof URLSearchParams.prototype.entries === 'function')\r\n );\r\n } catch (e) {\r\n return false;\r\n }\r\n };\r\n\r\n if (!checkIfURLSearchParamsSupported()) {\r\n polyfillURLSearchParams();\r\n }\r\n\r\n var proto = global.URLSearchParams.prototype;\r\n\r\n if (typeof proto.sort !== 'function') {\r\n proto.sort = function() {\r\n var _this = this;\r\n var items = [];\r\n this.forEach(function(value, name) {\r\n items.push([name, value]);\r\n if (!_this._entries) {\r\n _this.delete(name);\r\n }\r\n });\r\n items.sort(function(a, b) {\r\n if (a[0] < b[0]) {\r\n return -1;\r\n } else if (a[0] > b[0]) {\r\n return +1;\r\n } else {\r\n return 0;\r\n }\r\n });\r\n if (_this._entries) { // force reset because IE keeps keys index\r\n _this._entries = {};\r\n }\r\n for (var i = 0; i < items.length; i++) {\r\n this.append(items[i][0], items[i][1]);\r\n }\r\n };\r\n }\r\n\r\n if (typeof proto._fromString !== 'function') {\r\n Object.defineProperty(proto, '_fromString', {\r\n enumerable: false,\r\n configurable: false,\r\n writable: false,\r\n value: function(searchString) {\r\n if (this._entries) {\r\n this._entries = {};\r\n } else {\r\n var keys = [];\r\n this.forEach(function(value, name) {\r\n keys.push(name);\r\n });\r\n for (var i = 0; i < keys.length; i++) {\r\n this.delete(keys[i]);\r\n }\r\n }\r\n\r\n searchString = searchString.replace(/^\\?/, '');\r\n var attributes = searchString.split('&');\r\n var attribute;\r\n for (var i = 0; i < attributes.length; i++) {\r\n attribute = attributes[i].split('=');\r\n this.append(\r\n deserializeParam(attribute[0]),\r\n (attribute.length > 1) ? deserializeParam(attribute[1]) : ''\r\n );\r\n }\r\n }\r\n });\r\n }\r\n\r\n // HTMLAnchorElement\r\n\r\n})(\r\n (typeof global !== 'undefined') ? global\r\n : ((typeof window !== 'undefined') ? window\r\n : ((typeof self !== 'undefined') ? self : this))\r\n);\r\n\r\n(function(global) {\r\n /**\r\n * Polyfill URL\r\n *\r\n * Inspired from : https://github.com/arv/DOM-URL-Polyfill/blob/master/src/url.js\r\n */\r\n\r\n var checkIfURLIsSupported = function() {\r\n try {\r\n var u = new global.URL('b', 'http://a');\r\n u.pathname = 'c d';\r\n return (u.href === 'http://a/c%20d') && u.searchParams;\r\n } catch (e) {\r\n return false;\r\n }\r\n };\r\n\r\n\r\n var polyfillURL = function() {\r\n var _URL = global.URL;\r\n\r\n var URL = function(url, base) {\r\n if (typeof url !== 'string') url = String(url);\r\n if (base && typeof base !== 'string') base = String(base);\r\n\r\n // Only create another document if the base is different from current location.\r\n var doc = document, baseElement;\r\n if (base && (global.location === void 0 || base !== global.location.href)) {\r\n base = base.toLowerCase();\r\n doc = document.implementation.createHTMLDocument('');\r\n baseElement = doc.createElement('base');\r\n baseElement.href = base;\r\n doc.head.appendChild(baseElement);\r\n try {\r\n if (baseElement.href.indexOf(base) !== 0) throw new Error(baseElement.href);\r\n } catch (err) {\r\n throw new Error('URL unable to set base ' + base + ' due to ' + err);\r\n }\r\n }\r\n\r\n var anchorElement = doc.createElement('a');\r\n anchorElement.href = url;\r\n if (baseElement) {\r\n doc.body.appendChild(anchorElement);\r\n anchorElement.href = anchorElement.href; // force href to refresh\r\n }\r\n\r\n var inputElement = doc.createElement('input');\r\n inputElement.type = 'url';\r\n inputElement.value = url;\r\n\r\n if (anchorElement.protocol === ':' || !/:/.test(anchorElement.href) || (!inputElement.checkValidity() && !base)) {\r\n throw new TypeError('Invalid URL');\r\n }\r\n\r\n Object.defineProperty(this, '_anchorElement', {\r\n value: anchorElement\r\n });\r\n\r\n\r\n // create a linked searchParams which reflect its changes on URL\r\n var searchParams = new global.URLSearchParams(this.search);\r\n var enableSearchUpdate = true;\r\n var enableSearchParamsUpdate = true;\r\n var _this = this;\r\n ['append', 'delete', 'set'].forEach(function(methodName) {\r\n var method = searchParams[methodName];\r\n searchParams[methodName] = function() {\r\n method.apply(searchParams, arguments);\r\n if (enableSearchUpdate) {\r\n enableSearchParamsUpdate = false;\r\n _this.search = searchParams.toString();\r\n enableSearchParamsUpdate = true;\r\n }\r\n };\r\n });\r\n\r\n Object.defineProperty(this, 'searchParams', {\r\n value: searchParams,\r\n enumerable: true\r\n });\r\n\r\n var search = void 0;\r\n Object.defineProperty(this, '_updateSearchParams', {\r\n enumerable: false,\r\n configurable: false,\r\n writable: false,\r\n value: function() {\r\n if (this.search !== search) {\r\n search = this.search;\r\n if (enableSearchParamsUpdate) {\r\n enableSearchUpdate = false;\r\n this.searchParams._fromString(this.search);\r\n enableSearchUpdate = true;\r\n }\r\n }\r\n }\r\n });\r\n };\r\n\r\n var proto = URL.prototype;\r\n\r\n var linkURLWithAnchorAttribute = function(attributeName) {\r\n Object.defineProperty(proto, attributeName, {\r\n get: function() {\r\n return this._anchorElement[attributeName];\r\n },\r\n set: function(value) {\r\n this._anchorElement[attributeName] = value;\r\n },\r\n enumerable: true\r\n });\r\n };\r\n\r\n ['hash', 'host', 'hostname', 'port', 'protocol']\r\n .forEach(function(attributeName) {\r\n linkURLWithAnchorAttribute(attributeName);\r\n });\r\n\r\n Object.defineProperty(proto, 'search', {\r\n get: function() {\r\n return this._anchorElement['search'];\r\n },\r\n set: function(value) {\r\n this._anchorElement['search'] = value;\r\n this._updateSearchParams();\r\n },\r\n enumerable: true\r\n });\r\n\r\n Object.defineProperties(proto, {\r\n\r\n 'toString': {\r\n get: function() {\r\n var _this = this;\r\n return function() {\r\n return _this.href;\r\n };\r\n }\r\n },\r\n\r\n 'href': {\r\n get: function() {\r\n return this._anchorElement.href.replace(/\\?$/, '');\r\n },\r\n set: function(value) {\r\n this._anchorElement.href = value;\r\n this._updateSearchParams();\r\n },\r\n enumerable: true\r\n },\r\n\r\n 'pathname': {\r\n get: function() {\r\n return this._anchorElement.pathname.replace(/(^\\/?)/, '/');\r\n },\r\n set: function(value) {\r\n this._anchorElement.pathname = value;\r\n },\r\n enumerable: true\r\n },\r\n\r\n 'origin': {\r\n get: function() {\r\n // get expected port from protocol\r\n var expectedPort = { 'http:': 80, 'https:': 443, 'ftp:': 21 }[this._anchorElement.protocol];\r\n // add port to origin if, expected port is different than actual port\r\n // and it is not empty f.e http://foo:8080\r\n // 8080 != 80 && 8080 != ''\r\n var addPortToOrigin = this._anchorElement.port != expectedPort &&\r\n this._anchorElement.port !== '';\r\n\r\n return this._anchorElement.protocol +\r\n '//' +\r\n this._anchorElement.hostname +\r\n (addPortToOrigin ? (':' + this._anchorElement.port) : '');\r\n },\r\n enumerable: true\r\n },\r\n\r\n 'password': { // TODO\r\n get: function() {\r\n return '';\r\n },\r\n set: function(value) {\r\n },\r\n enumerable: true\r\n },\r\n\r\n 'username': { // TODO\r\n get: function() {\r\n return '';\r\n },\r\n set: function(value) {\r\n },\r\n enumerable: true\r\n },\r\n });\r\n\r\n URL.createObjectURL = function(blob) {\r\n return _URL.createObjectURL.apply(_URL, arguments);\r\n };\r\n\r\n URL.revokeObjectURL = function(url) {\r\n return _URL.revokeObjectURL.apply(_URL, arguments);\r\n };\r\n\r\n global.URL = URL;\r\n\r\n };\r\n\r\n if (!checkIfURLIsSupported()) {\r\n polyfillURL();\r\n }\r\n\r\n if ((global.location !== void 0) && !('origin' in global.location)) {\r\n var getOrigin = function() {\r\n return global.location.protocol + '//' + global.location.hostname + (global.location.port ? (':' + global.location.port) : '');\r\n };\r\n\r\n try {\r\n Object.defineProperty(global.location, 'origin', {\r\n get: getOrigin,\r\n enumerable: true\r\n });\r\n } catch (e) {\r\n setInterval(function() {\r\n global.location.origin = getOrigin();\r\n }, 100);\r\n }\r\n }\r\n\r\n})(\r\n (typeof global !== 'undefined') ? global\r\n : ((typeof window !== 'undefined') ? window\r\n : ((typeof self !== 'undefined') ? self : this))\r\n);\r\n","// ==========================================================================\n// Type checking utils\n// ==========================================================================\n\nconst getConstructor = (input) => (input !== null && typeof input !== 'undefined' ? input.constructor : null);\nconst instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor);\nconst isNullOrUndefined = (input) => input === null || typeof input === 'undefined';\nconst isObject = (input) => getConstructor(input) === Object;\nconst isNumber = (input) => getConstructor(input) === Number && !Number.isNaN(input);\nconst isString = (input) => getConstructor(input) === String;\nconst isBoolean = (input) => getConstructor(input) === Boolean;\nconst isFunction = (input) => getConstructor(input) === Function;\nconst isArray = (input) => Array.isArray(input);\nconst isWeakMap = (input) => instanceOf(input, WeakMap);\nconst isNodeList = (input) => instanceOf(input, NodeList);\nconst isTextNode = (input) => getConstructor(input) === Text;\nconst isEvent = (input) => instanceOf(input, Event);\nconst isKeyboardEvent = (input) => instanceOf(input, KeyboardEvent);\nconst isCue = (input) => instanceOf(input, window.TextTrackCue) || instanceOf(input, window.VTTCue);\nconst isTrack = (input) => instanceOf(input, TextTrack) || (!isNullOrUndefined(input) && isString(input.kind));\nconst isPromise = (input) => instanceOf(input, Promise) && isFunction(input.then);\n\nconst isElement = (input) =>\n input !== null &&\n typeof input === 'object' &&\n input.nodeType === 1 &&\n typeof input.style === 'object' &&\n typeof input.ownerDocument === 'object';\n\nconst isEmpty = (input) =>\n isNullOrUndefined(input) ||\n ((isString(input) || isArray(input) || isNodeList(input)) && !input.length) ||\n (isObject(input) && !Object.keys(input).length);\n\nconst isUrl = (input) => {\n // Accept a URL object\n if (instanceOf(input, window.URL)) {\n return true;\n }\n\n // Must be string from here\n if (!isString(input)) {\n return false;\n }\n\n // Add the protocol if required\n let string = input;\n if (!input.startsWith('http://') || !input.startsWith('https://')) {\n string = `http://${input}`;\n }\n\n try {\n return !isEmpty(new URL(string).hostname);\n } catch (_) {\n return false;\n }\n};\n\nexport default {\n nullOrUndefined: isNullOrUndefined,\n object: isObject,\n number: isNumber,\n string: isString,\n boolean: isBoolean,\n function: isFunction,\n array: isArray,\n weakMap: isWeakMap,\n nodeList: isNodeList,\n element: isElement,\n textNode: isTextNode,\n event: isEvent,\n keyboardEvent: isKeyboardEvent,\n cue: isCue,\n track: isTrack,\n promise: isPromise,\n url: isUrl,\n empty: isEmpty,\n};\n","// ==========================================================================\n// Animation utils\n// ==========================================================================\n\nimport is from './is';\n\nexport const transitionEndEvent = (() => {\n const element = document.createElement('span');\n\n const events = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend',\n };\n\n const type = Object.keys(events).find((event) => element.style[event] !== undefined);\n\n return is.string(type) ? events[type] : false;\n})();\n\n// Force repaint of element\nexport function repaint(element, delay) {\n setTimeout(() => {\n try {\n // eslint-disable-next-line no-param-reassign\n element.hidden = true;\n\n // eslint-disable-next-line no-unused-expressions\n element.offsetHeight;\n\n // eslint-disable-next-line no-param-reassign\n element.hidden = false;\n } catch (_) {\n // Do nothing\n }\n }, delay);\n}\n","// ==========================================================================\n// Browser sniffing\n// Unfortunately, due to mixed support, UA sniffing is required\n// ==========================================================================\n\nconst browser = {\n isIE: Boolean(window.document.documentMode),\n isEdge: window.navigator.userAgent.includes('Edge'),\n isWebkit: 'WebkitAppearance' in document.documentElement.style && !/Edge/.test(navigator.userAgent),\n isIPhone: /(iPhone|iPod)/gi.test(navigator.platform),\n isIos:\n (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) ||\n /(iPad|iPhone|iPod)/gi.test(navigator.platform),\n};\n\nexport default browser;\n","// ==========================================================================\n// Object utils\n// ==========================================================================\n\nimport is from './is';\n\n// Clone nested objects\nexport function cloneDeep(object) {\n return JSON.parse(JSON.stringify(object));\n}\n\n// Get a nested value in an object\nexport function getDeep(object, path) {\n return path.split('.').reduce((obj, key) => obj && obj[key], object);\n}\n\n// Deep extend destination object with N more objects\nexport function extend(target = {}, ...sources) {\n if (!sources.length) {\n return target;\n }\n\n const source = sources.shift();\n\n if (!is.object(source)) {\n return target;\n }\n\n Object.keys(source).forEach((key) => {\n if (is.object(source[key])) {\n if (!Object.keys(target).includes(key)) {\n Object.assign(target, { [key]: {} });\n }\n\n extend(target[key], source[key]);\n } else {\n Object.assign(target, { [key]: source[key] });\n }\n });\n\n return extend(target, ...sources);\n}\n","// ==========================================================================\n// Element utils\n// ==========================================================================\n\nimport is from './is';\nimport { extend } from './objects';\n\n// Wrap an element\nexport function wrap(elements, wrapper) {\n // Convert `elements` to an array, if necessary.\n const targets = elements.length ? elements : [elements];\n\n // Loops backwards to prevent having to clone the wrapper on the\n // first element (see `child` below).\n Array.from(targets)\n .reverse()\n .forEach((element, index) => {\n const child = index > 0 ? wrapper.cloneNode(true) : wrapper;\n // Cache the current parent and sibling.\n const parent = element.parentNode;\n const sibling = element.nextSibling;\n\n // Wrap the element (is automatically removed from its current\n // parent).\n child.appendChild(element);\n\n // If the element had a sibling, insert the wrapper before\n // the sibling to maintain the HTML structure; otherwise, just\n // append it to the parent.\n if (sibling) {\n parent.insertBefore(child, sibling);\n } else {\n parent.appendChild(child);\n }\n });\n}\n\n// Set attributes\nexport function setAttributes(element, attributes) {\n if (!is.element(element) || is.empty(attributes)) {\n return;\n }\n\n // Assume null and undefined attributes should be left out,\n // Setting them would otherwise convert them to \"null\" and \"undefined\"\n Object.entries(attributes)\n .filter(([, value]) => !is.nullOrUndefined(value))\n .forEach(([key, value]) => element.setAttribute(key, value));\n}\n\n// Create a DocumentFragment\nexport function createElement(type, attributes, text) {\n // Create a new <element>\n const element = document.createElement(type);\n\n // Set all passed attributes\n if (is.object(attributes)) {\n setAttributes(element, attributes);\n }\n\n // Add text node\n if (is.string(text)) {\n element.innerText = text;\n }\n\n // Return built element\n return element;\n}\n\n// Inaert an element after another\nexport function insertAfter(element, target) {\n if (!is.element(element) || !is.element(target)) {\n return;\n }\n\n target.parentNode.insertBefore(element, target.nextSibling);\n}\n\n// Insert a DocumentFragment\nexport function insertElement(type, parent, attributes, text) {\n if (!is.element(parent)) {\n return;\n }\n\n parent.appendChild(createElement(type, attributes, text));\n}\n\n// Remove element(s)\nexport function removeElement(element) {\n if (is.nodeList(element) || is.array(element)) {\n Array.from(element).forEach(removeElement);\n return;\n }\n\n if (!is.element(element) || !is.element(element.parentNode)) {\n return;\n }\n\n element.parentNode.removeChild(element);\n}\n\n// Remove all child elements\nexport function emptyElement(element) {\n if (!is.element(element)) {\n return;\n }\n\n let { length } = element.childNodes;\n\n while (length > 0) {\n element.removeChild(element.lastChild);\n length -= 1;\n }\n}\n\n// Replace element\nexport function replaceElement(newChild, oldChild) {\n if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) {\n return null;\n }\n\n oldChild.parentNode.replaceChild(newChild, oldChild);\n\n return newChild;\n}\n\n// Get an attribute object from a string selector\nexport function getAttributesFromSelector(sel, existingAttributes) {\n // For example:\n // '.test' to { class: 'test' }\n // '#test' to { id: 'test' }\n // '[data-test=\"test\"]' to { 'data-test': 'test' }\n\n if (!is.string(sel) || is.empty(sel)) {\n return {};\n }\n\n const attributes = {};\n const existing = extend({}, existingAttributes);\n\n sel.split(',').forEach((s) => {\n // Remove whitespace\n const selector = s.trim();\n const className = selector.replace('.', '');\n const stripped = selector.replace(/[[\\]]/g, '');\n // Get the parts and value\n const parts = stripped.split('=');\n const [key] = parts;\n const value = parts.length > 1 ? parts[1].replace(/[\"']/g, '') : '';\n // Get the first character\n const start = selector.charAt(0);\n\n switch (start) {\n case '.':\n // Add to existing classname\n if (is.string(existing.class)) {\n attributes.class = `${existing.class} ${className}`;\n } else {\n attributes.class = className;\n }\n break;\n\n case '#':\n // ID selector\n attributes.id = selector.replace('#', '');\n break;\n\n case '[':\n // Attribute selector\n attributes[key] = value;\n\n break;\n\n default:\n break;\n }\n });\n\n return extend(existing, attributes);\n}\n\n// Toggle hidden\nexport function toggleHidden(element, hidden) {\n if (!is.element(element)) {\n return;\n }\n\n let hide = hidden;\n\n if (!is.boolean(hide)) {\n hide = !element.hidden;\n }\n\n // eslint-disable-next-line no-param-reassign\n element.hidden = hide;\n}\n\n// Mirror Element.classList.toggle, with IE compatibility for \"force\" argument\nexport function toggleClass(element, className, force) {\n if (is.nodeList(element)) {\n return Array.from(element).map((e) => toggleClass(e, className, force));\n }\n\n if (is.element(element)) {\n let method = 'toggle';\n if (typeof force !== 'undefined') {\n method = force ? 'add' : 'remove';\n }\n\n element.classList[method](className);\n return element.classList.contains(className);\n }\n\n return false;\n}\n\n// Has class name\nexport function hasClass(element, className) {\n return is.element(element) && element.classList.contains(className);\n}\n\n// Element matches selector\nexport function matches(element, selector) {\n const { prototype } = Element;\n\n function match() {\n return Array.from(document.querySelectorAll(selector)).includes(this);\n }\n\n const method =\n prototype.matches ||\n prototype.webkitMatchesSelector ||\n prototype.mozMatchesSelector ||\n prototype.msMatchesSelector ||\n match;\n\n return method.call(element, selector);\n}\n\n// Closest ancestor element matching selector (also tests element itself)\nexport function closest(element, selector) {\n const { prototype } = Element;\n\n // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill\n function closestElement() {\n let el = this;\n\n do {\n if (matches.matches(el, selector)) return el;\n el = el.parentElement || el.parentNode;\n } while (el !== null && el.nodeType === 1);\n return null;\n }\n\n const method = prototype.closest || closestElement;\n\n return method.call(element, selector);\n}\n\n// Find all elements\nexport function getElements(selector) {\n return this.elements.container.querySelectorAll(selector);\n}\n\n// Find a single element\nexport function getElement(selector) {\n return this.elements.container.querySelector(selector);\n}\n\n// Set focus and tab focus class\nexport function setFocus(element = null, tabFocus = false) {\n if (!is.element(element)) {\n return;\n }\n\n // Set regular focus\n element.focus({ preventScroll: true });\n\n // If we want to mimic keyboard focus via tab\n if (tabFocus) {\n toggleClass(element, this.config.classNames.tabFocus);\n }\n}\n","// ==========================================================================\n// Plyr support checks\n// ==========================================================================\n\nimport { transitionEndEvent } from './utils/animation';\nimport browser from './utils/browser';\nimport { createElement } from './utils/elements';\nimport is from './utils/is';\n\n// Default codecs for checking mimetype support\nconst defaultCodecs = {\n 'audio/ogg': 'vorbis',\n 'audio/wav': '1',\n 'video/webm': 'vp8, vorbis',\n 'video/mp4': 'avc1.42E01E, mp4a.40.2',\n 'video/ogg': 'theora',\n};\n\n// Check for feature support\nconst support = {\n // Basic support\n audio: 'canPlayType' in document.createElement('audio'),\n video: 'canPlayType' in document.createElement('video'),\n\n // Check for support\n // Basic functionality vs full UI\n check(type, provider, playsinline) {\n const canPlayInline = browser.isIPhone && playsinline && support.playsinline;\n const api = support[type] || provider !== 'html5';\n const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline);\n\n return {\n api,\n ui,\n };\n },\n\n // Picture-in-picture support\n // Safari & Chrome only currently\n pip: (() => {\n if (browser.isIPhone) {\n return false;\n }\n\n // Safari\n // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls\n if (is.function(createElement('video').webkitSetPresentationMode)) {\n return true;\n }\n\n // Chrome\n // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture\n if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) {\n return true;\n }\n\n return false;\n })(),\n\n // Airplay support\n // Safari only currently\n airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent),\n\n // Inline playback support\n // https://webkit.org/blog/6784/new-video-policies-for-ios/\n playsinline: 'playsInline' in document.createElement('video'),\n\n // Check for mime type support against a player instance\n // Credits: http://diveintohtml5.info/everything.html\n // Related: http://www.leanbackplayer.com/test/h5mt.html\n mime(input) {\n if (is.empty(input)) {\n return false;\n }\n\n const [mediaType] = input.split('/');\n let type = input;\n\n // Verify we're using HTML5 and there's no media type mismatch\n if (!this.isHTML5 || mediaType !== this.type) {\n return false;\n }\n\n // Add codec if required\n if (Object.keys(defaultCodecs).includes(type)) {\n type += `; codecs=\"${defaultCodecs[input]}\"`;\n }\n\n try {\n return Boolean(type && this.media.canPlayType(type).replace(/no/, ''));\n } catch (_) {\n return false;\n }\n },\n\n // Check for textTracks support\n textTracks: 'textTracks' in document.createElement('video'),\n\n // <input type=\"range\"> Sliders\n rangeInput: (() => {\n const range = document.createElement('input');\n range.type = 'range';\n return range.type === 'range';\n })(),\n\n // Touch\n // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event\n touch: 'ontouchstart' in document.documentElement,\n\n // Detect transitions support\n transitions: transitionEndEvent !== false,\n\n // Reduced motion iOS & MacOS setting\n // https://webkit.org/blog/7551/responsive-design-for-motion/\n reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches,\n};\n\nexport default support;\n","// ==========================================================================\n// Event utils\n// ==========================================================================\n\nimport is from './is';\n\n// Check for passive event listener support\n// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md\n// https://www.youtube.com/watch?v=NPM6172J22g\nconst supportsPassiveListeners = (() => {\n // Test via a getter in the options object to see if the passive property is accessed\n let supported = false;\n try {\n const options = Object.defineProperty({}, 'passive', {\n get() {\n supported = true;\n return null;\n },\n });\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n } catch (_) {\n // Do nothing\n }\n\n return supported;\n})();\n\n// Toggle event listener\nexport function toggleListener(element, event, callback, toggle = false, passive = true, capture = false) {\n // Bail if no element, event, or callback\n if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) {\n return;\n }\n\n // Allow multiple events\n const events = event.split(' ');\n // Build options\n // Default to just the capture boolean for browsers with no passive listener support\n let options = capture;\n\n // If passive events listeners are supported\n if (supportsPassiveListeners) {\n options = {\n // Whether the listener can be passive (i.e. default never prevented)\n passive,\n // Whether the listener is a capturing listener or not\n capture,\n };\n }\n\n // If a single node is passed, bind the event listener\n events.forEach((type) => {\n if (this && this.eventListeners && toggle) {\n // Cache event listener\n this.eventListeners.push({ element, type, callback, options });\n }\n\n element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options);\n });\n}\n\n// Bind event handler\nexport function on(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, true, passive, capture);\n}\n\n// Unbind event handler\nexport function off(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, false, passive, capture);\n}\n\n// Bind once-only event handler\nexport function once(element, events = '', callback, passive = true, capture = false) {\n const onceCallback = (...args) => {\n off(element, events, onceCallback, passive, capture);\n callback.apply(this, args);\n };\n\n toggleListener.call(this, element, events, onceCallback, true, passive, capture);\n}\n\n// Trigger event\nexport function triggerEvent(element, type = '', bubbles = false, detail = {}) {\n // Bail if no element\n if (!is.element(element) || is.empty(type)) {\n return;\n }\n\n // Create and dispatch the event\n const event = new CustomEvent(type, {\n bubbles,\n detail: { ...detail, plyr: this },\n });\n\n // Dispatch the event\n element.dispatchEvent(event);\n}\n\n// Unbind all cached event listeners\nexport function unbindListeners() {\n if (this && this.eventListeners) {\n this.eventListeners.forEach((item) => {\n const { element, type, callback, options } = item;\n element.removeEventListener(type, callback, options);\n });\n\n this.eventListeners = [];\n }\n}\n\n// Run method when / if player is ready\nexport function ready() {\n return new Promise((resolve) =>\n this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve),\n ).then(() => {});\n}\n","import is from './is';\n/**\n * Silence a Promise-like object.\n * This is useful for avoiding non-harmful, but potentially confusing \"uncaught\n * play promise\" rejection error messages.\n * @param {Object} value An object that may or may not be `Promise`-like.\n */\nexport function silencePromise(value) {\n if (is.promise(value)) {\n value.then(null, () => {});\n }\n}\n\nexport default { silencePromise };\n","// ==========================================================================\n// Array utils\n// ==========================================================================\n\nimport is from './is';\n\n// Remove duplicates in an array\nexport function dedupe(array) {\n if (!is.array(array)) {\n return array;\n }\n\n return array.filter((item, index) => array.indexOf(item) === index);\n}\n\n// Get the closest value in an array\nexport function closest(array, value) {\n if (!is.array(array) || !array.length) {\n return null;\n }\n\n return array.reduce((prev, curr) => (Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev));\n}\n","// ==========================================================================\n// Style utils\n// ==========================================================================\n\nimport { closest } from './arrays';\nimport is from './is';\n\n// Check support for a CSS declaration\nexport function supportsCSS(declaration) {\n if (!window || !window.CSS) {\n return false;\n }\n\n return window.CSS.supports(declaration);\n}\n\n// Standard/common aspect ratios\nconst standardRatios = [\n [1, 1],\n [4, 3],\n [3, 4],\n [5, 4],\n [4, 5],\n [3, 2],\n [2, 3],\n [16, 10],\n [10, 16],\n [16, 9],\n [9, 16],\n [21, 9],\n [9, 21],\n [32, 9],\n [9, 32],\n].reduce((out, [x, y]) => ({ ...out, [x / y]: [x, y] }), {});\n\n// Validate an aspect ratio\nexport function validateAspectRatio(input) {\n if (!is.array(input) && (!is.string(input) || !input.includes(':'))) {\n return false;\n }\n\n const ratio = is.array(input) ? input : input.split(':');\n\n return ratio.map(Number).every(is.number);\n}\n\n// Reduce an aspect ratio to it's lowest form\nexport function reduceAspectRatio(ratio) {\n if (!is.array(ratio) || !ratio.every(is.number)) {\n return null;\n }\n\n const [width, height] = ratio;\n const getDivider = (w, h) => (h === 0 ? w : getDivider(h, w % h));\n const divider = getDivider(width, height);\n\n return [width / divider, height / divider];\n}\n\n// Calculate an aspect ratio\nexport function getAspectRatio(input) {\n const parse = (ratio) => (validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null);\n // Try provided ratio\n let ratio = parse(input);\n\n // Get from config\n if (ratio === null) {\n ratio = parse(this.config.ratio);\n }\n\n // Get from embed\n if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) {\n ({ ratio } = this.embed);\n }\n\n // Get from HTML5 video\n if (ratio === null && this.isHTML5) {\n const { videoWidth, videoHeight } = this.media;\n ratio = [videoWidth, videoHeight];\n }\n\n return reduceAspectRatio(ratio);\n}\n\n// Set aspect ratio for responsive container\nexport function setAspectRatio(input) {\n if (!this.isVideo) {\n return {};\n }\n\n const { wrapper } = this.elements;\n const ratio = getAspectRatio.call(this, input);\n\n if (!is.array(ratio)) {\n return {};\n }\n\n const [x, y] = reduceAspectRatio(ratio);\n const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`);\n const padding = (100 / x) * y;\n\n if (useNative) {\n wrapper.style.aspectRatio = `${x}/${y}`;\n } else {\n wrapper.style.paddingBottom = `${padding}%`;\n }\n\n // For Vimeo we have an extra <div> to hide the standard controls and UI\n if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) {\n const height = (100 / this.media.offsetWidth) * parseInt(window.getComputedStyle(this.media).paddingBottom, 10);\n const offset = (height - padding) / (height / 50);\n\n if (this.fullscreen.active) {\n wrapper.style.paddingBottom = null;\n } else {\n this.media.style.transform = `translateY(-${offset}%)`;\n }\n } else if (this.isHTML5) {\n wrapper.classList.add(this.config.classNames.videoFixedRatio);\n }\n\n return { padding, ratio };\n}\n\n// Round an aspect ratio to closest standard ratio\nexport function roundAspectRatio(x, y, tolerance = 0.05) {\n const ratio = x / y;\n const closestRatio = closest(Object.keys(standardRatios), ratio);\n\n // Check match is within tolerance\n if (Math.abs(closestRatio - ratio) <= tolerance) {\n return standardRatios[closestRatio];\n }\n\n // No match\n return [x, y];\n}\n\n// Get the size of the viewport\n// https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions\nexport function getViewportSize() {\n const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);\n const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);\n return [width, height];\n}\n","// ==========================================================================\n// Plyr HTML5 helpers\n// ==========================================================================\n\nimport support from './support';\nimport { removeElement } from './utils/elements';\nimport { triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\nimport { setAspectRatio } from './utils/style';\n\nconst html5 = {\n getSources() {\n if (!this.isHTML5) {\n return [];\n }\n\n const sources = Array.from(this.media.querySelectorAll('source'));\n\n // Filter out unsupported sources (if type is specified)\n return sources.filter((source) => {\n const type = source.getAttribute('type');\n\n if (is.empty(type)) {\n return true;\n }\n\n return support.mime.call(this, type);\n });\n },\n\n // Get quality levels\n getQualityOptions() {\n // Whether we're forcing all options (e.g. for streaming)\n if (this.config.quality.forced) {\n return this.config.quality.options;\n }\n\n // Get sizes from <source> elements\n return html5.getSources\n .call(this)\n .map((source) => Number(source.getAttribute('data-res')))\n .filter(Boolean);\n },\n\n setup() {\n if (!this.isHTML5) {\n return;\n }\n\n const player = this;\n\n // Set speed options from config\n player.options.speed = player.config.speed.options;\n\n // Set aspect ratio if fixed\n if (!is.empty(this.config.ratio)) {\n setAspectRatio.call(player);\n }\n\n // Quality\n Object.defineProperty(player.media, 'quality', {\n get() {\n // Get sources\n const sources = html5.getSources.call(player);\n const source = sources.find((s) => s.getAttribute('src') === player.source);\n\n // Return size, if match is found\n return source && Number(source.getAttribute('data-res'));\n },\n set(input) {\n if (player.quality === input) {\n return;\n }\n\n // If we're using an external handler...\n if (player.config.quality.forced && is.function(player.config.quality.onChange)) {\n player.config.quality.onChange(input);\n } else {\n // Get sources\n const sources = html5.getSources.call(player);\n // Get first match for requested size\n const source = sources.find((s) => Number(s.getAttribute('data-res')) === input);\n\n // No matching source found\n if (!source) {\n return;\n }\n\n // Get current state\n const { currentTime, paused, preload, readyState, playbackRate } = player.media;\n\n // Set new source\n player.media.src = source.getAttribute('src');\n\n // Prevent loading if preload=\"none\" and the current source isn't loaded (#1044)\n if (preload !== 'none' || readyState) {\n // Restore time\n player.once('loadedmetadata', () => {\n player.speed = playbackRate;\n player.currentTime = currentTime;\n\n // Resume playing\n if (!paused) {\n silencePromise(player.play());\n }\n });\n\n // Load new source\n player.media.load();\n }\n }\n\n // Trigger change event\n triggerEvent.call(player, player.media, 'qualitychange', false, {\n quality: input,\n });\n },\n });\n },\n\n // Cancel current network requests\n // See https://github.com/sampotts/plyr/issues/174\n cancelRequests() {\n if (!this.isHTML5) {\n return;\n }\n\n // Remove child sources\n removeElement(html5.getSources.call(this));\n\n // Set blank video src attribute\n // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error\n // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection\n this.media.setAttribute('src', this.config.blankVideo);\n\n // Load the new empty source\n // This will cancel existing requests\n // See https://github.com/sampotts/plyr/issues/174\n this.media.load();\n\n // Debugging\n this.debug.log('Cancelled network requests');\n },\n};\n\nexport default html5;\n","// ==========================================================================\n// String utils\n// ==========================================================================\n\nimport is from './is';\n\n// Generate a random ID\nexport function generateId(prefix) {\n return `${prefix}-${Math.floor(Math.random() * 10000)}`;\n}\n\n// Format string\nexport function format(input, ...args) {\n if (is.empty(input)) {\n return input;\n }\n\n return input.toString().replace(/{(\\d+)}/g, (match, i) => args[i].toString());\n}\n\n// Get percentage\nexport function getPercentage(current, max) {\n if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) {\n return 0;\n }\n\n return ((current / max) * 100).toFixed(2);\n}\n\n// Replace all occurances of a string in a string\nexport const replaceAll = (input = '', find = '', replace = '') =>\n input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\\]/\\\\])/g, '\\\\$1'), 'g'), replace.toString());\n\n// Convert to title case\nexport const toTitleCase = (input = '') =>\n input.toString().replace(/\\w\\S*/g, (text) => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase());\n\n// Convert string to pascalCase\nexport function toPascalCase(input = '') {\n let string = input.toString();\n\n // Convert kebab case\n string = replaceAll(string, '-', ' ');\n\n // Convert snake case\n string = replaceAll(string, '_', ' ');\n\n // Convert to title case\n string = toTitleCase(string);\n\n // Convert to pascal case\n return replaceAll(string, ' ', '');\n}\n\n// Convert string to pascalCase\nexport function toCamelCase(input = '') {\n let string = input.toString();\n\n // Convert to pascal case\n string = toPascalCase(string);\n\n // Convert first character to lowercase\n return string.charAt(0).toLowerCase() + string.slice(1);\n}\n\n// Remove HTML from a string\nexport function stripHTML(source) {\n const fragment = document.createDocumentFragment();\n const element = document.createElement('div');\n fragment.appendChild(element);\n element.innerHTML = source;\n return fragment.firstChild.innerText;\n}\n\n// Like outerHTML, but also works for DocumentFragment\nexport function getHTML(element) {\n const wrapper = document.createElement('div');\n wrapper.appendChild(element);\n return wrapper.innerHTML;\n}\n","// ==========================================================================\n// Plyr internationalization\n// ==========================================================================\n\nimport is from './is';\nimport { getDeep } from './objects';\nimport { replaceAll } from './strings';\n\n// Skip i18n for abbreviations and brand names\nconst resources = {\n pip: 'PIP',\n airplay: 'AirPlay',\n html5: 'HTML5',\n vimeo: 'Vimeo',\n youtube: 'YouTube',\n};\n\nconst i18n = {\n get(key = '', config = {}) {\n if (is.empty(key) || is.empty(config)) {\n return '';\n }\n\n let string = getDeep(config.i18n, key);\n\n if (is.empty(string)) {\n if (Object.keys(resources).includes(key)) {\n return resources[key];\n }\n\n return '';\n }\n\n const replace = {\n '{seektime}': config.seekTime,\n '{title}': config.title,\n };\n\n Object.entries(replace).forEach(([k, v]) => {\n string = replaceAll(string, k, v);\n });\n\n return string;\n },\n};\n\nexport default i18n;\n","// ==========================================================================\n// Plyr storage\n// ==========================================================================\n\nimport is from './utils/is';\nimport { extend } from './utils/objects';\n\nclass Storage {\n constructor(player) {\n this.enabled = player.config.storage.enabled;\n this.key = player.config.storage.key;\n }\n\n // Check for actual support (see if we can use it)\n static get supported() {\n try {\n if (!('localStorage' in window)) {\n return false;\n }\n\n const test = '___test';\n\n // Try to use it (it might be disabled, e.g. user is in private mode)\n // see: https://github.com/sampotts/plyr/issues/131\n window.localStorage.setItem(test, test);\n window.localStorage.removeItem(test);\n\n return true;\n } catch (_) {\n return false;\n }\n }\n\n get = (key) => {\n if (!Storage.supported || !this.enabled) {\n return null;\n }\n\n const store = window.localStorage.getItem(this.key);\n\n if (is.empty(store)) {\n return null;\n }\n\n const json = JSON.parse(store);\n\n return is.string(key) && key.length ? json[key] : json;\n };\n\n set = (object) => {\n // Bail if we don't have localStorage support or it's disabled\n if (!Storage.supported || !this.enabled) {\n return;\n }\n\n // Can only store objectst\n if (!is.object(object)) {\n return;\n }\n\n // Get current storage\n let storage = this.get();\n\n // Default to empty object\n if (is.empty(storage)) {\n storage = {};\n }\n\n // Update the working copy of the values\n extend(storage, object);\n\n // Update storage\n try {\n window.localStorage.setItem(this.key, JSON.stringify(storage));\n } catch (_) {\n // Do nothing\n }\n };\n}\n\nexport default Storage;\n","// ==========================================================================\n// Fetch wrapper\n// Using XHR to avoid issues with older browsers\n// ==========================================================================\n\nexport default function fetch(url, responseType = 'text') {\n return new Promise((resolve, reject) => {\n try {\n const request = new XMLHttpRequest();\n\n // Check for CORS support\n if (!('withCredentials' in request)) {\n return;\n }\n\n request.addEventListener('load', () => {\n if (responseType === 'text') {\n try {\n resolve(JSON.parse(request.responseText));\n } catch (_) {\n resolve(request.responseText);\n }\n } else {\n resolve(request.response);\n }\n });\n\n request.addEventListener('error', () => {\n throw new Error(request.status);\n });\n\n request.open('GET', url, true);\n\n // Set the required response type\n request.responseType = responseType;\n\n request.send();\n } catch (error) {\n reject(error);\n }\n });\n}\n","// ==========================================================================\n// Sprite loader\n// ==========================================================================\n\nimport Storage from '../storage';\nimport fetch from './fetch';\nimport is from './is';\n\n// Load an external SVG sprite\nexport default function loadSprite(url, id) {\n if (!is.string(url)) {\n return;\n }\n\n const prefix = 'cache';\n const hasId = is.string(id);\n let isCached = false;\n const exists = () => document.getElementById(id) !== null;\n\n const update = (container, data) => {\n // eslint-disable-next-line no-param-reassign\n container.innerHTML = data;\n\n // Check again incase of race condition\n if (hasId && exists()) {\n return;\n }\n\n // Inject the SVG to the body\n document.body.insertAdjacentElement('afterbegin', container);\n };\n\n // Only load once if ID set\n if (!hasId || !exists()) {\n const useStorage = Storage.supported;\n // Create container\n const container = document.createElement('div');\n container.setAttribute('hidden', '');\n\n if (hasId) {\n container.setAttribute('id', id);\n }\n\n // Check in cache\n if (useStorage) {\n const cached = window.localStorage.getItem(`${prefix}-${id}`);\n isCached = cached !== null;\n\n if (isCached) {\n const data = JSON.parse(cached);\n update(container, data.content);\n }\n }\n\n // Get the sprite\n fetch(url)\n .then((result) => {\n if (is.empty(result)) {\n return;\n }\n\n if (useStorage) {\n try {\n window.localStorage.setItem(\n `${prefix}-${id}`,\n JSON.stringify({\n content: result,\n }),\n );\n } catch (_) {\n // Do nothing\n }\n }\n\n update(container, result);\n })\n .catch(() => {});\n }\n}\n","// ==========================================================================\n// Time utils\n// ==========================================================================\n\nimport is from './is';\n\n// Time helpers\nexport const getHours = (value) => Math.trunc((value / 60 / 60) % 60, 10);\nexport const getMinutes = (value) => Math.trunc((value / 60) % 60, 10);\nexport const getSeconds = (value) => Math.trunc(value % 60, 10);\n\n// Format time to UI friendly string\nexport function formatTime(time = 0, displayHours = false, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return formatTime(undefined, displayHours, inverted);\n }\n\n // Format time component to add leading zero\n const format = (value) => `0${value}`.slice(-2);\n // Breakdown to hours, mins, secs\n let hours = getHours(time);\n const mins = getMinutes(time);\n const secs = getSeconds(time);\n\n // Do we need to display hours?\n if (displayHours || hours > 0) {\n hours = `${hours}:`;\n } else {\n hours = '';\n }\n\n // Render\n return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`;\n}\n","// ==========================================================================\n// Plyr controls\n// TODO: This needs to be split into smaller files and cleaned up\n// ==========================================================================\n\nimport RangeTouch from 'rangetouch';\n\nimport captions from './captions';\nimport html5 from './html5';\nimport support from './support';\nimport { repaint, transitionEndEvent } from './utils/animation';\nimport { dedupe } from './utils/arrays';\nimport browser from './utils/browser';\nimport {\n createElement,\n emptyElement,\n getAttributesFromSelector,\n getElement,\n getElements,\n hasClass,\n matches,\n removeElement,\n setAttributes,\n setFocus,\n toggleClass,\n toggleHidden,\n} from './utils/elements';\nimport { off, on } from './utils/events';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport loadSprite from './utils/load-sprite';\nimport { extend } from './utils/objects';\nimport { getPercentage, replaceAll, toCamelCase, toTitleCase } from './utils/strings';\nimport { formatTime, getHours } from './utils/time';\n\n// TODO: Don't export a massive object - break down and create class\nconst controls = {\n // Get icon URL\n getIconUrl() {\n const url = new URL(this.config.iconUrl, window.location);\n const host = window.location.host ? window.location.host : window.top.location.host;\n const cors = url.host !== host || (browser.isIE && !window.svg4everybody);\n\n return {\n url: this.config.iconUrl,\n cors,\n };\n },\n\n // Find the UI controls\n findElements() {\n try {\n this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper);\n\n // Buttons\n this.elements.buttons = {\n play: getElements.call(this, this.config.selectors.buttons.play),\n pause: getElement.call(this, this.config.selectors.buttons.pause),\n restart: getElement.call(this, this.config.selectors.buttons.restart),\n rewind: getElement.call(this, this.config.selectors.buttons.rewind),\n fastForward: getElement.call(this, this.config.selectors.buttons.fastForward),\n mute: getElement.call(this, this.config.selectors.buttons.mute),\n pip: getElement.call(this, this.config.selectors.buttons.pip),\n airplay: getElement.call(this, this.config.selectors.buttons.airplay),\n settings: getElement.call(this, this.config.selectors.buttons.settings),\n captions: getElement.call(this, this.config.selectors.buttons.captions),\n fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen),\n };\n\n // Progress\n this.elements.progress = getElement.call(this, this.config.selectors.progress);\n\n // Inputs\n this.elements.inputs = {\n seek: getElement.call(this, this.config.selectors.inputs.seek),\n volume: getElement.call(this, this.config.selectors.inputs.volume),\n };\n\n // Display\n this.elements.display = {\n buffer: getElement.call(this, this.config.selectors.display.buffer),\n currentTime: getElement.call(this, this.config.selectors.display.currentTime),\n duration: getElement.call(this, this.config.selectors.display.duration),\n };\n\n // Seek tooltip\n if (is.element(this.elements.progress)) {\n this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`);\n }\n\n return true;\n } catch (error) {\n // Log it\n this.debug.warn('It looks like there is a problem with your custom controls HTML', error);\n\n // Restore native video controls\n this.toggleNativeControls(true);\n\n return false;\n }\n },\n\n // Create <svg> icon\n createIcon(type, attributes) {\n const namespace = 'http://www.w3.org/2000/svg';\n const iconUrl = controls.getIconUrl.call(this);\n const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`;\n // Create <svg>\n const icon = document.createElementNS(namespace, 'svg');\n setAttributes(\n icon,\n extend(attributes, {\n 'aria-hidden': 'true',\n focusable: 'false',\n }),\n );\n\n // Create the <use> to reference sprite\n const use = document.createElementNS(namespace, 'use');\n const path = `${iconPath}-${type}`;\n\n // Set `href` attributes\n // https://github.com/sampotts/plyr/issues/460\n // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href\n if ('href' in use) {\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path);\n }\n\n // Always set the older attribute even though it's \"deprecated\" (it'll be around for ages)\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path);\n\n // Add <use> to <svg>\n icon.appendChild(use);\n\n return icon;\n },\n\n // Create hidden text label\n createLabel(key, attr = {}) {\n const text = i18n.get(key, this.config);\n const attributes = { ...attr, class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ') };\n\n return createElement('span', attributes, text);\n },\n\n // Create a badge\n createBadge(text) {\n if (is.empty(text)) {\n return null;\n }\n\n const badge = createElement('span', {\n class: this.config.classNames.menu.value,\n });\n\n badge.appendChild(\n createElement(\n 'span',\n {\n class: this.config.classNames.menu.badge,\n },\n text,\n ),\n );\n\n return badge;\n },\n\n // Create a <button>\n createButton(buttonType, attr) {\n const attributes = extend({}, attr);\n let type = toCamelCase(buttonType);\n\n const props = {\n element: 'button',\n toggle: false,\n label: null,\n icon: null,\n labelPressed: null,\n iconPressed: null,\n };\n\n ['element', 'icon', 'label'].forEach((key) => {\n if (Object.keys(attributes).includes(key)) {\n props[key] = attributes[key];\n delete attributes[key];\n }\n });\n\n // Default to 'button' type to prevent form submission\n if (props.element === 'button' && !Object.keys(attributes).includes('type')) {\n attributes.type = 'button';\n }\n\n // Set class name\n if (Object.keys(attributes).includes('class')) {\n if (!attributes.class.split(' ').some((c) => c === this.config.classNames.control)) {\n extend(attributes, {\n class: `${attributes.class} ${this.config.classNames.control}`,\n });\n }\n } else {\n attributes.class = this.config.classNames.control;\n }\n\n // Large play button\n switch (buttonType) {\n case 'play':\n props.toggle = true;\n props.label = 'play';\n props.labelPressed = 'pause';\n props.icon = 'play';\n props.iconPressed = 'pause';\n break;\n\n case 'mute':\n props.toggle = true;\n props.label = 'mute';\n props.labelPressed = 'unmute';\n props.icon = 'volume';\n props.iconPressed = 'muted';\n break;\n\n case 'captions':\n props.toggle = true;\n props.label = 'enableCaptions';\n props.labelPressed = 'disableCaptions';\n props.icon = 'captions-off';\n props.iconPressed = 'captions-on';\n break;\n\n case 'fullscreen':\n props.toggle = true;\n props.label = 'enterFullscreen';\n props.labelPressed = 'exitFullscreen';\n props.icon = 'enter-fullscreen';\n props.iconPressed = 'exit-fullscreen';\n break;\n\n case 'play-large':\n attributes.class += ` ${this.config.classNames.control}--overlaid`;\n type = 'play';\n props.label = 'play';\n props.icon = 'play';\n break;\n\n default:\n if (is.empty(props.label)) {\n props.label = type;\n }\n if (is.empty(props.icon)) {\n props.icon = buttonType;\n }\n }\n\n const button = createElement(props.element);\n\n // Setup toggle icon and labels\n if (props.toggle) {\n // Icon\n button.appendChild(\n controls.createIcon.call(this, props.iconPressed, {\n class: 'icon--pressed',\n }),\n );\n button.appendChild(\n controls.createIcon.call(this, props.icon, {\n class: 'icon--not-pressed',\n }),\n );\n\n // Label/Tooltip\n button.appendChild(\n controls.createLabel.call(this, props.labelPressed, {\n class: 'label--pressed',\n }),\n );\n button.appendChild(\n controls.createLabel.call(this, props.label, {\n class: 'label--not-pressed',\n }),\n );\n } else {\n button.appendChild(controls.createIcon.call(this, props.icon));\n button.appendChild(controls.createLabel.call(this, props.label));\n }\n\n // Merge and set attributes\n extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes));\n setAttributes(button, attributes);\n\n // We have multiple play buttons\n if (type === 'play') {\n if (!is.array(this.elements.buttons[type])) {\n this.elements.buttons[type] = [];\n }\n\n this.elements.buttons[type].push(button);\n } else {\n this.elements.buttons[type] = button;\n }\n\n return button;\n },\n\n // Create an <input type='range'>\n createRange(type, attributes) {\n // Seek input\n const input = createElement(\n 'input',\n extend(\n getAttributesFromSelector(this.config.selectors.inputs[type]),\n {\n type: 'range',\n min: 0,\n max: 100,\n step: 0.01,\n value: 0,\n autocomplete: 'off',\n // A11y fixes for https://github.com/sampotts/plyr/issues/905\n role: 'slider',\n 'aria-label': i18n.get(type, this.config),\n 'aria-valuemin': 0,\n 'aria-valuemax': 100,\n 'aria-valuenow': 0,\n },\n attributes,\n ),\n );\n\n this.elements.inputs[type] = input;\n\n // Set the fill for webkit now\n controls.updateRangeFill.call(this, input);\n\n // Improve support on touch devices\n RangeTouch.setup(input);\n\n return input;\n },\n\n // Create a <progress>\n createProgress(type, attributes) {\n const progress = createElement(\n 'progress',\n extend(\n getAttributesFromSelector(this.config.selectors.display[type]),\n {\n min: 0,\n max: 100,\n value: 0,\n role: 'progressbar',\n 'aria-hidden': true,\n },\n attributes,\n ),\n );\n\n // Create the label inside\n if (type !== 'volume') {\n progress.appendChild(createElement('span', null, '0'));\n\n const suffixKey = {\n played: 'played',\n buffer: 'buffered',\n }[type];\n const suffix = suffixKey ? i18n.get(suffixKey, this.config) : '';\n\n progress.innerText = `% ${suffix.toLowerCase()}`;\n }\n\n this.elements.display[type] = progress;\n\n return progress;\n },\n\n // Create time display\n createTime(type, attrs) {\n const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs);\n\n const container = createElement(\n 'div',\n extend(attributes, {\n class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(),\n 'aria-label': i18n.get(type, this.config),\n }),\n '00:00',\n );\n\n // Reference for updates\n this.elements.display[type] = container;\n\n return container;\n },\n\n // Bind keyboard shortcuts for a menu item\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n bindMenuItemShortcuts(menuItem, type) {\n // Navigate through menus via arrow keys and space\n on.call(\n this,\n menuItem,\n 'keydown keyup',\n (event) => {\n // We only care about space and ⬆️ ⬇️️ ➡️\n if (![32, 38, 39, 40].includes(event.which)) {\n return;\n }\n\n // Prevent play / seek\n event.preventDefault();\n event.stopPropagation();\n\n // We're just here to prevent the keydown bubbling\n if (event.type === 'keydown') {\n return;\n }\n\n const isRadioButton = matches(menuItem, '[role=\"menuitemradio\"]');\n\n // Show the respective menu\n if (!isRadioButton && [32, 39].includes(event.which)) {\n controls.showMenuPanel.call(this, type, true);\n } else {\n let target;\n\n if (event.which !== 32) {\n if (event.which === 40 || (isRadioButton && event.which === 39)) {\n target = menuItem.nextElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.firstElementChild;\n }\n } else {\n target = menuItem.previousElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.lastElementChild;\n }\n }\n\n setFocus.call(this, target, true);\n }\n }\n },\n false,\n );\n\n // Enter will fire a `click` event but we still need to manage focus\n // So we bind to keyup which fires after and set focus here\n on.call(this, menuItem, 'keyup', (event) => {\n if (event.which !== 13) {\n return;\n }\n\n controls.focusFirstMenuItem.call(this, null, true);\n });\n },\n\n // Create a settings menu item\n createMenuItem({ value, list, type, title, badge = null, checked = false }) {\n const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]);\n\n const menuItem = createElement(\n 'button',\n extend(attributes, {\n type: 'button',\n role: 'menuitemradio',\n class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(),\n 'aria-checked': checked,\n value,\n }),\n );\n\n const flex = createElement('span');\n\n // We have to set as HTML incase of special characters\n flex.innerHTML = title;\n\n if (is.element(badge)) {\n flex.appendChild(badge);\n }\n\n menuItem.appendChild(flex);\n\n // Replicate radio button behaviour\n Object.defineProperty(menuItem, 'checked', {\n enumerable: true,\n get() {\n return menuItem.getAttribute('aria-checked') === 'true';\n },\n set(check) {\n // Ensure exclusivity\n if (check) {\n Array.from(menuItem.parentNode.children)\n .filter((node) => matches(node, '[role=\"menuitemradio\"]'))\n .forEach((node) => node.setAttribute('aria-checked', 'false'));\n }\n\n menuItem.setAttribute('aria-checked', check ? 'true' : 'false');\n },\n });\n\n this.listeners.bind(\n menuItem,\n 'click keyup',\n (event) => {\n if (is.keyboardEvent(event) && event.which !== 32) {\n return;\n }\n\n event.preventDefault();\n event.stopPropagation();\n\n menuItem.checked = true;\n\n switch (type) {\n case 'language':\n this.currentTrack = Number(value);\n break;\n\n case 'quality':\n this.quality = value;\n break;\n\n case 'speed':\n this.speed = parseFloat(value);\n break;\n\n default:\n break;\n }\n\n controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event));\n },\n type,\n false,\n );\n\n controls.bindMenuItemShortcuts.call(this, menuItem, type);\n\n list.appendChild(menuItem);\n },\n\n // Format a time for display\n formatTime(time = 0, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return time;\n }\n\n // Always display hours if duration is over an hour\n const forceHours = getHours(this.duration) > 0;\n\n return formatTime(time, forceHours, inverted);\n },\n\n // Update the displayed time\n updateTimeDisplay(target = null, time = 0, inverted = false) {\n // Bail if there's no element to display or the value isn't a number\n if (!is.element(target) || !is.number(time)) {\n return;\n }\n\n // eslint-disable-next-line no-param-reassign\n target.innerText = controls.formatTime(time, inverted);\n },\n\n // Update volume UI and storage\n updateVolume() {\n if (!this.supported.ui) {\n return;\n }\n\n // Update range\n if (is.element(this.elements.inputs.volume)) {\n controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);\n }\n\n // Update mute state\n if (is.element(this.elements.buttons.mute)) {\n this.elements.buttons.mute.pressed = this.muted || this.volume === 0;\n }\n },\n\n // Update seek value and lower fill\n setRange(target, value = 0) {\n if (!is.element(target)) {\n return;\n }\n\n // eslint-disable-next-line\n target.value = value;\n\n // Webkit range fill\n controls.updateRangeFill.call(this, target);\n },\n\n // Update <progress> elements\n updateProgress(event) {\n if (!this.supported.ui || !is.event(event)) {\n return;\n }\n\n let value = 0;\n\n const setProgress = (target, input) => {\n const val = is.number(input) ? input : 0;\n const progress = is.element(target) ? target : this.elements.display.buffer;\n\n // Update value and label\n if (is.element(progress)) {\n progress.value = val;\n\n // Update text label inside\n const label = progress.getElementsByTagName('span')[0];\n if (is.element(label)) {\n label.childNodes[0].nodeValue = val;\n }\n }\n };\n\n if (event) {\n switch (event.type) {\n // Video playing\n case 'timeupdate':\n case 'seeking':\n case 'seeked':\n value = getPercentage(this.currentTime, this.duration);\n\n // Set seek range value only if it's a 'natural' time event\n if (event.type === 'timeupdate') {\n controls.setRange.call(this, this.elements.inputs.seek, value);\n }\n\n break;\n\n // Check buffer status\n case 'playing':\n case 'progress':\n setProgress(this.elements.display.buffer, this.buffered * 100);\n\n break;\n\n default:\n break;\n }\n }\n },\n\n // Webkit polyfill for lower fill range\n updateRangeFill(target) {\n // Get range from event if event passed\n const range = is.event(target) ? target.target : target;\n\n // Needs to be a valid <input type='range'>\n if (!is.element(range) || range.getAttribute('type') !== 'range') {\n return;\n }\n\n // Set aria values for https://github.com/sampotts/plyr/issues/905\n if (matches(range, this.config.selectors.inputs.seek)) {\n range.setAttribute('aria-valuenow', this.currentTime);\n const currentTime = controls.formatTime(this.currentTime);\n const duration = controls.formatTime(this.duration);\n const format = i18n.get('seekLabel', this.config);\n range.setAttribute(\n 'aria-valuetext',\n format.replace('{currentTime}', currentTime).replace('{duration}', duration),\n );\n } else if (matches(range, this.config.selectors.inputs.volume)) {\n const percent = range.value * 100;\n range.setAttribute('aria-valuenow', percent);\n range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`);\n } else {\n range.setAttribute('aria-valuenow', range.value);\n }\n\n // WebKit only\n if (!browser.isWebkit) {\n return;\n }\n\n // Set CSS custom property\n range.style.setProperty('--value', `${(range.value / range.max) * 100}%`);\n },\n\n // Update hover tooltip for seeking\n updateSeekTooltip(event) {\n // Bail if setting not true\n if (\n !this.config.tooltips.seek ||\n !is.element(this.elements.inputs.seek) ||\n !is.element(this.elements.display.seekTooltip) ||\n this.duration === 0\n ) {\n return;\n }\n\n const visible = `${this.config.classNames.tooltip}--visible`;\n const toggle = (show) => toggleClass(this.elements.display.seekTooltip, visible, show);\n\n // Hide on touch\n if (this.touch) {\n toggle(false);\n return;\n }\n\n // Determine percentage, if already visible\n let percent = 0;\n const clientRect = this.elements.progress.getBoundingClientRect();\n\n if (is.event(event)) {\n percent = (100 / clientRect.width) * (event.pageX - clientRect.left);\n } else if (hasClass(this.elements.display.seekTooltip, visible)) {\n percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);\n } else {\n return;\n }\n\n // Set bounds\n if (percent < 0) {\n percent = 0;\n } else if (percent > 100) {\n percent = 100;\n }\n\n // Display the time a click would seek to\n controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, (this.duration / 100) * percent);\n\n // Set position\n this.elements.display.seekTooltip.style.left = `${percent}%`;\n\n // Show/hide the tooltip\n // If the event is a moues in/out and percentage is inside bounds\n if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) {\n toggle(event.type === 'mouseenter');\n }\n },\n\n // Handle time change event\n timeUpdate(event) {\n // Only invert if only one time element is displayed and used for both duration and currentTime\n const invert = !is.element(this.elements.display.duration) && this.config.invertTime;\n\n // Duration\n controls.updateTimeDisplay.call(\n this,\n this.elements.display.currentTime,\n invert ? this.duration - this.currentTime : this.currentTime,\n invert,\n );\n\n // Ignore updates while seeking\n if (event && event.type === 'timeupdate' && this.media.seeking) {\n return;\n }\n\n // Playing progress\n controls.updateProgress.call(this, event);\n },\n\n // Show the duration on metadataloaded or durationchange events\n durationUpdate() {\n // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false\n if (!this.supported.ui || (!this.config.invertTime && this.currentTime)) {\n return;\n }\n\n // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar.\n // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415\n // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062\n // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338\n if (this.duration >= 2 ** 32) {\n toggleHidden(this.elements.display.currentTime, true);\n toggleHidden(this.elements.progress, true);\n return;\n }\n\n // Update ARIA values\n if (is.element(this.elements.inputs.seek)) {\n this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration);\n }\n\n // If there's a spot to display duration\n const hasDuration = is.element(this.elements.display.duration);\n\n // If there's only one time display, display duration there\n if (!hasDuration && this.config.displayDuration && this.paused) {\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);\n }\n\n // If there's a duration element, update content\n if (hasDuration) {\n controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);\n }\n\n // Update the tooltip (if visible)\n controls.updateSeekTooltip.call(this);\n },\n\n // Hide/show a tab\n toggleMenuButton(setting, toggle) {\n toggleHidden(this.elements.settings.buttons[setting], !toggle);\n },\n\n // Update the selected setting\n updateSetting(setting, container, input) {\n const pane = this.elements.settings.panels[setting];\n let value = null;\n let list = container;\n\n if (setting === 'captions') {\n value = this.currentTrack;\n } else {\n value = !is.empty(input) ? input : this[setting];\n\n // Get default\n if (is.empty(value)) {\n value = this.config[setting].default;\n }\n\n // Unsupported value\n if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) {\n this.debug.warn(`Unsupported value of '${value}' for ${setting}`);\n return;\n }\n\n // Disabled value\n if (!this.config[setting].options.includes(value)) {\n this.debug.warn(`Disabled value of '${value}' for ${setting}`);\n return;\n }\n }\n\n // Get the list if we need to\n if (!is.element(list)) {\n list = pane && pane.querySelector('[role=\"menu\"]');\n }\n\n // If there's no list it means it's not been rendered...\n if (!is.element(list)) {\n return;\n }\n\n // Update the label\n const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`);\n label.innerHTML = controls.getLabel.call(this, setting, value);\n\n // Find the radio option and check it\n const target = list && list.querySelector(`[value=\"${value}\"]`);\n\n if (is.element(target)) {\n target.checked = true;\n }\n },\n\n // Translate a value into a nice label\n getLabel(setting, value) {\n switch (setting) {\n case 'speed':\n return value === 1 ? i18n.get('normal', this.config) : `${value}×`;\n\n case 'quality':\n if (is.number(value)) {\n const label = i18n.get(`qualityLabel.${value}`, this.config);\n\n if (!label.length) {\n return `${value}p`;\n }\n\n return label;\n }\n\n return toTitleCase(value);\n\n case 'captions':\n return captions.getLabel.call(this);\n\n default:\n return null;\n }\n },\n\n // Set the quality menu\n setQualityMenu(options) {\n // Menu required\n if (!is.element(this.elements.settings.panels.quality)) {\n return;\n }\n\n const type = 'quality';\n const list = this.elements.settings.panels.quality.querySelector('[role=\"menu\"]');\n\n // Set options if passed and filter based on uniqueness and config\n if (is.array(options)) {\n this.options.quality = dedupe(options).filter((quality) => this.config.quality.options.includes(quality));\n }\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1;\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If we're hiding, nothing more to do\n if (!toggle) {\n return;\n }\n\n // Get the badge HTML for HD, 4K etc\n const getBadge = (quality) => {\n const label = i18n.get(`qualityBadge.${quality}`, this.config);\n\n if (!label.length) {\n return null;\n }\n\n return controls.createBadge.call(this, label);\n };\n\n // Sort options by the config and then render options\n this.options.quality\n .sort((a, b) => {\n const sorting = this.config.quality.options;\n return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1;\n })\n .forEach((quality) => {\n controls.createMenuItem.call(this, {\n value: quality,\n list,\n type,\n title: controls.getLabel.call(this, 'quality', quality),\n badge: getBadge(quality),\n });\n });\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Set the looping options\n /* setLoopMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.loop)) {\n return;\n }\n\n const options = ['start', 'end', 'all', 'reset'];\n const list = this.elements.settings.panels.loop.querySelector('[role=\"menu\"]');\n\n // Show the pane and tab\n toggleHidden(this.elements.settings.buttons.loop, false);\n toggleHidden(this.elements.settings.panels.loop, false);\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.loop.options);\n controls.toggleMenuButton.call(this, 'loop', toggle);\n\n // Empty the menu\n emptyElement(list);\n\n options.forEach(option => {\n const item = createElement('li');\n\n const button = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.loop), {\n type: 'button',\n class: this.config.classNames.control,\n 'data-plyr-loop-action': option,\n }),\n i18n.get(option, this.config)\n );\n\n if (['start', 'end'].includes(option)) {\n const badge = controls.createBadge.call(this, '00:00');\n button.appendChild(badge);\n }\n\n item.appendChild(button);\n list.appendChild(item);\n });\n }, */\n\n // Get current selected caption language\n // TODO: rework this to user the getter in the API?\n\n // Set a list of available captions languages\n setCaptionsMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.captions)) {\n return;\n }\n\n // TODO: Captions or language? Currently it's mixed\n const type = 'captions';\n const list = this.elements.settings.panels.captions.querySelector('[role=\"menu\"]');\n const tracks = captions.getTracks.call(this);\n const toggle = Boolean(tracks.length);\n\n // Toggle the pane and tab\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If there's no captions, bail\n if (!toggle) {\n return;\n }\n\n // Generate options data\n const options = tracks.map((track, value) => ({\n value,\n checked: this.captions.toggled && this.currentTrack === value,\n title: captions.getLabel.call(this, track),\n badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()),\n list,\n type: 'language',\n }));\n\n // Add the \"Disabled\" option to turn off captions\n options.unshift({\n value: -1,\n checked: !this.captions.toggled,\n title: i18n.get('disabled', this.config),\n list,\n type: 'language',\n });\n\n // Generate options\n options.forEach(controls.createMenuItem.bind(this));\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Set a list of available captions languages\n setSpeedMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.speed)) {\n return;\n }\n\n const type = 'speed';\n const list = this.elements.settings.panels.speed.querySelector('[role=\"menu\"]');\n\n // Filter out invalid speeds\n this.options.speed = this.options.speed.filter((o) => o >= this.minimumSpeed && o <= this.maximumSpeed);\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1;\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If we're hiding, nothing more to do\n if (!toggle) {\n return;\n }\n\n // Create items\n this.options.speed.forEach((speed) => {\n controls.createMenuItem.call(this, {\n value: speed,\n list,\n type,\n title: controls.getLabel.call(this, 'speed', speed),\n });\n });\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Check if we need to hide/show the settings menu\n checkMenu() {\n const { buttons } = this.elements.settings;\n const visible = !is.empty(buttons) && Object.values(buttons).some((button) => !button.hidden);\n\n toggleHidden(this.elements.settings.menu, !visible);\n },\n\n // Focus the first menu item in a given (or visible) menu\n focusFirstMenuItem(pane, tabFocus = false) {\n if (this.elements.settings.popup.hidden) {\n return;\n }\n\n let target = pane;\n\n if (!is.element(target)) {\n target = Object.values(this.elements.settings.panels).find((p) => !p.hidden);\n }\n\n const firstItem = target.querySelector('[role^=\"menuitem\"]');\n\n setFocus.call(this, firstItem, tabFocus);\n },\n\n // Show/hide menu\n toggleMenu(input) {\n const { popup } = this.elements.settings;\n const button = this.elements.buttons.settings;\n\n // Menu and button are required\n if (!is.element(popup) || !is.element(button)) {\n return;\n }\n\n // True toggle by default\n const { hidden } = popup;\n let show = hidden;\n\n if (is.boolean(input)) {\n show = input;\n } else if (is.keyboardEvent(input) && input.which === 27) {\n show = false;\n } else if (is.event(input)) {\n // If Plyr is in a shadowDOM, the event target is set to the component, instead of the\n // Element in the shadowDOM. The path, if available, is complete.\n const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target;\n const isMenuItem = popup.contains(target);\n\n // If the click was inside the menu or if the click\n // wasn't the button or menu item and we're trying to\n // show the menu (a doc click shouldn't show the menu)\n if (isMenuItem || (!isMenuItem && input.target !== button && show)) {\n return;\n }\n }\n\n // Set button attributes\n button.setAttribute('aria-expanded', show);\n\n // Show the actual popup\n toggleHidden(popup, !show);\n\n // Add class hook\n toggleClass(this.elements.container, this.config.classNames.menu.open, show);\n\n // Focus the first item if key interaction\n if (show && is.keyboardEvent(input)) {\n controls.focusFirstMenuItem.call(this, null, true);\n } else if (!show && !hidden) {\n // If closing, re-focus the button\n setFocus.call(this, button, is.keyboardEvent(input));\n }\n },\n\n // Get the natural size of a menu panel\n getMenuSize(tab) {\n const clone = tab.cloneNode(true);\n clone.style.position = 'absolute';\n clone.style.opacity = 0;\n clone.removeAttribute('hidden');\n\n // Append to parent so we get the \"real\" size\n tab.parentNode.appendChild(clone);\n\n // Get the sizes before we remove\n const width = clone.scrollWidth;\n const height = clone.scrollHeight;\n\n // Remove from the DOM\n removeElement(clone);\n\n return {\n width,\n height,\n };\n },\n\n // Show a panel in the menu\n showMenuPanel(type = '', tabFocus = false) {\n const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`);\n\n // Nothing to show, bail\n if (!is.element(target)) {\n return;\n }\n\n // Hide all other panels\n const container = target.parentNode;\n const current = Array.from(container.children).find((node) => !node.hidden);\n\n // If we can do fancy animations, we'll animate the height/width\n if (support.transitions && !support.reducedMotion) {\n // Set the current width as a base\n container.style.width = `${current.scrollWidth}px`;\n container.style.height = `${current.scrollHeight}px`;\n\n // Get potential sizes\n const size = controls.getMenuSize.call(this, target);\n\n // Restore auto height/width\n const restore = (event) => {\n // We're only bothered about height and width on the container\n if (event.target !== container || !['width', 'height'].includes(event.propertyName)) {\n return;\n }\n\n // Revert back to auto\n container.style.width = '';\n container.style.height = '';\n\n // Only listen once\n off.call(this, container, transitionEndEvent, restore);\n };\n\n // Listen for the transition finishing and restore auto height/width\n on.call(this, container, transitionEndEvent, restore);\n\n // Set dimensions to target\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n }\n\n // Set attributes on current tab\n toggleHidden(current, true);\n\n // Set attributes on target\n toggleHidden(target, false);\n\n // Focus the first item\n controls.focusFirstMenuItem.call(this, target, tabFocus);\n },\n\n // Set the download URL\n setDownloadUrl() {\n const button = this.elements.buttons.download;\n\n // Bail if no button\n if (!is.element(button)) {\n return;\n }\n\n // Set attribute\n button.setAttribute('href', this.download);\n },\n\n // Build the default HTML\n create(data) {\n const {\n bindMenuItemShortcuts,\n createButton,\n createProgress,\n createRange,\n createTime,\n setQualityMenu,\n setSpeedMenu,\n showMenuPanel,\n } = controls;\n this.elements.controls = null;\n\n // Larger overlaid play button\n if (is.array(this.config.controls) && this.config.controls.includes('play-large')) {\n this.elements.container.appendChild(createButton.call(this, 'play-large'));\n }\n\n // Create the container\n const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper));\n this.elements.controls = container;\n\n // Default item attributes\n const defaultAttributes = { class: 'plyr__controls__item' };\n\n // Loop through controls in order\n dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach((control) => {\n // Restart button\n if (control === 'restart') {\n container.appendChild(createButton.call(this, 'restart', defaultAttributes));\n }\n\n // Rewind button\n if (control === 'rewind') {\n container.appendChild(createButton.call(this, 'rewind', defaultAttributes));\n }\n\n // Play/Pause button\n if (control === 'play') {\n container.appendChild(createButton.call(this, 'play', defaultAttributes));\n }\n\n // Fast forward button\n if (control === 'fast-forward') {\n container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes));\n }\n\n // Progress\n if (control === 'progress') {\n const progressContainer = createElement('div', {\n class: `${defaultAttributes.class} plyr__progress__container`,\n });\n\n const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress));\n\n // Seek range slider\n progress.appendChild(\n createRange.call(this, 'seek', {\n id: `plyr-seek-${data.id}`,\n }),\n );\n\n // Buffer progress\n progress.appendChild(createProgress.call(this, 'buffer'));\n\n // TODO: Add loop display indicator\n\n // Seek tooltip\n if (this.config.tooltips.seek) {\n const tooltip = createElement(\n 'span',\n {\n class: this.config.classNames.tooltip,\n },\n '00:00',\n );\n\n progress.appendChild(tooltip);\n this.elements.display.seekTooltip = tooltip;\n }\n\n this.elements.progress = progress;\n progressContainer.appendChild(this.elements.progress);\n container.appendChild(progressContainer);\n }\n\n // Media current time display\n if (control === 'current-time') {\n container.appendChild(createTime.call(this, 'currentTime', defaultAttributes));\n }\n\n // Media duration display\n if (control === 'duration') {\n container.appendChild(createTime.call(this, 'duration', defaultAttributes));\n }\n\n // Volume controls\n if (control === 'mute' || control === 'volume') {\n let { volume } = this.elements;\n\n // Create the volume container if needed\n if (!is.element(volume) || !container.contains(volume)) {\n volume = createElement(\n 'div',\n extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__volume`.trim(),\n }),\n );\n\n this.elements.volume = volume;\n\n container.appendChild(volume);\n }\n\n // Toggle mute button\n if (control === 'mute') {\n volume.appendChild(createButton.call(this, 'mute'));\n }\n\n // Volume range control\n // Ignored on iOS as it's handled globally\n // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html\n if (control === 'volume' && !browser.isIos) {\n // Set the attributes\n const attributes = {\n max: 1,\n step: 0.05,\n value: this.config.volume,\n };\n\n // Create the volume range slider\n volume.appendChild(\n createRange.call(\n this,\n 'volume',\n extend(attributes, {\n id: `plyr-volume-${data.id}`,\n }),\n ),\n );\n }\n }\n\n // Toggle captions button\n if (control === 'captions') {\n container.appendChild(createButton.call(this, 'captions', defaultAttributes));\n }\n\n // Settings button / menu\n if (control === 'settings' && !is.empty(this.config.settings)) {\n const wrapper = createElement(\n 'div',\n extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__menu`.trim(),\n hidden: '',\n }),\n );\n\n wrapper.appendChild(\n createButton.call(this, 'settings', {\n 'aria-haspopup': true,\n 'aria-controls': `plyr-settings-${data.id}`,\n 'aria-expanded': false,\n }),\n );\n\n const popup = createElement('div', {\n class: 'plyr__menu__container',\n id: `plyr-settings-${data.id}`,\n hidden: '',\n });\n\n const inner = createElement('div');\n\n const home = createElement('div', {\n id: `plyr-settings-${data.id}-home`,\n });\n\n // Create the menu\n const menu = createElement('div', {\n role: 'menu',\n });\n\n home.appendChild(menu);\n inner.appendChild(home);\n this.elements.settings.panels.home = home;\n\n // Build the menu items\n this.config.settings.forEach((type) => {\n // TODO: bundle this with the createMenuItem helper and bindings\n const menuItem = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.settings), {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`,\n role: 'menuitem',\n 'aria-haspopup': true,\n hidden: '',\n }),\n );\n\n // Bind menu shortcuts for keyboard users\n bindMenuItemShortcuts.call(this, menuItem, type);\n\n // Show menu on click\n on.call(this, menuItem, 'click', () => {\n showMenuPanel.call(this, type, false);\n });\n\n const flex = createElement('span', null, i18n.get(type, this.config));\n\n const value = createElement('span', {\n class: this.config.classNames.menu.value,\n });\n\n // Speed contains HTML entities\n value.innerHTML = data[type];\n\n flex.appendChild(value);\n menuItem.appendChild(flex);\n menu.appendChild(menuItem);\n\n // Build the panes\n const pane = createElement('div', {\n id: `plyr-settings-${data.id}-${type}`,\n hidden: '',\n });\n\n // Back button\n const backButton = createElement('button', {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--back`,\n });\n\n // Visible label\n backButton.appendChild(\n createElement(\n 'span',\n {\n 'aria-hidden': true,\n },\n i18n.get(type, this.config),\n ),\n );\n\n // Screen reader label\n backButton.appendChild(\n createElement(\n 'span',\n {\n class: this.config.classNames.hidden,\n },\n i18n.get('menuBack', this.config),\n ),\n );\n\n // Go back via keyboard\n on.call(\n this,\n pane,\n 'keydown',\n (event) => {\n // We only care about <-\n if (event.which !== 37) {\n return;\n }\n\n // Prevent seek\n event.preventDefault();\n event.stopPropagation();\n\n // Show the respective menu\n showMenuPanel.call(this, 'home', true);\n },\n false,\n );\n\n // Go back via button click\n on.call(this, backButton, 'click', () => {\n showMenuPanel.call(this, 'home', false);\n });\n\n // Add to pane\n pane.appendChild(backButton);\n\n // Menu\n pane.appendChild(\n createElement('div', {\n role: 'menu',\n }),\n );\n\n inner.appendChild(pane);\n\n this.elements.settings.buttons[type] = menuItem;\n this.elements.settings.panels[type] = pane;\n });\n\n popup.appendChild(inner);\n wrapper.appendChild(popup);\n container.appendChild(wrapper);\n\n this.elements.settings.popup = popup;\n this.elements.settings.menu = wrapper;\n }\n\n // Picture in picture button\n if (control === 'pip' && support.pip) {\n container.appendChild(createButton.call(this, 'pip', defaultAttributes));\n }\n\n // Airplay button\n if (control === 'airplay' && support.airplay) {\n container.appendChild(createButton.call(this, 'airplay', defaultAttributes));\n }\n\n // Download button\n if (control === 'download') {\n const attributes = extend({}, defaultAttributes, {\n element: 'a',\n href: this.download,\n target: '_blank',\n });\n\n // Set download attribute for HTML5 only\n if (this.isHTML5) {\n attributes.download = '';\n }\n\n const { download } = this.config.urls;\n\n if (!is.url(download) && this.isEmbed) {\n extend(attributes, {\n icon: `logo-${this.provider}`,\n label: this.provider,\n });\n }\n\n container.appendChild(createButton.call(this, 'download', attributes));\n }\n\n // Toggle fullscreen button\n if (control === 'fullscreen') {\n container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes));\n }\n });\n\n // Set available quality levels\n if (this.isHTML5) {\n setQualityMenu.call(this, html5.getQualityOptions.call(this));\n }\n\n setSpeedMenu.call(this);\n\n return container;\n },\n\n // Insert controls\n inject() {\n // Sprite\n if (this.config.loadSprite) {\n const icon = controls.getIconUrl.call(this);\n\n // Only load external sprite using AJAX\n if (icon.cors) {\n loadSprite(icon.url, 'sprite-plyr');\n }\n }\n\n // Create a unique ID\n this.id = Math.floor(Math.random() * 10000);\n\n // Null by default\n let container = null;\n this.elements.controls = null;\n\n // Set template properties\n const props = {\n id: this.id,\n seektime: this.config.seekTime,\n title: this.config.title,\n };\n let update = true;\n\n // If function, run it and use output\n if (is.function(this.config.controls)) {\n this.config.controls = this.config.controls.call(this, props);\n }\n\n // Convert falsy controls to empty array (primarily for empty strings)\n if (!this.config.controls) {\n this.config.controls = [];\n }\n\n if (is.element(this.config.controls) || is.string(this.config.controls)) {\n // HTMLElement or Non-empty string passed as the option\n container = this.config.controls;\n } else {\n // Create controls\n container = controls.create.call(this, {\n id: this.id,\n seektime: this.config.seekTime,\n speed: this.speed,\n quality: this.quality,\n captions: captions.getLabel.call(this),\n // TODO: Looping\n // loop: 'None',\n });\n update = false;\n }\n\n // Replace props with their value\n const replace = (input) => {\n let result = input;\n\n Object.entries(props).forEach(([key, value]) => {\n result = replaceAll(result, `{${key}}`, value);\n });\n\n return result;\n };\n\n // Update markup\n if (update) {\n if (is.string(this.config.controls)) {\n container = replace(container);\n }\n }\n\n // Controls container\n let target;\n\n // Inject to custom location\n if (is.string(this.config.selectors.controls.container)) {\n target = document.querySelector(this.config.selectors.controls.container);\n }\n\n // Inject into the container by default\n if (!is.element(target)) {\n target = this.elements.container;\n }\n\n // Inject controls HTML (needs to be before captions, hence \"afterbegin\")\n const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML';\n target[insertMethod]('afterbegin', container);\n\n // Find the elements if need be\n if (!is.element(this.elements.controls)) {\n controls.findElements.call(this);\n }\n\n // Add pressed property to buttons\n if (!is.empty(this.elements.buttons)) {\n const addProperty = (button) => {\n const className = this.config.classNames.controlPressed;\n Object.defineProperty(button, 'pressed', {\n enumerable: true,\n get() {\n return hasClass(button, className);\n },\n set(pressed = false) {\n toggleClass(button, className, pressed);\n },\n });\n };\n\n // Toggle classname when pressed property is set\n Object.values(this.elements.buttons)\n .filter(Boolean)\n .forEach((button) => {\n if (is.array(button) || is.nodeList(button)) {\n Array.from(button).filter(Boolean).forEach(addProperty);\n } else {\n addProperty(button);\n }\n });\n }\n\n // Edge sometimes doesn't finish the paint so force a repaint\n if (browser.isEdge) {\n repaint(target);\n }\n\n // Setup tooltips\n if (this.config.tooltips.controls) {\n const { classNames, selectors } = this.config;\n const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`;\n const labels = getElements.call(this, selector);\n\n Array.from(labels).forEach((label) => {\n toggleClass(label, this.config.classNames.hidden, false);\n toggleClass(label, this.config.classNames.tooltip, true);\n });\n }\n },\n};\n\nexport default controls;\n","// ==========================================================================\n// URL utils\n// ==========================================================================\n\nimport is from './is';\n\n/**\n * Parse a string to a URL object\n * @param {String} input - the URL to be parsed\n * @param {Boolean} safe - failsafe parsing\n */\nexport function parseUrl(input, safe = true) {\n let url = input;\n\n if (safe) {\n const parser = document.createElement('a');\n parser.href = url;\n url = parser.href;\n }\n\n try {\n return new URL(url);\n } catch (_) {\n return null;\n }\n}\n\n// Convert object to URLSearchParams\nexport function buildUrlParams(input) {\n const params = new URLSearchParams();\n\n if (is.object(input)) {\n Object.entries(input).forEach(([key, value]) => {\n params.set(key, value);\n });\n }\n\n return params;\n}\n","// ==========================================================================\n// Plyr Captions\n// TODO: Create as class\n// ==========================================================================\n\nimport controls from './controls';\nimport support from './support';\nimport { dedupe } from './utils/arrays';\nimport browser from './utils/browser';\nimport {\n createElement,\n emptyElement,\n getAttributesFromSelector,\n insertAfter,\n removeElement,\n toggleClass,\n} from './utils/elements';\nimport { on, triggerEvent } from './utils/events';\nimport fetch from './utils/fetch';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport { getHTML } from './utils/strings';\nimport { parseUrl } from './utils/urls';\n\nconst captions = {\n // Setup captions\n setup() {\n // Requires UI support\n if (!this.supported.ui) {\n return;\n }\n\n // Only Vimeo and HTML5 video supported at this point\n if (!this.isVideo || this.isYouTube || (this.isHTML5 && !support.textTracks)) {\n // Clear menu and hide\n if (\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n this.config.settings.includes('captions')\n ) {\n controls.setCaptionsMenu.call(this);\n }\n\n return;\n }\n\n // Inject the container\n if (!is.element(this.elements.captions)) {\n this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions));\n\n insertAfter(this.elements.captions, this.elements.wrapper);\n }\n\n // Fix IE captions if CORS is used\n // Fetch captions and inject as blobs instead (data URIs not supported!)\n if (browser.isIE && window.URL) {\n const elements = this.media.querySelectorAll('track');\n\n Array.from(elements).forEach((track) => {\n const src = track.getAttribute('src');\n const url = parseUrl(src);\n\n if (\n url !== null &&\n url.hostname !== window.location.href.hostname &&\n ['http:', 'https:'].includes(url.protocol)\n ) {\n fetch(src, 'blob')\n .then((blob) => {\n track.setAttribute('src', window.URL.createObjectURL(blob));\n })\n .catch(() => {\n removeElement(track);\n });\n }\n });\n }\n\n // Get and set initial data\n // The \"preferred\" options are not realized unless / until the wanted language has a match\n // * languages: Array of user's browser languages.\n // * language: The language preferred by user settings or config\n // * active: The state preferred by user settings or config\n // * toggled: The real captions state\n\n const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en'];\n const languages = dedupe(browserLanguages.map((language) => language.split('-')[0]));\n let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase();\n\n // Use first browser language when language is 'auto'\n if (language === 'auto') {\n [language] = languages;\n }\n\n let active = this.storage.get('captions');\n if (!is.boolean(active)) {\n ({ active } = this.config.captions);\n }\n\n Object.assign(this.captions, {\n toggled: false,\n active,\n language,\n languages,\n });\n\n // Watch changes to textTracks and update captions menu\n if (this.isHTML5) {\n const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack';\n on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this));\n }\n\n // Update available languages in list next tick (the event must not be triggered before the listeners)\n setTimeout(captions.update.bind(this), 0);\n },\n\n // Update available language options in settings based on tracks\n update() {\n const tracks = captions.getTracks.call(this, true);\n // Get the wanted language\n const { active, language, meta, currentTrackNode } = this.captions;\n const languageExists = Boolean(tracks.find((track) => track.language === language));\n\n // Handle tracks (add event listener and \"pseudo\"-default)\n if (this.isHTML5 && this.isVideo) {\n tracks\n .filter((track) => !meta.get(track))\n .forEach((track) => {\n this.debug.log('Track added', track);\n\n // Attempt to store if the original dom element was \"default\"\n meta.set(track, {\n default: track.mode === 'showing',\n });\n\n // Turn off native caption rendering to avoid double captions\n // Note: mode='hidden' forces a track to download. To ensure every track\n // isn't downloaded at once, only 'showing' tracks should be reassigned\n // eslint-disable-next-line no-param-reassign\n if (track.mode === 'showing') {\n // eslint-disable-next-line no-param-reassign\n track.mode = 'hidden';\n }\n\n // Add event listener for cue changes\n on.call(this, track, 'cuechange', () => captions.updateCues.call(this));\n });\n }\n\n // Update language first time it matches, or if the previous matching track was removed\n if ((languageExists && this.language !== language) || !tracks.includes(currentTrackNode)) {\n captions.setLanguage.call(this, language);\n captions.toggle.call(this, active && languageExists);\n }\n\n // Enable or disable captions based on track length\n if (this.elements) {\n toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks));\n }\n\n // Update available languages in list\n if (\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n this.config.settings.includes('captions')\n ) {\n controls.setCaptionsMenu.call(this);\n }\n },\n\n // Toggle captions display\n // Used internally for the toggleCaptions method, with the passive option forced to false\n toggle(input, passive = true) {\n // If there's no full support\n if (!this.supported.ui) {\n return;\n }\n\n const { toggled } = this.captions; // Current state\n const activeClass = this.config.classNames.captions.active;\n // Get the next state\n // If the method is called without parameter, toggle based on current value\n const active = is.nullOrUndefined(input) ? !toggled : input;\n\n // Update state and trigger event\n if (active !== toggled) {\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.active = active;\n this.storage.set({ captions: active });\n }\n\n // Force language if the call isn't passive and there is no matching language to toggle to\n if (!this.language && active && !passive) {\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true);\n\n // Override user preferences to avoid switching languages if a matching track is added\n this.captions.language = track.language;\n\n // Set caption, but don't store in localStorage as user preference\n captions.set.call(this, tracks.indexOf(track));\n return;\n }\n\n // Toggle button if it's enabled\n if (this.elements.buttons.captions) {\n this.elements.buttons.captions.pressed = active;\n }\n\n // Add class hook\n toggleClass(this.elements.container, activeClass, active);\n\n this.captions.toggled = active;\n\n // Update settings menu\n controls.updateSetting.call(this, 'captions');\n\n // Trigger event (not used internally)\n triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled');\n }\n\n // Wait for the call stack to clear before setting mode='hidden'\n // on the active track - forcing the browser to download it\n setTimeout(() => {\n if (active && this.captions.toggled) {\n this.captions.currentTrackNode.mode = 'hidden';\n }\n });\n },\n\n // Set captions by track index\n // Used internally for the currentTrack setter with the passive option forced to false\n set(index, passive = true) {\n const tracks = captions.getTracks.call(this);\n\n // Disable captions if setting to -1\n if (index === -1) {\n captions.toggle.call(this, false, passive);\n return;\n }\n\n if (!is.number(index)) {\n this.debug.warn('Invalid caption argument', index);\n return;\n }\n\n if (!(index in tracks)) {\n this.debug.warn('Track not found', index);\n return;\n }\n\n if (this.captions.currentTrack !== index) {\n this.captions.currentTrack = index;\n const track = tracks[index];\n const { language } = track || {};\n\n // Store reference to node for invalidation on remove\n this.captions.currentTrackNode = track;\n\n // Update settings menu\n controls.updateSetting.call(this, 'captions');\n\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.language = language;\n this.storage.set({ language });\n }\n\n // Handle Vimeo captions\n if (this.isVimeo) {\n this.embed.enableTextTrack(language);\n }\n\n // Trigger event\n triggerEvent.call(this, this.media, 'languagechange');\n }\n\n // Show captions\n captions.toggle.call(this, true, passive);\n\n if (this.isHTML5 && this.isVideo) {\n // If we change the active track while a cue is already displayed we need to update it\n captions.updateCues.call(this);\n }\n },\n\n // Set captions by language\n // Used internally for the language setter with the passive option forced to false\n setLanguage(input, passive = true) {\n if (!is.string(input)) {\n this.debug.warn('Invalid language argument', input);\n return;\n }\n // Normalize\n const language = input.toLowerCase();\n this.captions.language = language;\n\n // Set currentTrack\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [language]);\n captions.set.call(this, tracks.indexOf(track), passive);\n },\n\n // Get current valid caption tracks\n // If update is false it will also ignore tracks without metadata\n // This is used to \"freeze\" the language options when captions.update is false\n getTracks(update = false) {\n // Handle media or textTracks missing or null\n const tracks = Array.from((this.media || {}).textTracks || []);\n // For HTML5, use cache instead of current tracks when it exists (if captions.update is false)\n // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata)\n return tracks\n .filter((track) => !this.isHTML5 || update || this.captions.meta.has(track))\n .filter((track) => ['captions', 'subtitles'].includes(track.kind));\n },\n\n // Match tracks based on languages and get the first\n findTrack(languages, force = false) {\n const tracks = captions.getTracks.call(this);\n const sortIsDefault = (track) => Number((this.captions.meta.get(track) || {}).default);\n const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a));\n let track;\n\n languages.every((language) => {\n track = sorted.find((t) => t.language === language);\n return !track; // Break iteration if there is a match\n });\n\n // If no match is found but is required, get first\n return track || (force ? sorted[0] : undefined);\n },\n\n // Get the current track\n getCurrentTrack() {\n return captions.getTracks.call(this)[this.currentTrack];\n },\n\n // Get UI label for track\n getLabel(track) {\n let currentTrack = track;\n\n if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) {\n currentTrack = captions.getCurrentTrack.call(this);\n }\n\n if (is.track(currentTrack)) {\n if (!is.empty(currentTrack.label)) {\n return currentTrack.label;\n }\n\n if (!is.empty(currentTrack.language)) {\n return track.language.toUpperCase();\n }\n\n return i18n.get('enabled', this.config);\n }\n\n return i18n.get('disabled', this.config);\n },\n\n // Update captions using current track's active cues\n // Also optional array argument in case there isn't any track (ex: vimeo)\n updateCues(input) {\n // Requires UI\n if (!this.supported.ui) {\n return;\n }\n\n if (!is.element(this.elements.captions)) {\n this.debug.warn('No captions element to render to');\n return;\n }\n\n // Only accept array or empty input\n if (!is.nullOrUndefined(input) && !Array.isArray(input)) {\n this.debug.warn('updateCues: Invalid input', input);\n return;\n }\n\n let cues = input;\n\n // Get cues from track\n if (!cues) {\n const track = captions.getCurrentTrack.call(this);\n\n cues = Array.from((track || {}).activeCues || [])\n .map((cue) => cue.getCueAsHTML())\n .map(getHTML);\n }\n\n // Set new caption text\n const content = cues.map((cueText) => cueText.trim()).join('\\n');\n const changed = content !== this.elements.captions.innerHTML;\n\n if (changed) {\n // Empty the container and create a new child element\n emptyElement(this.elements.captions);\n const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption));\n caption.innerHTML = content;\n this.elements.captions.appendChild(caption);\n\n // Trigger event\n triggerEvent.call(this, this.media, 'cuechange');\n }\n },\n};\n\nexport default captions;\n","// ==========================================================================\n// Plyr default config\n// ==========================================================================\n\nconst defaults = {\n // Disable\n enabled: true,\n\n // Custom media title\n title: '',\n\n // Logging to console\n debug: false,\n\n // Auto play (if supported)\n autoplay: false,\n\n // Only allow one media playing at once (vimeo only)\n autopause: true,\n\n // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present)\n // TODO: Remove iosNative fullscreen option in favour of this (logic needs work)\n playsinline: true,\n\n // Default time to skip when rewind/fast forward\n seekTime: 10,\n\n // Default volume\n volume: 1,\n muted: false,\n\n // Pass a custom duration\n duration: null,\n\n // Display the media duration on load in the current time position\n // If you have opted to display both duration and currentTime, this is ignored\n displayDuration: true,\n\n // Invert the current time to be a countdown\n invertTime: true,\n\n // Clicking the currentTime inverts it's value to show time left rather than elapsed\n toggleInvert: true,\n\n // Force an aspect ratio\n // The format must be `'w:h'` (e.g. `'16:9'`)\n ratio: null,\n\n // Click video container to play/pause\n clickToPlay: true,\n\n // Auto hide the controls\n hideControls: true,\n\n // Reset to start when playback ended\n resetOnEnd: false,\n\n // Disable the standard context menu\n disableContextMenu: true,\n\n // Sprite (for icons)\n loadSprite: true,\n iconPrefix: 'plyr',\n iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg',\n\n // Blank video (used to prevent errors on source change)\n blankVideo: 'https://cdn.plyr.io/static/blank.mp4',\n\n // Quality default\n quality: {\n default: 576,\n // The options to display in the UI, if available for the source media\n options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240],\n forced: false,\n onChange: null,\n },\n\n // Set loops\n loop: {\n active: false,\n // start: null,\n // end: null,\n },\n\n // Speed default and options to display\n speed: {\n selected: 1,\n // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x)\n options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4],\n },\n\n // Keyboard shortcut settings\n keyboard: {\n focused: true,\n global: false,\n },\n\n // Display tooltips\n tooltips: {\n controls: false,\n seek: true,\n },\n\n // Captions settings\n captions: {\n active: false,\n language: 'auto',\n // Listen to new tracks added after Plyr is initialized.\n // This is needed for streaming captions, but may result in unselectable options\n update: false,\n },\n\n // Fullscreen settings\n fullscreen: {\n enabled: true, // Allow fullscreen?\n fallback: true, // Fallback using full viewport/window\n iosNative: false, // Use the native fullscreen in iOS (disables custom controls)\n // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode\n // Non-ancestors of the player element will be ignored\n // container: null, // defaults to the player element\n },\n\n // Local storage\n storage: {\n enabled: true,\n key: 'plyr',\n },\n\n // Default controls\n controls: [\n 'play-large',\n // 'restart',\n // 'rewind',\n 'play',\n // 'fast-forward',\n 'progress',\n 'current-time',\n // 'duration',\n 'mute',\n 'volume',\n 'captions',\n 'settings',\n 'pip',\n 'airplay',\n // 'download',\n 'fullscreen',\n ],\n settings: ['captions', 'quality', 'speed'],\n\n // Localisation\n i18n: {\n restart: 'Restart',\n rewind: 'Rewind {seektime}s',\n play: 'Play',\n pause: 'Pause',\n fastForward: 'Forward {seektime}s',\n seek: 'Seek',\n seekLabel: '{currentTime} of {duration}',\n played: 'Played',\n buffered: 'Buffered',\n currentTime: 'Current time',\n duration: 'Duration',\n volume: 'Volume',\n mute: 'Mute',\n unmute: 'Unmute',\n enableCaptions: 'Enable captions',\n disableCaptions: 'Disable captions',\n download: 'Download',\n enterFullscreen: 'Enter fullscreen',\n exitFullscreen: 'Exit fullscreen',\n frameTitle: 'Player for {title}',\n captions: 'Captions',\n settings: 'Settings',\n pip: 'PIP',\n menuBack: 'Go back to previous menu',\n speed: 'Speed',\n normal: 'Normal',\n quality: 'Quality',\n loop: 'Loop',\n start: 'Start',\n end: 'End',\n all: 'All',\n reset: 'Reset',\n disabled: 'Disabled',\n enabled: 'Enabled',\n advertisement: 'Ad',\n qualityBadge: {\n 2160: '4K',\n 1440: 'HD',\n 1080: 'HD',\n 720: 'HD',\n 576: 'SD',\n 480: 'SD',\n },\n },\n\n // URLs\n urls: {\n download: null,\n vimeo: {\n sdk: 'https://player.vimeo.com/api/player.js',\n iframe: 'https://player.vimeo.com/video/{0}?{1}',\n api: 'https://vimeo.com/api/oembed.json?url={0}',\n },\n youtube: {\n sdk: 'https://www.youtube.com/iframe_api',\n api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}',\n },\n googleIMA: {\n sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js',\n },\n },\n\n // Custom control listeners\n listeners: {\n seek: null,\n play: null,\n pause: null,\n restart: null,\n rewind: null,\n fastForward: null,\n mute: null,\n volume: null,\n captions: null,\n download: null,\n fullscreen: null,\n pip: null,\n airplay: null,\n speed: null,\n quality: null,\n loop: null,\n language: null,\n },\n\n // Events to watch and bubble\n events: [\n // Events to watch on HTML5 media elements and bubble\n // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events\n 'ended',\n 'progress',\n 'stalled',\n 'playing',\n 'waiting',\n 'canplay',\n 'canplaythrough',\n 'loadstart',\n 'loadeddata',\n 'loadedmetadata',\n 'timeupdate',\n 'volumechange',\n 'play',\n 'pause',\n 'error',\n 'seeking',\n 'seeked',\n 'emptied',\n 'ratechange',\n 'cuechange',\n\n // Custom events\n 'download',\n 'enterfullscreen',\n 'exitfullscreen',\n 'captionsenabled',\n 'captionsdisabled',\n 'languagechange',\n 'controlshidden',\n 'controlsshown',\n 'ready',\n\n // YouTube\n 'statechange',\n\n // Quality\n 'qualitychange',\n\n // Ads\n 'adsloaded',\n 'adscontentpause',\n 'adscontentresume',\n 'adstarted',\n 'adsmidpoint',\n 'adscomplete',\n 'adsallcomplete',\n 'adsimpression',\n 'adsclick',\n ],\n\n // Selectors\n // Change these to match your template if using custom HTML\n selectors: {\n editable: 'input, textarea, select, [contenteditable]',\n container: '.plyr',\n controls: {\n container: null,\n wrapper: '.plyr__controls',\n },\n labels: '[data-plyr]',\n buttons: {\n play: '[data-plyr=\"play\"]',\n pause: '[data-plyr=\"pause\"]',\n restart: '[data-plyr=\"restart\"]',\n rewind: '[data-plyr=\"rewind\"]',\n fastForward: '[data-plyr=\"fast-forward\"]',\n mute: '[data-plyr=\"mute\"]',\n captions: '[data-plyr=\"captions\"]',\n download: '[data-plyr=\"download\"]',\n fullscreen: '[data-plyr=\"fullscreen\"]',\n pip: '[data-plyr=\"pip\"]',\n airplay: '[data-plyr=\"airplay\"]',\n settings: '[data-plyr=\"settings\"]',\n loop: '[data-plyr=\"loop\"]',\n },\n inputs: {\n seek: '[data-plyr=\"seek\"]',\n volume: '[data-plyr=\"volume\"]',\n speed: '[data-plyr=\"speed\"]',\n language: '[data-plyr=\"language\"]',\n quality: '[data-plyr=\"quality\"]',\n },\n display: {\n currentTime: '.plyr__time--current',\n duration: '.plyr__time--duration',\n buffer: '.plyr__progress__buffer',\n loop: '.plyr__progress__loop', // Used later\n volume: '.plyr__volume--display',\n },\n progress: '.plyr__progress',\n captions: '.plyr__captions',\n caption: '.plyr__caption',\n },\n\n // Class hooks added to the player in different states\n classNames: {\n type: 'plyr--{0}',\n provider: 'plyr--{0}',\n video: 'plyr__video-wrapper',\n embed: 'plyr__video-embed',\n videoFixedRatio: 'plyr__video-wrapper--fixed-ratio',\n embedContainer: 'plyr__video-embed__container',\n poster: 'plyr__poster',\n posterEnabled: 'plyr__poster-enabled',\n ads: 'plyr__ads',\n control: 'plyr__control',\n controlPressed: 'plyr__control--pressed',\n playing: 'plyr--playing',\n paused: 'plyr--paused',\n stopped: 'plyr--stopped',\n loading: 'plyr--loading',\n hover: 'plyr--hover',\n tooltip: 'plyr__tooltip',\n cues: 'plyr__cues',\n hidden: 'plyr__sr-only',\n hideControls: 'plyr--hide-controls',\n isIos: 'plyr--is-ios',\n isTouch: 'plyr--is-touch',\n uiSupported: 'plyr--full-ui',\n noTransition: 'plyr--no-transition',\n display: {\n time: 'plyr__time',\n },\n menu: {\n value: 'plyr__menu__value',\n badge: 'plyr__badge',\n open: 'plyr--menu-open',\n },\n captions: {\n enabled: 'plyr--captions-enabled',\n active: 'plyr--captions-active',\n },\n fullscreen: {\n enabled: 'plyr--fullscreen-enabled',\n fallback: 'plyr--fullscreen-fallback',\n },\n pip: {\n supported: 'plyr--pip-supported',\n active: 'plyr--pip-active',\n },\n airplay: {\n supported: 'plyr--airplay-supported',\n active: 'plyr--airplay-active',\n },\n tabFocus: 'plyr__tab-focus',\n previewThumbnails: {\n // Tooltip thumbs\n thumbContainer: 'plyr__preview-thumb',\n thumbContainerShown: 'plyr__preview-thumb--is-shown',\n imageContainer: 'plyr__preview-thumb__image-container',\n timeContainer: 'plyr__preview-thumb__time-container',\n // Scrubbing\n scrubbingContainer: 'plyr__preview-scrubbing',\n scrubbingContainerShown: 'plyr__preview-scrubbing--is-shown',\n },\n },\n\n // Embed attributes\n attributes: {\n embed: {\n provider: 'data-plyr-provider',\n id: 'data-plyr-embed-id',\n hash: 'data-plyr-embed-hash',\n },\n },\n\n // Advertisements plugin\n // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio\n ads: {\n enabled: false,\n publisherId: '',\n tagUrl: '',\n },\n\n // Preview Thumbnails plugin\n previewThumbnails: {\n enabled: false,\n src: '',\n },\n\n // Vimeo plugin\n vimeo: {\n byline: false,\n portrait: false,\n title: false,\n speed: true,\n transparent: false,\n // Custom settings from Plyr\n customControls: true,\n referrerPolicy: null, // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy\n // Whether the owner of the video has a Pro or Business account\n // (which allows us to properly hide controls without CSS hacks, etc)\n premium: false,\n },\n\n // YouTube plugin\n youtube: {\n rel: 0, // No related vids\n showinfo: 0, // Hide info\n iv_load_policy: 3, // Hide annotations\n modestbranding: 1, // Hide logos as much as possible (they still show one in the corner when paused)\n // Custom settings from Plyr\n customControls: true,\n noCookie: false, // Whether to use an alternative version of YouTube without cookies\n },\n};\n\nexport default defaults;\n","// ==========================================================================\n// Plyr states\n// ==========================================================================\n\nexport const pip = {\n active: 'picture-in-picture',\n inactive: 'inline',\n};\n\nexport default { pip };\n","// ==========================================================================\n// Plyr supported types and providers\n// ==========================================================================\n\nexport const providers = {\n html5: 'html5',\n youtube: 'youtube',\n vimeo: 'vimeo',\n};\n\nexport const types = {\n audio: 'audio',\n video: 'video',\n};\n\n/**\n * Get provider by URL\n * @param {String} url\n */\nexport function getProviderByUrl(url) {\n // YouTube\n if (/^(https?:\\/\\/)?(www\\.)?(youtube\\.com|youtube-nocookie\\.com|youtu\\.?be)\\/.+$/.test(url)) {\n return providers.youtube;\n }\n\n // Vimeo\n if (/^https?:\\/\\/player.vimeo.com\\/video\\/\\d{0,9}(?=\\b|\\/)/.test(url)) {\n return providers.vimeo;\n }\n\n return null;\n}\n\nexport default { providers, types };\n","// ==========================================================================\n// Console wrapper\n// ==========================================================================\n\nconst noop = () => {};\n\nexport default class Console {\n constructor(enabled = false) {\n this.enabled = window.console && enabled;\n\n if (this.enabled) {\n this.log('Debugging enabled');\n }\n }\n\n get log() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.log, console) : noop;\n }\n\n get warn() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop;\n }\n\n get error() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.error, console) : noop;\n }\n}\n","// ==========================================================================\n// Fullscreen wrapper\n// https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API#prefixing\n// https://webkit.org/blog/7929/designing-websites-for-iphone-x/\n// ==========================================================================\n\nimport browser from './utils/browser';\nimport { closest, getElements, hasClass, toggleClass } from './utils/elements';\nimport { on, triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\n\nclass Fullscreen {\n constructor(player) {\n // Keep reference to parent\n this.player = player;\n\n // Get prefix\n this.prefix = Fullscreen.prefix;\n this.property = Fullscreen.property;\n\n // Scroll position\n this.scrollPosition = { x: 0, y: 0 };\n\n // Force the use of 'full window/browser' rather than fullscreen\n this.forceFallback = player.config.fullscreen.fallback === 'force';\n\n // Get the fullscreen element\n // Checks container is an ancestor, defaults to null\n this.player.elements.fullscreen =\n player.config.fullscreen.container && closest(this.player.elements.container, player.config.fullscreen.container);\n\n // Register event listeners\n // Handle event (incase user presses escape etc)\n on.call(\n this.player,\n document,\n this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`,\n () => {\n // TODO: Filter for target??\n this.onChange();\n },\n );\n\n // Fullscreen toggle on double click\n on.call(this.player, this.player.elements.container, 'dblclick', (event) => {\n // Ignore double click in controls\n if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) {\n return;\n }\n\n this.player.listeners.proxy(event, this.toggle, 'fullscreen');\n });\n\n // Tap focus when in fullscreen\n on.call(this, this.player.elements.container, 'keydown', (event) => this.trapFocus(event));\n\n // Update the UI\n this.update();\n\n // this.toggle = this.toggle.bind(this);\n }\n\n // Determine if native supported\n static get native() {\n return !!(\n document.fullscreenEnabled ||\n document.webkitFullscreenEnabled ||\n document.mozFullScreenEnabled ||\n document.msFullscreenEnabled\n );\n }\n\n // If we're actually using native\n get usingNative() {\n return Fullscreen.native && !this.forceFallback;\n }\n\n // Get the prefix for handlers\n static get prefix() {\n // No prefix\n if (is.function(document.exitFullscreen)) {\n return '';\n }\n\n // Check for fullscreen support by vendor prefix\n let value = '';\n const prefixes = ['webkit', 'moz', 'ms'];\n\n prefixes.some((pre) => {\n if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) {\n value = pre;\n return true;\n }\n\n return false;\n });\n\n return value;\n }\n\n static get property() {\n return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen';\n }\n\n // Determine if fullscreen is enabled\n get enabled() {\n return (\n (Fullscreen.native || this.player.config.fullscreen.fallback) &&\n this.player.config.fullscreen.enabled &&\n this.player.supported.ui &&\n this.player.isVideo\n );\n }\n\n // Get active state\n get active() {\n if (!this.enabled) {\n return false;\n }\n\n // Fallback using classname\n if (!Fullscreen.native || this.forceFallback) {\n return hasClass(this.target, this.player.config.classNames.fullscreen.fallback);\n }\n\n const element = !this.prefix\n ? this.target.getRootNode().fullscreenElement\n : this.target.getRootNode()[`${this.prefix}${this.property}Element`];\n\n return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target;\n }\n\n // Get target element\n get target() {\n return browser.isIos && this.player.config.fullscreen.iosNative\n ? this.player.media\n : this.player.elements.fullscreen || this.player.elements.container;\n }\n\n onChange = () => {\n if (!this.enabled) {\n return;\n }\n\n // Update toggle button\n const button = this.player.elements.buttons.fullscreen;\n if (is.element(button)) {\n button.pressed = this.active;\n }\n\n // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up\n const target = this.target === this.player.media ? this.target : this.player.elements.container;\n // Trigger an event\n triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true);\n };\n\n toggleFallback = (toggle = false) => {\n // Store or restore scroll position\n if (toggle) {\n this.scrollPosition = {\n x: window.scrollX || 0,\n y: window.scrollY || 0,\n };\n } else {\n window.scrollTo(this.scrollPosition.x, this.scrollPosition.y);\n }\n\n // Toggle scroll\n document.body.style.overflow = toggle ? 'hidden' : '';\n\n // Toggle class hook\n toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle);\n\n // Force full viewport on iPhone X+\n if (browser.isIos) {\n let viewport = document.head.querySelector('meta[name=\"viewport\"]');\n const property = 'viewport-fit=cover';\n\n // Inject the viewport meta if required\n if (!viewport) {\n viewport = document.createElement('meta');\n viewport.setAttribute('name', 'viewport');\n }\n\n // Check if the property already exists\n const hasProperty = is.string(viewport.content) && viewport.content.includes(property);\n\n if (toggle) {\n this.cleanupViewport = !hasProperty;\n\n if (!hasProperty) {\n viewport.content += `,${property}`;\n }\n } else if (this.cleanupViewport) {\n viewport.content = viewport.content\n .split(',')\n .filter((part) => part.trim() !== property)\n .join(',');\n }\n }\n\n // Toggle button and fire events\n this.onChange();\n };\n\n // Trap focus inside container\n trapFocus = (event) => {\n // Bail if iOS, not active, not the tab key\n if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) {\n return;\n }\n\n // Get the current focused element\n const focused = document.activeElement;\n const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]');\n const [first] = focusable;\n const last = focusable[focusable.length - 1];\n\n if (focused === last && !event.shiftKey) {\n // Move focus to first element that can be tabbed if Shift isn't used\n first.focus();\n event.preventDefault();\n } else if (focused === first && event.shiftKey) {\n // Move focus to last element that can be tabbed if Shift is used\n last.focus();\n event.preventDefault();\n }\n };\n\n // Update UI\n update = () => {\n if (this.enabled) {\n let mode;\n\n if (this.forceFallback) {\n mode = 'Fallback (forced)';\n } else if (Fullscreen.native) {\n mode = 'Native';\n } else {\n mode = 'Fallback';\n }\n\n this.player.debug.log(`${mode} fullscreen enabled`);\n } else {\n this.player.debug.log('Fullscreen not supported and fallback disabled');\n }\n\n // Add styling hook to show button\n toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled);\n };\n\n // Make an element fullscreen\n enter = () => {\n if (!this.enabled) {\n return;\n }\n\n // iOS native fullscreen doesn't need the request step\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n if (this.player.isVimeo) {\n this.player.embed.requestFullscreen();\n } else {\n this.target.webkitEnterFullscreen();\n }\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(true);\n } else if (!this.prefix) {\n this.target.requestFullscreen({ navigationUI: 'hide' });\n } else if (!is.empty(this.prefix)) {\n this.target[`${this.prefix}Request${this.property}`]();\n }\n };\n\n // Bail from fullscreen\n exit = () => {\n if (!this.enabled) {\n return;\n }\n\n // iOS native fullscreen\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n this.target.webkitExitFullscreen();\n silencePromise(this.player.play());\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(false);\n } else if (!this.prefix) {\n (document.cancelFullScreen || document.exitFullscreen).call(document);\n } else if (!is.empty(this.prefix)) {\n const action = this.prefix === 'moz' ? 'Cancel' : 'Exit';\n document[`${this.prefix}${action}${this.property}`]();\n }\n };\n\n // Toggle state\n toggle = () => {\n if (!this.active) {\n this.enter();\n } else {\n this.exit();\n }\n };\n}\n\nexport default Fullscreen;\n","// ==========================================================================\n// Load image avoiding xhr/fetch CORS issues\n// Server status can't be obtained this way unfortunately, so this uses \"naturalWidth\" to determine if the image has loaded\n// By default it checks if it is at least 1px, but you can add a second argument to change this\n// ==========================================================================\n\nexport default function loadImage(src, minWidth = 1) {\n return new Promise((resolve, reject) => {\n const image = new Image();\n\n const handler = () => {\n delete image.onload;\n delete image.onerror;\n (image.naturalWidth >= minWidth ? resolve : reject)(image);\n };\n\n Object.assign(image, { onload: handler, onerror: handler, src });\n });\n}\n","// ==========================================================================\n// Plyr UI\n// ==========================================================================\n\nimport captions from './captions';\nimport controls from './controls';\nimport support from './support';\nimport browser from './utils/browser';\nimport { getElement, toggleClass } from './utils/elements';\nimport { ready, triggerEvent } from './utils/events';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport loadImage from './utils/load-image';\n\nconst ui = {\n addStyleHook() {\n toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);\n toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);\n },\n\n // Toggle native HTML5 media controls\n toggleNativeControls(toggle = false) {\n if (toggle && this.isHTML5) {\n this.media.setAttribute('controls', '');\n } else {\n this.media.removeAttribute('controls');\n }\n },\n\n // Setup the UI\n build() {\n // Re-attach media element listeners\n // TODO: Use event bubbling?\n this.listeners.media();\n\n // Don't setup interface if no support\n if (!this.supported.ui) {\n this.debug.warn(`Basic support only for ${this.provider} ${this.type}`);\n\n // Restore native controls\n ui.toggleNativeControls.call(this, true);\n\n // Bail\n return;\n }\n\n // Inject custom controls if not present\n if (!is.element(this.elements.controls)) {\n // Inject custom controls\n controls.inject.call(this);\n\n // Re-attach control listeners\n this.listeners.controls();\n }\n\n // Remove native controls\n ui.toggleNativeControls.call(this);\n\n // Setup captions for HTML5\n if (this.isHTML5) {\n captions.setup.call(this);\n }\n\n // Reset volume\n this.volume = null;\n\n // Reset mute state\n this.muted = null;\n\n // Reset loop state\n this.loop = null;\n\n // Reset quality setting\n this.quality = null;\n\n // Reset speed\n this.speed = null;\n\n // Reset volume display\n controls.updateVolume.call(this);\n\n // Reset time display\n controls.timeUpdate.call(this);\n\n // Reset duration display\n controls.durationUpdate.call(this);\n\n // Update the UI\n ui.checkPlaying.call(this);\n\n // Check for picture-in-picture support\n toggleClass(\n this.elements.container,\n this.config.classNames.pip.supported,\n support.pip && this.isHTML5 && this.isVideo,\n );\n\n // Check for airplay support\n toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5);\n\n // Add iOS class\n toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos);\n\n // Add touch class\n toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch);\n\n // Ready for API calls\n this.ready = true;\n\n // Ready event at end of execution stack\n setTimeout(() => {\n triggerEvent.call(this, this.media, 'ready');\n }, 0);\n\n // Set the title\n ui.setTitle.call(this);\n\n // Assure the poster image is set, if the property was added before the element was created\n if (this.poster) {\n ui.setPoster.call(this, this.poster, false).catch(() => {});\n }\n\n // Manually set the duration if user has overridden it.\n // The event listeners for it doesn't get called if preload is disabled (#701)\n if (this.config.duration) {\n controls.durationUpdate.call(this);\n }\n },\n\n // Setup aria attribute for play and iframe title\n setTitle() {\n // Find the current text\n let label = i18n.get('play', this.config);\n\n // If there's a media title set, use that for the label\n if (is.string(this.config.title) && !is.empty(this.config.title)) {\n label += `, ${this.config.title}`;\n }\n\n // If there's a play button, set label\n Array.from(this.elements.buttons.play || []).forEach((button) => {\n button.setAttribute('aria-label', label);\n });\n\n // Set iframe title\n // https://github.com/sampotts/plyr/issues/124\n if (this.isEmbed) {\n const iframe = getElement.call(this, 'iframe');\n\n if (!is.element(iframe)) {\n return;\n }\n\n // Default to media type\n const title = !is.empty(this.config.title) ? this.config.title : 'video';\n const format = i18n.get('frameTitle', this.config);\n\n iframe.setAttribute('title', format.replace('{title}', title));\n }\n },\n\n // Toggle poster\n togglePoster(enable) {\n toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);\n },\n\n // Set the poster image (async)\n // Used internally for the poster setter, with the passive option forced to false\n setPoster(poster, passive = true) {\n // Don't override if call is passive\n if (passive && this.poster) {\n return Promise.reject(new Error('Poster already set'));\n }\n\n // Set property synchronously to respect the call order\n this.media.setAttribute('data-poster', poster);\n\n // Show the poster\n this.elements.poster.removeAttribute('hidden');\n\n // Wait until ui is ready\n return (\n ready\n .call(this)\n // Load image\n .then(() => loadImage(poster))\n .catch((error) => {\n // Hide poster on error unless it's been set by another call\n if (poster === this.poster) {\n ui.togglePoster.call(this, false);\n }\n // Rethrow\n throw error;\n })\n .then(() => {\n // Prevent race conditions\n if (poster !== this.poster) {\n throw new Error('setPoster cancelled by later call to setPoster');\n }\n })\n .then(() => {\n Object.assign(this.elements.poster.style, {\n backgroundImage: `url('${poster}')`,\n // Reset backgroundSize as well (since it can be set to \"cover\" for padded thumbnails for youtube)\n backgroundSize: '',\n });\n\n ui.togglePoster.call(this, true);\n\n return poster;\n })\n );\n },\n\n // Check playing state\n checkPlaying(event) {\n // Class hooks\n toggleClass(this.elements.container, this.config.classNames.playing, this.playing);\n toggleClass(this.elements.container, this.config.classNames.paused, this.paused);\n toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped);\n\n // Set state\n Array.from(this.elements.buttons.play || []).forEach((target) => {\n Object.assign(target, { pressed: this.playing });\n target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config));\n });\n\n // Only update controls on non timeupdate events\n if (is.event(event) && event.type === 'timeupdate') {\n return;\n }\n\n // Toggle controls\n ui.toggleControls.call(this);\n },\n\n // Check if media is loading\n checkLoading(event) {\n this.loading = ['stalled', 'waiting'].includes(event.type);\n\n // Clear timer\n clearTimeout(this.timers.loading);\n\n // Timer to prevent flicker when seeking\n this.timers.loading = setTimeout(\n () => {\n // Update progress bar loading class state\n toggleClass(this.elements.container, this.config.classNames.loading, this.loading);\n\n // Update controls visibility\n ui.toggleControls.call(this);\n },\n this.loading ? 250 : 0,\n );\n },\n\n // Toggle controls based on state and `force` argument\n toggleControls(force) {\n const { controls: controlsElement } = this.elements;\n\n if (controlsElement && this.config.hideControls) {\n // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.)\n const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now();\n\n // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide\n this.toggleControls(\n Boolean(\n force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek,\n ),\n );\n }\n },\n\n // Migrate any custom properties from the media to the parent\n migrateStyles() {\n // Loop through values (as they are the keys when the object is spread 🤔)\n Object.values({ ...this.media.style })\n // We're only fussed about Plyr specific properties\n .filter((key) => !is.empty(key) && is.string(key) && key.startsWith('--plyr'))\n .forEach((key) => {\n // Set on the container\n this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key));\n\n // Clean up from media element\n this.media.style.removeProperty(key);\n });\n\n // Remove attribute if empty\n if (is.empty(this.media.style)) {\n this.media.removeAttribute('style');\n }\n },\n};\n\nexport default ui;\n","// ==========================================================================\n// Plyr Event Listeners\n// ==========================================================================\n\nimport controls from './controls';\nimport ui from './ui';\nimport { repaint } from './utils/animation';\nimport browser from './utils/browser';\nimport { getElement, getElements, matches, toggleClass } from './utils/elements';\nimport { off, on, once, toggleListener, triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\nimport { getAspectRatio, getViewportSize, supportsCSS } from './utils/style';\n\nclass Listeners {\n constructor(player) {\n this.player = player;\n this.lastKey = null;\n this.focusTimer = null;\n this.lastKeyDown = null;\n\n this.handleKey = this.handleKey.bind(this);\n this.toggleMenu = this.toggleMenu.bind(this);\n this.setTabFocus = this.setTabFocus.bind(this);\n this.firstTouch = this.firstTouch.bind(this);\n }\n\n // Handle key presses\n handleKey(event) {\n const { player } = this;\n const { elements } = player;\n const code = event.keyCode ? event.keyCode : event.which;\n const pressed = event.type === 'keydown';\n const repeat = pressed && code === this.lastKey;\n\n // Bail if a modifier key is set\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {\n return;\n }\n\n // If the event is bubbled from the media element\n // Firefox doesn't get the keycode for whatever reason\n if (!is.number(code)) {\n return;\n }\n\n // Seek by the number keys\n const seekByKey = () => {\n // Divide the max duration into 10th's and times by the number value\n player.currentTime = (player.duration / 10) * (code - 48);\n };\n\n // Handle the key on keydown\n // Reset on keyup\n if (pressed) {\n // Check focused element\n // and if the focused element is not editable (e.g. text input)\n // and any that accept key input http://webaim.org/techniques/keyboard/\n const focused = document.activeElement;\n if (is.element(focused)) {\n const { editable } = player.config.selectors;\n const { seek } = elements.inputs;\n\n if (focused !== seek && matches(focused, editable)) {\n return;\n }\n\n if (event.which === 32 && matches(focused, 'button, [role^=\"menuitem\"]')) {\n return;\n }\n }\n\n // Which keycodes should we prevent default\n const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79];\n\n // If the code is found prevent default (e.g. prevent scrolling for arrows)\n if (preventDefault.includes(code)) {\n event.preventDefault();\n event.stopPropagation();\n }\n\n switch (code) {\n case 48:\n case 49:\n case 50:\n case 51:\n case 52:\n case 53:\n case 54:\n case 55:\n case 56:\n case 57:\n // 0-9\n if (!repeat) {\n seekByKey();\n }\n break;\n\n case 32:\n case 75:\n // Space and K key\n if (!repeat) {\n silencePromise(player.togglePlay());\n }\n break;\n\n case 38:\n // Arrow up\n player.increaseVolume(0.1);\n break;\n\n case 40:\n // Arrow down\n player.decreaseVolume(0.1);\n break;\n\n case 77:\n // M key\n if (!repeat) {\n player.muted = !player.muted;\n }\n break;\n\n case 39:\n // Arrow forward\n player.forward();\n break;\n\n case 37:\n // Arrow back\n player.rewind();\n break;\n\n case 70:\n // F key\n player.fullscreen.toggle();\n break;\n\n case 67:\n // C key\n if (!repeat) {\n player.toggleCaptions();\n }\n break;\n\n case 76:\n // L key\n player.loop = !player.loop;\n break;\n\n /* case 73:\n this.setLoop('start');\n break;\n\n case 76:\n this.setLoop();\n break;\n\n case 79:\n this.setLoop('end');\n break; */\n\n default:\n break;\n }\n\n // Escape is handle natively when in full screen\n // So we only need to worry about non native\n if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) {\n player.fullscreen.toggle();\n }\n\n // Store last code for next cycle\n this.lastKey = code;\n } else {\n this.lastKey = null;\n }\n }\n\n // Toggle menu\n toggleMenu(event) {\n controls.toggleMenu.call(this.player, event);\n }\n\n // Device is touch enabled\n firstTouch = () => {\n const { player } = this;\n const { elements } = player;\n\n player.touch = true;\n\n // Add touch class\n toggleClass(elements.container, player.config.classNames.isTouch, true);\n };\n\n setTabFocus = (event) => {\n const { player } = this;\n const { elements } = player;\n\n clearTimeout(this.focusTimer);\n\n // Ignore any key other than tab\n if (event.type === 'keydown' && event.which !== 9) {\n return;\n }\n\n // Store reference to event timeStamp\n if (event.type === 'keydown') {\n this.lastKeyDown = event.timeStamp;\n }\n\n // Remove current classes\n const removeCurrent = () => {\n const className = player.config.classNames.tabFocus;\n const current = getElements.call(player, `.${className}`);\n toggleClass(current, className, false);\n };\n\n // Determine if a key was pressed to trigger this event\n const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20;\n\n // Ignore focus events if a key was pressed prior\n if (event.type === 'focus' && !wasKeyDown) {\n return;\n }\n\n // Remove all current\n removeCurrent();\n\n // Delay the adding of classname until the focus has changed\n // This event fires before the focusin event\n if (event.type !== 'focusout') {\n this.focusTimer = setTimeout(() => {\n const focused = document.activeElement;\n\n // Ignore if current focus element isn't inside the player\n if (!elements.container.contains(focused)) {\n return;\n }\n\n toggleClass(document.activeElement, player.config.classNames.tabFocus, true);\n }, 10);\n }\n };\n\n // Global window & document listeners\n global = (toggle = true) => {\n const { player } = this;\n\n // Keyboard shortcuts\n if (player.config.keyboard.global) {\n toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false);\n }\n\n // Click anywhere closes menu\n toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle);\n\n // Detect touch by events\n once.call(player, document.body, 'touchstart', this.firstTouch);\n\n // Tab focus detection\n toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true);\n };\n\n // Container listeners\n container = () => {\n const { player } = this;\n const { config, elements, timers } = player;\n\n // Keyboard shortcuts\n if (!config.keyboard.global && config.keyboard.focused) {\n on.call(player, elements.container, 'keydown keyup', this.handleKey, false);\n }\n\n // Toggle controls on mouse events and entering fullscreen\n on.call(\n player,\n elements.container,\n 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen',\n (event) => {\n const { controls: controlsElement } = elements;\n\n // Remove button states for fullscreen\n if (controlsElement && event.type === 'enterfullscreen') {\n controlsElement.pressed = false;\n controlsElement.hover = false;\n }\n\n // Show, then hide after a timeout unless another control event occurs\n const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type);\n let delay = 0;\n\n if (show) {\n ui.toggleControls.call(player, true);\n // Use longer timeout for touch devices\n delay = player.touch ? 3000 : 2000;\n }\n\n // Clear timer\n clearTimeout(timers.controls);\n\n // Set new timer to prevent flicker when seeking\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n },\n );\n\n // Set a gutter for Vimeo\n const setGutter = () => {\n if (!player.isVimeo || player.config.vimeo.premium) {\n return;\n }\n\n const target = elements.wrapper;\n const { active } = player.fullscreen;\n const [videoWidth, videoHeight] = getAspectRatio.call(player);\n const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`);\n\n // If not active, remove styles\n if (!active) {\n if (useNativeAspectRatio) {\n target.style.width = null;\n target.style.height = null;\n } else {\n target.style.maxWidth = null;\n target.style.margin = null;\n }\n return;\n }\n\n // Determine which dimension will overflow and constrain view\n const [viewportWidth, viewportHeight] = getViewportSize();\n const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight;\n\n if (useNativeAspectRatio) {\n target.style.width = overflow ? 'auto' : '100%';\n target.style.height = overflow ? '100%' : 'auto';\n } else {\n target.style.maxWidth = overflow ? `${(viewportHeight / videoHeight) * videoWidth}px` : null;\n target.style.margin = overflow ? '0 auto' : null;\n }\n };\n\n // Handle resizing\n const resized = () => {\n clearTimeout(timers.resized);\n timers.resized = setTimeout(setGutter, 50);\n };\n\n on.call(player, elements.container, 'enterfullscreen exitfullscreen', (event) => {\n const { target } = player.fullscreen;\n\n // Ignore events not from target\n if (target !== elements.container) {\n return;\n }\n\n // If it's not an embed and no ratio specified\n if (!player.isEmbed && is.empty(player.config.ratio)) {\n return;\n }\n\n // Set Vimeo gutter\n setGutter();\n\n // Watch for resizes\n const method = event.type === 'enterfullscreen' ? on : off;\n method.call(player, window, 'resize', resized);\n });\n };\n\n // Listen for media events\n media = () => {\n const { player } = this;\n const { elements } = player;\n\n // Time change on media\n on.call(player, player.media, 'timeupdate seeking seeked', (event) => controls.timeUpdate.call(player, event));\n\n // Display duration\n on.call(player, player.media, 'durationchange loadeddata loadedmetadata', (event) =>\n controls.durationUpdate.call(player, event),\n );\n\n // Handle the media finishing\n on.call(player, player.media, 'ended', () => {\n // Show poster on end\n if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) {\n // Restart\n player.restart();\n\n // Call pause otherwise IE11 will start playing the video again\n player.pause();\n }\n });\n\n // Check for buffer progress\n on.call(player, player.media, 'progress playing seeking seeked', (event) =>\n controls.updateProgress.call(player, event),\n );\n\n // Handle volume changes\n on.call(player, player.media, 'volumechange', (event) => controls.updateVolume.call(player, event));\n\n // Handle play/pause\n on.call(player, player.media, 'playing play pause ended emptied timeupdate', (event) =>\n ui.checkPlaying.call(player, event),\n );\n\n // Loading state\n on.call(player, player.media, 'waiting canplay seeked playing', (event) => ui.checkLoading.call(player, event));\n\n // Click video\n if (player.supported.ui && player.config.clickToPlay && !player.isAudio) {\n // Re-fetch the wrapper\n const wrapper = getElement.call(player, `.${player.config.classNames.video}`);\n\n // Bail if there's no wrapper (this should never happen)\n if (!is.element(wrapper)) {\n return;\n }\n\n // On click play, pause or restart\n on.call(player, elements.container, 'click', (event) => {\n const targets = [elements.container, wrapper];\n\n // Ignore if click if not container or in video wrapper\n if (!targets.includes(event.target) && !wrapper.contains(event.target)) {\n return;\n }\n\n // Touch devices will just show controls (if hidden)\n if (player.touch && player.config.hideControls) {\n return;\n }\n\n if (player.ended) {\n this.proxy(event, player.restart, 'restart');\n this.proxy(\n event,\n () => {\n silencePromise(player.play());\n },\n 'play',\n );\n } else {\n this.proxy(\n event,\n () => {\n silencePromise(player.togglePlay());\n },\n 'play',\n );\n }\n });\n }\n\n // Disable right click\n if (player.supported.ui && player.config.disableContextMenu) {\n on.call(\n player,\n elements.wrapper,\n 'contextmenu',\n (event) => {\n event.preventDefault();\n },\n false,\n );\n }\n\n // Volume change\n on.call(player, player.media, 'volumechange', () => {\n // Save to storage\n player.storage.set({\n volume: player.volume,\n muted: player.muted,\n });\n });\n\n // Speed change\n on.call(player, player.media, 'ratechange', () => {\n // Update UI\n controls.updateSetting.call(player, 'speed');\n\n // Save to storage\n player.storage.set({ speed: player.speed });\n });\n\n // Quality change\n on.call(player, player.media, 'qualitychange', (event) => {\n // Update UI\n controls.updateSetting.call(player, 'quality', null, event.detail.quality);\n });\n\n // Update download link when ready and if quality changes\n on.call(player, player.media, 'ready qualitychange', () => {\n controls.setDownloadUrl.call(player);\n });\n\n // Proxy events to container\n // Bubble up key events for Edge\n const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' ');\n\n on.call(player, player.media, proxyEvents, (event) => {\n let { detail = {} } = event;\n\n // Get error details from media\n if (event.type === 'error') {\n detail = player.media.error;\n }\n\n triggerEvent.call(player, elements.container, event.type, true, detail);\n });\n };\n\n // Run default and custom handlers\n proxy = (event, defaultHandler, customHandlerKey) => {\n const { player } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n let returned = true;\n\n // Execute custom handler\n if (hasCustomHandler) {\n returned = customHandler.call(player, event);\n }\n\n // Only call default handler if not prevented in custom handler\n if (returned !== false && is.function(defaultHandler)) {\n defaultHandler.call(player, event);\n }\n };\n\n // Trigger custom and default handlers\n bind = (element, type, defaultHandler, customHandlerKey, passive = true) => {\n const { player } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n\n on.call(\n player,\n element,\n type,\n (event) => this.proxy(event, defaultHandler, customHandlerKey),\n passive && !hasCustomHandler,\n );\n };\n\n // Listen for control events\n controls = () => {\n const { player } = this;\n const { elements } = player;\n // IE doesn't support input event, so we fallback to change\n const inputEvent = browser.isIE ? 'change' : 'input';\n\n // Play/pause toggle\n if (elements.buttons.play) {\n Array.from(elements.buttons.play).forEach((button) => {\n this.bind(\n button,\n 'click',\n () => {\n silencePromise(player.togglePlay());\n },\n 'play',\n );\n });\n }\n\n // Pause\n this.bind(elements.buttons.restart, 'click', player.restart, 'restart');\n\n // Rewind\n this.bind(\n elements.buttons.rewind,\n 'click',\n () => {\n // Record seek time so we can prevent hiding controls for a few seconds after rewind\n player.lastSeekTime = Date.now();\n player.rewind();\n },\n 'rewind',\n );\n\n // Rewind\n this.bind(\n elements.buttons.fastForward,\n 'click',\n () => {\n // Record seek time so we can prevent hiding controls for a few seconds after fast forward\n player.lastSeekTime = Date.now();\n player.forward();\n },\n 'fastForward',\n );\n\n // Mute toggle\n this.bind(\n elements.buttons.mute,\n 'click',\n () => {\n player.muted = !player.muted;\n },\n 'mute',\n );\n\n // Captions toggle\n this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions());\n\n // Download\n this.bind(\n elements.buttons.download,\n 'click',\n () => {\n triggerEvent.call(player, player.media, 'download');\n },\n 'download',\n );\n\n // Fullscreen toggle\n this.bind(\n elements.buttons.fullscreen,\n 'click',\n () => {\n player.fullscreen.toggle();\n },\n 'fullscreen',\n );\n\n // Picture-in-Picture\n this.bind(\n elements.buttons.pip,\n 'click',\n () => {\n player.pip = 'toggle';\n },\n 'pip',\n );\n\n // Airplay\n this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay');\n\n // Settings menu - click toggle\n this.bind(\n elements.buttons.settings,\n 'click',\n (event) => {\n // Prevent the document click listener closing the menu\n event.stopPropagation();\n event.preventDefault();\n\n controls.toggleMenu.call(player, event);\n },\n null,\n false,\n ); // Can't be passive as we're preventing default\n\n // Settings menu - keyboard toggle\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n this.bind(\n elements.buttons.settings,\n 'keyup',\n (event) => {\n const code = event.which;\n\n // We only care about space and return\n if (![13, 32].includes(code)) {\n return;\n }\n\n // Because return triggers a click anyway, all we need to do is set focus\n if (code === 13) {\n controls.focusFirstMenuItem.call(player, null, true);\n return;\n }\n\n // Prevent scroll\n event.preventDefault();\n\n // Prevent playing video (Firefox)\n event.stopPropagation();\n\n // Toggle menu\n controls.toggleMenu.call(player, event);\n },\n null,\n false, // Can't be passive as we're preventing default\n );\n\n // Escape closes menu\n this.bind(elements.settings.menu, 'keydown', (event) => {\n if (event.which === 27) {\n controls.toggleMenu.call(player, event);\n }\n });\n\n // Set range input alternative \"value\", which matches the tooltip time (#954)\n this.bind(elements.inputs.seek, 'mousedown mousemove', (event) => {\n const rect = elements.progress.getBoundingClientRect();\n const percent = (100 / rect.width) * (event.pageX - rect.left);\n event.currentTarget.setAttribute('seek-value', percent);\n });\n\n // Pause while seeking\n this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', (event) => {\n const seek = event.currentTarget;\n const code = event.keyCode ? event.keyCode : event.which;\n const attribute = 'play-on-seeked';\n\n if (is.keyboardEvent(event) && code !== 39 && code !== 37) {\n return;\n }\n\n // Record seek time so we can prevent hiding controls for a few seconds after seek\n player.lastSeekTime = Date.now();\n\n // Was playing before?\n const play = seek.hasAttribute(attribute);\n // Done seeking\n const done = ['mouseup', 'touchend', 'keyup'].includes(event.type);\n\n // If we're done seeking and it was playing, resume playback\n if (play && done) {\n seek.removeAttribute(attribute);\n silencePromise(player.play());\n } else if (!done && player.playing) {\n seek.setAttribute(attribute, '');\n player.pause();\n }\n });\n\n // Fix range inputs on iOS\n // Super weird iOS bug where after you interact with an <input type=\"range\">,\n // it takes over further interactions on the page. This is a hack\n if (browser.isIos) {\n const inputs = getElements.call(player, 'input[type=\"range\"]');\n Array.from(inputs).forEach((input) => this.bind(input, inputEvent, (event) => repaint(event.target)));\n }\n\n // Seek\n this.bind(\n elements.inputs.seek,\n inputEvent,\n (event) => {\n const seek = event.currentTarget;\n // If it exists, use seek-value instead of \"value\" for consistency with tooltip time (#954)\n let seekTo = seek.getAttribute('seek-value');\n\n if (is.empty(seekTo)) {\n seekTo = seek.value;\n }\n\n seek.removeAttribute('seek-value');\n\n player.currentTime = (seekTo / seek.max) * player.duration;\n },\n 'seek',\n );\n\n // Seek tooltip\n this.bind(elements.progress, 'mouseenter mouseleave mousemove', (event) =>\n controls.updateSeekTooltip.call(player, event),\n );\n\n // Preview thumbnails plugin\n // TODO: Really need to work on some sort of plug-in wide event bus or pub-sub for this\n this.bind(elements.progress, 'mousemove touchmove', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startMove(event);\n }\n });\n\n // Hide thumbnail preview - on mouse click, mouse leave, and video play/seek. All four are required, e.g., for buffering\n this.bind(elements.progress, 'mouseleave touchend click', () => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endMove(false, true);\n }\n });\n\n // Show scrubbing preview\n this.bind(elements.progress, 'mousedown touchstart', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startScrubbing(event);\n }\n });\n\n this.bind(elements.progress, 'mouseup touchend', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endScrubbing(event);\n }\n });\n\n // Polyfill for lower fill in <input type=\"range\"> for webkit\n if (browser.isWebkit) {\n Array.from(getElements.call(player, 'input[type=\"range\"]')).forEach((element) => {\n this.bind(element, 'input', (event) => controls.updateRangeFill.call(player, event.target));\n });\n }\n\n // Current time invert\n // Only if one time element is used for both currentTime and duration\n if (player.config.toggleInvert && !is.element(elements.display.duration)) {\n this.bind(elements.display.currentTime, 'click', () => {\n // Do nothing if we're at the start\n if (player.currentTime === 0) {\n return;\n }\n\n player.config.invertTime = !player.config.invertTime;\n\n controls.timeUpdate.call(player);\n });\n }\n\n // Volume\n this.bind(\n elements.inputs.volume,\n inputEvent,\n (event) => {\n player.volume = event.target.value;\n },\n 'volume',\n );\n\n // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting)\n this.bind(elements.controls, 'mouseenter mouseleave', (event) => {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n });\n\n // Also update controls.hover state for any non-player children of fullscreen element (as above)\n if (elements.fullscreen) {\n Array.from(elements.fullscreen.children)\n .filter((c) => !c.contains(elements.container))\n .forEach((child) => {\n this.bind(child, 'mouseenter mouseleave', (event) => {\n if (elements.controls) {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }\n });\n });\n }\n\n // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting)\n this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', (event) => {\n elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type);\n });\n\n // Show controls when they receive focus (e.g., when using keyboard tab key)\n this.bind(elements.controls, 'focusin', () => {\n const { config, timers } = player;\n\n // Skip transition to prevent focus from scrolling the parent element\n toggleClass(elements.controls, config.classNames.noTransition, true);\n\n // Toggle\n ui.toggleControls.call(player, true);\n\n // Restore transition\n setTimeout(() => {\n toggleClass(elements.controls, config.classNames.noTransition, false);\n }, 0);\n\n // Delay a little more for mouse users\n const delay = this.touch ? 3000 : 4000;\n\n // Clear timer\n clearTimeout(timers.controls);\n\n // Hide again after delay\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n });\n\n // Mouse wheel for volume\n this.bind(\n elements.inputs.volume,\n 'wheel',\n (event) => {\n // Detect \"natural\" scroll - suppored on OS X Safari only\n // Other browsers on OS X will be inverted until support improves\n const inverted = event.webkitDirectionInvertedFromDevice;\n // Get delta from event. Invert if `inverted` is true\n const [x, y] = [event.deltaX, -event.deltaY].map((value) => (inverted ? -value : value));\n // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta)\n const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y);\n\n // Change the volume by 2%\n player.increaseVolume(direction / 50);\n\n // Don't break page scrolling at max and min\n const { volume } = player.media;\n if ((direction === 1 && volume < 1) || (direction === -1 && volume > 0)) {\n event.preventDefault();\n }\n },\n 'volume',\n false,\n );\n };\n}\n\nexport default Listeners;\n","(function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n define([], factory);\n } else if (typeof exports === 'object') {\n module.exports = factory();\n } else {\n root.loadjs = factory();\n }\n}(this, function() {\n/**\n * Global dependencies.\n * @global {Object} document - DOM\n */\n\nvar devnull = function() {},\n bundleIdCache = {},\n bundleResultCache = {},\n bundleCallbackQueue = {};\n\n\n/**\n * Subscribe to bundle load event.\n * @param {string[]} bundleIds - Bundle ids\n * @param {Function} callbackFn - The callback function\n */\nfunction subscribe(bundleIds, callbackFn) {\n // listify\n bundleIds = bundleIds.push ? bundleIds : [bundleIds];\n\n var depsNotFound = [],\n i = bundleIds.length,\n numWaiting = i,\n fn,\n bundleId,\n r,\n q;\n\n // define callback function\n fn = function (bundleId, pathsNotFound) {\n if (pathsNotFound.length) depsNotFound.push(bundleId);\n\n numWaiting--;\n if (!numWaiting) callbackFn(depsNotFound);\n };\n\n // register callback\n while (i--) {\n bundleId = bundleIds[i];\n\n // execute callback if in result cache\n r = bundleResultCache[bundleId];\n if (r) {\n fn(bundleId, r);\n continue;\n }\n\n // add to callback queue\n q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];\n q.push(fn);\n }\n}\n\n\n/**\n * Publish bundle load event.\n * @param {string} bundleId - Bundle id\n * @param {string[]} pathsNotFound - List of files not found\n */\nfunction publish(bundleId, pathsNotFound) {\n // exit if id isn't defined\n if (!bundleId) return;\n\n var q = bundleCallbackQueue[bundleId];\n\n // cache result\n bundleResultCache[bundleId] = pathsNotFound;\n\n // exit if queue is empty\n if (!q) return;\n\n // empty callback queue\n while (q.length) {\n q[0](bundleId, pathsNotFound);\n q.splice(0, 1);\n }\n}\n\n\n/**\n * Execute callbacks.\n * @param {Object or Function} args - The callback args\n * @param {string[]} depsNotFound - List of dependencies not found\n */\nfunction executeCallbacks(args, depsNotFound) {\n // accept function as argument\n if (args.call) args = {success: args};\n\n // success and error callbacks\n if (depsNotFound.length) (args.error || devnull)(depsNotFound);\n else (args.success || devnull)(args);\n}\n\n\n/**\n * Load individual file.\n * @param {string} path - The file path\n * @param {Function} callbackFn - The callback function\n */\nfunction loadFile(path, callbackFn, args, numTries) {\n var doc = document,\n async = args.async,\n maxTries = (args.numRetries || 0) + 1,\n beforeCallbackFn = args.before || devnull,\n pathname = path.replace(/[\\?|#].*$/, ''),\n pathStripped = path.replace(/^(css|img)!/, ''),\n isLegacyIECss,\n e;\n\n numTries = numTries || 0;\n\n if (/(^css!|\\.css$)/.test(pathname)) {\n // css\n e = doc.createElement('link');\n e.rel = 'stylesheet';\n e.href = pathStripped;\n\n // tag IE9+\n isLegacyIECss = 'hideFocus' in e;\n\n // use preload in IE Edge (to detect load errors)\n if (isLegacyIECss && e.relList) {\n isLegacyIECss = 0;\n e.rel = 'preload';\n e.as = 'style';\n }\n } else if (/(^img!|\\.(png|gif|jpg|svg|webp)$)/.test(pathname)) {\n // image\n e = doc.createElement('img');\n e.src = pathStripped; \n } else {\n // javascript\n e = doc.createElement('script');\n e.src = path;\n e.async = async === undefined ? true : async;\n }\n\n e.onload = e.onerror = e.onbeforeload = function (ev) {\n var result = ev.type[0];\n\n // treat empty stylesheets as failures to get around lack of onerror\n // support in IE9-11\n if (isLegacyIECss) {\n try {\n if (!e.sheet.cssText.length) result = 'e';\n } catch (x) {\n // sheets objects created from load errors don't allow access to\n // `cssText` (unless error is Code:18 SecurityError)\n if (x.code != 18) result = 'e';\n }\n }\n\n // handle retries in case of load failure\n if (result == 'e') {\n // increment counter\n numTries += 1;\n\n // exit function and try again\n if (numTries < maxTries) {\n return loadFile(path, callbackFn, args, numTries);\n }\n } else if (e.rel == 'preload' && e.as == 'style') {\n // activate preloaded stylesheets\n return e.rel = 'stylesheet'; // jshint ignore:line\n }\n \n // execute callback\n callbackFn(path, result, ev.defaultPrevented);\n };\n\n // add to document (unless callback returns `false`)\n if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);\n}\n\n\n/**\n * Load multiple files.\n * @param {string[]} paths - The file paths\n * @param {Function} callbackFn - The callback function\n */\nfunction loadFiles(paths, callbackFn, args) {\n // listify paths\n paths = paths.push ? paths : [paths];\n\n var numWaiting = paths.length,\n x = numWaiting,\n pathsNotFound = [],\n fn,\n i;\n\n // define callback function\n fn = function(path, result, defaultPrevented) {\n // handle error\n if (result == 'e') pathsNotFound.push(path);\n\n // handle beforeload event. If defaultPrevented then that means the load\n // will be blocked (ex. Ghostery/ABP on Safari)\n if (result == 'b') {\n if (defaultPrevented) pathsNotFound.push(path);\n else return;\n }\n\n numWaiting--;\n if (!numWaiting) callbackFn(pathsNotFound);\n };\n\n // load scripts\n for (i=0; i < x; i++) loadFile(paths[i], fn, args);\n}\n\n\n/**\n * Initiate script load and register bundle.\n * @param {(string|string[])} paths - The file paths\n * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success\n * callback or (3) object literal with success/error arguments, numRetries,\n * etc.\n * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object\n * literal with success/error arguments, numRetries, etc.\n */\nfunction loadjs(paths, arg1, arg2) {\n var bundleId,\n args;\n\n // bundleId (if string)\n if (arg1 && arg1.trim) bundleId = arg1;\n\n // args (default is {})\n args = (bundleId ? arg2 : arg1) || {};\n\n // throw error if bundle is already defined\n if (bundleId) {\n if (bundleId in bundleIdCache) {\n throw \"LoadJS\";\n } else {\n bundleIdCache[bundleId] = true;\n }\n }\n\n function loadFn(resolve, reject) {\n loadFiles(paths, function (pathsNotFound) {\n // execute callbacks\n executeCallbacks(args, pathsNotFound);\n \n // resolve Promise\n if (resolve) {\n executeCallbacks({success: resolve, error: reject}, pathsNotFound);\n }\n\n // publish bundle load event\n publish(bundleId, pathsNotFound);\n }, args);\n }\n \n if (args.returnPromise) return new Promise(loadFn);\n else loadFn();\n}\n\n\n/**\n * Execute callbacks when dependencies have been satisfied.\n * @param {(string|string[])} deps - List of bundle ids\n * @param {Object} args - success/error arguments\n */\nloadjs.ready = function ready(deps, args) {\n // subscribe to bundle load event\n subscribe(deps, function (depsNotFound) {\n // execute callbacks\n executeCallbacks(args, depsNotFound);\n });\n\n return loadjs;\n};\n\n\n/**\n * Manually satisfy bundle dependencies.\n * @param {string} bundleId - The bundle id\n */\nloadjs.done = function done(bundleId) {\n publish(bundleId, []);\n};\n\n\n/**\n * Reset loadjs dependencies statuses\n */\nloadjs.reset = function reset() {\n bundleIdCache = {};\n bundleResultCache = {};\n bundleCallbackQueue = {};\n};\n\n\n/**\n * Determine if bundle has already been defined\n * @param String} bundleId - The bundle id\n */\nloadjs.isDefined = function isDefined(bundleId) {\n return bundleId in bundleIdCache;\n};\n\n\n// export\nreturn loadjs;\n\n}));\n","// ==========================================================================\n// Load an external script\n// ==========================================================================\n\nimport loadjs from 'loadjs';\n\nexport default function loadScript(url) {\n return new Promise((resolve, reject) => {\n loadjs(url, {\n success: resolve,\n error: reject,\n });\n });\n}\n","// ==========================================================================\n// Vimeo plugin\n// ==========================================================================\n\nimport captions from '../captions';\nimport controls from '../controls';\nimport ui from '../ui';\nimport { createElement, replaceElement, toggleClass } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport loadScript from '../utils/load-script';\nimport { format, stripHTML } from '../utils/strings';\nimport { roundAspectRatio, setAspectRatio } from '../utils/style';\nimport { buildUrlParams } from '../utils/urls';\n\n// Parse Vimeo ID from URL\nfunction parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n if (is.number(Number(url))) {\n return url;\n }\n\n const regex = /^.*(vimeo.com\\/|video\\/)(\\d+).*/;\n return url.match(regex) ? RegExp.$2 : url;\n}\n\n// Try to extract a hash for private videos from the URL\nfunction parseHash(url) {\n /* This regex matches a hexadecimal hash if given in any of these forms:\n * - [https://player.]vimeo.com/video/{id}/{hash}[?params]\n * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms]\n * - [https://player.]vimeo.com/video/{id}?[params]&h={hash}\n * - video/{id}/{hash}\n * If matched, the hash is available in the named group `hash`\n */\n const regex = /^.*(?:vimeo.com\\/|video\\/)(?:\\d+)(?:\\?.*&*h=|\\/)+(?<hash>[\\d,a-f]+)/;\n const found = url.match(regex);\n\n return found ? found.groups.hash : null;\n}\n\n// Set playback state and trigger change (only on actual change)\nfunction assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nconst vimeo = {\n setup() {\n const player = this;\n\n // Add embed class for responsive\n toggleClass(player.elements.wrapper, player.config.classNames.embed, true);\n\n // Set speed options from config\n player.options.speed = player.config.speed.options;\n\n // Set intial ratio\n setAspectRatio.call(player);\n\n // Load the SDK if not already\n if (!is.object(window.Vimeo)) {\n loadScript(player.config.urls.vimeo.sdk)\n .then(() => {\n vimeo.ready.call(player);\n })\n .catch((error) => {\n player.debug.warn('Vimeo SDK (player.js) failed to load', error);\n });\n } else {\n vimeo.ready.call(player);\n }\n },\n\n // API Ready\n ready() {\n const player = this;\n const config = player.config.vimeo;\n const { premium, referrerPolicy, ...frameParams } = config;\n // Get the source URL or ID\n let source = player.media.getAttribute('src');\n let hash = '';\n // Get from <div> if needed\n if (is.empty(source)) {\n source = player.media.getAttribute(player.config.attributes.embed.id);\n // hash can also be set as attribute on the <div>\n hash = player.media.getAttribute(player.config.attributes.embed.hash);\n } else {\n hash = parseHash(source);\n }\n const hashParam = hash ? { h: hash } : {};\n\n // If the owner has a pro or premium account then we can hide controls etc\n if (premium) {\n Object.assign(frameParams, {\n controls: false,\n sidedock: false,\n });\n }\n\n // Get Vimeo params for the iframe\n const params = buildUrlParams({\n loop: player.config.loop.active,\n autoplay: player.autoplay,\n muted: player.muted,\n gesture: 'media',\n playsinline: !this.config.fullscreen.iosNative,\n // hash has to be added to iframe-URL\n ...hashParam,\n ...frameParams,\n });\n\n const id = parseId(source);\n // Build an iframe\n const iframe = createElement('iframe');\n const src = format(player.config.urls.vimeo.iframe, id, params);\n iframe.setAttribute('src', src);\n iframe.setAttribute('allowfullscreen', '');\n iframe.setAttribute(\n 'allow',\n ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; '),\n );\n\n // Set the referrer policy if required\n if (!is.empty(referrerPolicy)) {\n iframe.setAttribute('referrerPolicy', referrerPolicy);\n }\n\n // Inject the package\n if (premium || !config.customControls) {\n iframe.setAttribute('data-poster', player.poster);\n player.media = replaceElement(iframe, player.media);\n } else {\n const wrapper = createElement('div', {\n class: player.config.classNames.embedContainer,\n 'data-poster': player.poster,\n });\n wrapper.appendChild(iframe);\n player.media = replaceElement(wrapper, player.media);\n }\n\n // Get poster image\n if (!config.customControls) {\n fetch(format(player.config.urls.vimeo.api, src)).then((response) => {\n if (is.empty(response) || !response.thumbnail_url) {\n return;\n }\n\n // Set and show poster\n ui.setPoster.call(player, response.thumbnail_url).catch(() => {});\n });\n }\n\n // Setup instance\n // https://github.com/vimeo/player.js\n player.embed = new window.Vimeo.Player(iframe, {\n autopause: player.config.autopause,\n muted: player.muted,\n });\n\n player.media.paused = true;\n player.media.currentTime = 0;\n\n // Disable native text track rendering\n if (player.supported.ui) {\n player.embed.disableTextTrack();\n }\n\n // Create a faux HTML5 API using the Vimeo API\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n return player.embed.play();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n return player.embed.pause();\n };\n\n player.media.stop = () => {\n player.pause();\n player.currentTime = 0;\n };\n\n // Seeking\n let { currentTime } = player.media;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return currentTime;\n },\n set(time) {\n // Vimeo will automatically play on seek if the video hasn't been played before\n\n // Get current paused state and volume etc\n const { embed, media, paused, volume } = player;\n const restorePause = paused && !embed.hasPlayed;\n\n // Set seeking state and trigger event\n media.seeking = true;\n triggerEvent.call(player, media, 'seeking');\n\n // If paused, mute until seek is complete\n Promise.resolve(restorePause && embed.setVolume(0))\n // Seek\n .then(() => embed.setCurrentTime(time))\n // Restore paused\n .then(() => restorePause && embed.pause())\n // Restore volume\n .then(() => restorePause && embed.setVolume(volume))\n .catch(() => {\n // Do nothing\n });\n },\n });\n\n // Playback speed\n let speed = player.config.speed.selected;\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return speed;\n },\n set(input) {\n player.embed\n .setPlaybackRate(input)\n .then(() => {\n speed = input;\n triggerEvent.call(player, player.media, 'ratechange');\n })\n .catch(() => {\n // Cannot set Playback Rate, Video is probably not on Pro account\n player.options.speed = [1];\n });\n },\n });\n\n // Volume\n let { volume } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n set(input) {\n player.embed.setVolume(input).then(() => {\n volume = input;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n },\n });\n\n // Muted\n let { muted } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : false;\n\n player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => {\n muted = toggle;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n },\n });\n\n // Loop\n let { loop } = player.config;\n Object.defineProperty(player.media, 'loop', {\n get() {\n return loop;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : player.config.loop.active;\n\n player.embed.setLoop(toggle).then(() => {\n loop = toggle;\n });\n },\n });\n\n // Source\n let currentSrc;\n player.embed\n .getVideoUrl()\n .then((value) => {\n currentSrc = value;\n controls.setDownloadUrl.call(player);\n })\n .catch((error) => {\n this.debug.warn(error);\n });\n\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return currentSrc;\n },\n });\n\n // Ended\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n },\n });\n\n // Set aspect ratio based on video size\n Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then((dimensions) => {\n const [width, height] = dimensions;\n player.embed.ratio = roundAspectRatio(width, height);\n setAspectRatio.call(this);\n });\n\n // Set autopause\n player.embed.setAutopause(player.config.autopause).then((state) => {\n player.config.autopause = state;\n });\n\n // Get title\n player.embed.getVideoTitle().then((title) => {\n player.config.title = title;\n ui.setTitle.call(this);\n });\n\n // Get current time\n player.embed.getCurrentTime().then((value) => {\n currentTime = value;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n\n // Get duration\n player.embed.getDuration().then((value) => {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n });\n\n // Get captions\n player.embed.getTextTracks().then((tracks) => {\n player.media.textTracks = tracks;\n captions.setup.call(player);\n });\n\n player.embed.on('cuechange', ({ cues = [] }) => {\n const strippedCues = cues.map((cue) => stripHTML(cue.text));\n captions.updateCues.call(player, strippedCues);\n });\n\n player.embed.on('loaded', () => {\n // Assure state and events are updated on autoplay\n player.embed.getPaused().then((paused) => {\n assurePlaybackState.call(player, !paused);\n if (!paused) {\n triggerEvent.call(player, player.media, 'playing');\n }\n });\n\n if (is.element(player.embed.element) && player.supported.ui) {\n const frame = player.embed.element;\n\n // Fix keyboard focus issues\n // https://github.com/sampotts/plyr/issues/317\n frame.setAttribute('tabindex', -1);\n }\n });\n\n player.embed.on('bufferstart', () => {\n triggerEvent.call(player, player.media, 'waiting');\n });\n\n player.embed.on('bufferend', () => {\n triggerEvent.call(player, player.media, 'playing');\n });\n\n player.embed.on('play', () => {\n assurePlaybackState.call(player, true);\n triggerEvent.call(player, player.media, 'playing');\n });\n\n player.embed.on('pause', () => {\n assurePlaybackState.call(player, false);\n });\n\n player.embed.on('timeupdate', (data) => {\n player.media.seeking = false;\n currentTime = data.seconds;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n\n player.embed.on('progress', (data) => {\n player.media.buffered = data.percent;\n triggerEvent.call(player, player.media, 'progress');\n\n // Check all loaded\n if (parseInt(data.percent, 10) === 1) {\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n\n // Get duration as if we do it before load, it gives an incorrect value\n // https://github.com/sampotts/plyr/issues/891\n player.embed.getDuration().then((value) => {\n if (value !== player.media.duration) {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }\n });\n });\n\n player.embed.on('seeked', () => {\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n });\n\n player.embed.on('ended', () => {\n player.media.paused = true;\n triggerEvent.call(player, player.media, 'ended');\n });\n\n player.embed.on('error', (detail) => {\n player.media.error = detail;\n triggerEvent.call(player, player.media, 'error');\n });\n\n // Rebuild UI\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 0);\n }\n },\n};\n\nexport default vimeo;\n","// ==========================================================================\n// YouTube plugin\n// ==========================================================================\n\nimport ui from '../ui';\nimport { createElement, replaceElement, toggleClass } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport loadImage from '../utils/load-image';\nimport loadScript from '../utils/load-script';\nimport { extend } from '../utils/objects';\nimport { format, generateId } from '../utils/strings';\nimport { roundAspectRatio, setAspectRatio } from '../utils/style';\n\n// Parse YouTube ID from URL\nfunction parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n const regex = /^.*(youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=|&v=)([^#&?]*).*/;\n return url.match(regex) ? RegExp.$2 : url;\n}\n\n// Set playback state and trigger change (only on actual change)\nfunction assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nfunction getHost(config) {\n if (config.noCookie) {\n return 'https://www.youtube-nocookie.com';\n }\n\n if (window.location.protocol === 'http:') {\n return 'http://www.youtube.com';\n }\n\n // Use YouTube's default\n return undefined;\n}\n\nconst youtube = {\n setup() {\n // Add embed class for responsive\n toggleClass(this.elements.wrapper, this.config.classNames.embed, true);\n\n // Setup API\n if (is.object(window.YT) && is.function(window.YT.Player)) {\n youtube.ready.call(this);\n } else {\n // Reference current global callback\n const callback = window.onYouTubeIframeAPIReady;\n\n // Set callback to process queue\n window.onYouTubeIframeAPIReady = () => {\n // Call global callback if set\n if (is.function(callback)) {\n callback();\n }\n\n youtube.ready.call(this);\n };\n\n // Load the SDK\n loadScript(this.config.urls.youtube.sdk).catch((error) => {\n this.debug.warn('YouTube API failed to load', error);\n });\n }\n },\n\n // Get the media title\n getTitle(videoId) {\n const url = format(this.config.urls.youtube.api, videoId);\n\n fetch(url)\n .then((data) => {\n if (is.object(data)) {\n const { title, height, width } = data;\n\n // Set title\n this.config.title = title;\n ui.setTitle.call(this);\n\n // Set aspect ratio\n this.embed.ratio = roundAspectRatio(width, height);\n }\n\n setAspectRatio.call(this);\n })\n .catch(() => {\n // Set aspect ratio\n setAspectRatio.call(this);\n });\n },\n\n // API ready\n ready() {\n const player = this;\n const config = player.config.youtube;\n // Ignore already setup (race condition)\n const currentId = player.media && player.media.getAttribute('id');\n if (!is.empty(currentId) && currentId.startsWith('youtube-')) {\n return;\n }\n\n // Get the source URL or ID\n let source = player.media.getAttribute('src');\n\n // Get from <div> if needed\n if (is.empty(source)) {\n source = player.media.getAttribute(this.config.attributes.embed.id);\n }\n\n // Replace the <iframe> with a <div> due to YouTube API issues\n const videoId = parseId(source);\n const id = generateId(player.provider);\n // Replace media element\n const container = createElement('div', { id, 'data-poster': config.customControls ? player.poster : undefined });\n player.media = replaceElement(container, player.media);\n\n // Only load the poster when using custom controls\n if (config.customControls) {\n const posterSrc = (s) => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`;\n\n // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide)\n loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded\n .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3\n .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists\n .then((image) => ui.setPoster.call(player, image.src))\n .then((src) => {\n // If the image is padded, use background-size \"cover\" instead (like youtube does too with their posters)\n if (!src.includes('maxres')) {\n player.elements.poster.style.backgroundSize = 'cover';\n }\n })\n .catch(() => {});\n }\n\n // Setup instance\n // https://developers.google.com/youtube/iframe_api_reference\n player.embed = new window.YT.Player(player.media, {\n videoId,\n host: getHost(config),\n playerVars: extend(\n {},\n {\n // Autoplay\n autoplay: player.config.autoplay ? 1 : 0,\n // iframe interface language\n hl: player.config.hl,\n // Only show controls if not fully supported or opted out\n controls: player.supported.ui && config.customControls ? 0 : 1,\n // Disable keyboard as we handle it\n disablekb: 1,\n // Allow iOS inline playback\n playsinline: !player.config.fullscreen.iosNative ? 1 : 0,\n // Captions are flaky on YouTube\n cc_load_policy: player.captions.active ? 1 : 0,\n cc_lang_pref: player.config.captions.language,\n // Tracking for stats\n widget_referrer: window ? window.location.href : null,\n },\n config,\n ),\n events: {\n onError(event) {\n // YouTube may fire onError twice, so only handle it once\n if (!player.media.error) {\n const code = event.data;\n // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError\n const message =\n {\n 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.',\n 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.',\n 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.',\n 101: 'The owner of the requested video does not allow it to be played in embedded players.',\n 150: 'The owner of the requested video does not allow it to be played in embedded players.',\n }[code] || 'An unknown error occured';\n\n player.media.error = { code, message };\n\n triggerEvent.call(player, player.media, 'error');\n }\n },\n onPlaybackRateChange(event) {\n // Get the instance\n const instance = event.target;\n\n // Get current speed\n player.media.playbackRate = instance.getPlaybackRate();\n\n triggerEvent.call(player, player.media, 'ratechange');\n },\n onReady(event) {\n // Bail if onReady has already been called. See issue #1108\n if (is.function(player.media.play)) {\n return;\n }\n // Get the instance\n const instance = event.target;\n\n // Get the title\n youtube.getTitle.call(player, videoId);\n\n // Create a faux HTML5 API using the YouTube API\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n instance.playVideo();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n instance.pauseVideo();\n };\n\n player.media.stop = () => {\n instance.stopVideo();\n };\n\n player.media.duration = instance.getDuration();\n player.media.paused = true;\n\n // Seeking\n player.media.currentTime = 0;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return Number(instance.getCurrentTime());\n },\n set(time) {\n // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet).\n if (player.paused && !player.embed.hasPlayed) {\n player.embed.mute();\n }\n\n // Set seeking state and trigger event\n player.media.seeking = true;\n triggerEvent.call(player, player.media, 'seeking');\n\n // Seek after events sent\n instance.seekTo(time);\n },\n });\n\n // Playback speed\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return instance.getPlaybackRate();\n },\n set(input) {\n instance.setPlaybackRate(input);\n },\n });\n\n // Volume\n let { volume } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n set(input) {\n volume = input;\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n },\n });\n\n // Muted\n let { muted } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : muted;\n muted = toggle;\n instance[toggle ? 'mute' : 'unMute']();\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n },\n });\n\n // Source\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return instance.getVideoUrl();\n },\n });\n\n // Ended\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n },\n });\n\n // Get available speeds\n const speeds = instance.getAvailablePlaybackRates();\n // Filter based on config\n player.options.speed = speeds.filter((s) => player.config.speed.options.includes(s));\n\n // Set the tabindex to avoid focus entering iframe\n if (player.supported.ui && config.customControls) {\n player.media.setAttribute('tabindex', -1);\n }\n\n triggerEvent.call(player, player.media, 'timeupdate');\n triggerEvent.call(player, player.media, 'durationchange');\n\n // Reset timer\n clearInterval(player.timers.buffering);\n\n // Setup buffering\n player.timers.buffering = setInterval(() => {\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction();\n\n // Trigger progress only when we actually buffer something\n if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) {\n triggerEvent.call(player, player.media, 'progress');\n }\n\n // Set last buffer point\n player.media.lastBuffered = player.media.buffered;\n\n // Bail if we're at 100%\n if (player.media.buffered === 1) {\n clearInterval(player.timers.buffering);\n\n // Trigger event\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n }, 200);\n\n // Rebuild UI\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 50);\n }\n },\n onStateChange(event) {\n // Get the instance\n const instance = event.target;\n\n // Reset timer\n clearInterval(player.timers.playing);\n\n const seeked = player.media.seeking && [1, 2].includes(event.data);\n\n if (seeked) {\n // Unset seeking and fire seeked event\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n }\n\n // Handle events\n // -1 Unstarted\n // 0 Ended\n // 1 Playing\n // 2 Paused\n // 3 Buffering\n // 5 Video cued\n switch (event.data) {\n case -1:\n // Update scrubber\n triggerEvent.call(player, player.media, 'timeupdate');\n\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction();\n triggerEvent.call(player, player.media, 'progress');\n\n break;\n\n case 0:\n assurePlaybackState.call(player, false);\n\n // YouTube doesn't support loop for a single video, so mimick it.\n if (player.media.loop) {\n // YouTube needs a call to `stopVideo` before playing again\n instance.stopVideo();\n instance.playVideo();\n } else {\n triggerEvent.call(player, player.media, 'ended');\n }\n\n break;\n\n case 1:\n // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet)\n if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) {\n player.media.pause();\n } else {\n assurePlaybackState.call(player, true);\n\n triggerEvent.call(player, player.media, 'playing');\n\n // Poll to get playback progress\n player.timers.playing = setInterval(() => {\n triggerEvent.call(player, player.media, 'timeupdate');\n }, 50);\n\n // Check duration again due to YouTube bug\n // https://github.com/sampotts/plyr/issues/374\n // https://code.google.com/p/gdata-issues/issues/detail?id=8690\n if (player.media.duration !== instance.getDuration()) {\n player.media.duration = instance.getDuration();\n triggerEvent.call(player, player.media, 'durationchange');\n }\n }\n\n break;\n\n case 2:\n // Restore audio (YouTube starts playing on seek if the video hasn't been played yet)\n if (!player.muted) {\n player.embed.unMute();\n }\n assurePlaybackState.call(player, false);\n\n break;\n\n case 3:\n // Trigger waiting event to add loading classes to container as the video buffers.\n triggerEvent.call(player, player.media, 'waiting');\n\n break;\n\n default:\n break;\n }\n\n triggerEvent.call(player, player.elements.container, 'statechange', false, {\n code: event.data,\n });\n },\n },\n });\n },\n};\n\nexport default youtube;\n","// ==========================================================================\n// Plyr Media\n// ==========================================================================\n\nimport html5 from './html5';\nimport vimeo from './plugins/vimeo';\nimport youtube from './plugins/youtube';\nimport { createElement, toggleClass, wrap } from './utils/elements';\n\nconst media = {\n // Setup media\n setup() {\n // If there's no media, bail\n if (!this.media) {\n this.debug.warn('No media element found!');\n return;\n }\n\n // Add type class\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true);\n\n // Add provider class\n toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true);\n\n // Add video class for embeds\n // This will require changes if audio embeds are added\n if (this.isEmbed) {\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true);\n }\n\n // Inject the player wrapper\n if (this.isVideo) {\n // Create the wrapper div\n this.elements.wrapper = createElement('div', {\n class: this.config.classNames.video,\n });\n\n // Wrap the video in a container\n wrap(this.media, this.elements.wrapper);\n\n // Poster image container\n this.elements.poster = createElement('div', {\n class: this.config.classNames.poster,\n });\n\n this.elements.wrapper.appendChild(this.elements.poster);\n }\n\n if (this.isHTML5) {\n html5.setup.call(this);\n } else if (this.isYouTube) {\n youtube.setup.call(this);\n } else if (this.isVimeo) {\n vimeo.setup.call(this);\n }\n },\n};\n\nexport default media;\n","// ==========================================================================\n// Advertisement plugin using Google IMA HTML5 SDK\n// Create an account with our ad partner, vi here:\n// https://www.vi.ai/publisher-video-monetization/\n// ==========================================================================\n\n/* global google */\n\nimport { createElement } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport i18n from '../utils/i18n';\nimport is from '../utils/is';\nimport loadScript from '../utils/load-script';\nimport { silencePromise } from '../utils/promise';\nimport { formatTime } from '../utils/time';\nimport { buildUrlParams } from '../utils/urls';\n\nconst destroy = (instance) => {\n // Destroy our adsManager\n if (instance.manager) {\n instance.manager.destroy();\n }\n\n // Destroy our adsManager\n if (instance.elements.displayContainer) {\n instance.elements.displayContainer.destroy();\n }\n\n instance.elements.container.remove();\n};\n\nclass Ads {\n /**\n * Ads constructor.\n * @param {Object} player\n * @return {Ads}\n */\n constructor(player) {\n this.player = player;\n this.config = player.config.ads;\n this.playing = false;\n this.initialized = false;\n this.elements = {\n container: null,\n displayContainer: null,\n };\n this.manager = null;\n this.loader = null;\n this.cuePoints = null;\n this.events = {};\n this.safetyTimer = null;\n this.countdownTimer = null;\n\n // Setup a promise to resolve when the IMA manager is ready\n this.managerPromise = new Promise((resolve, reject) => {\n // The ad is loaded and ready\n this.on('loaded', resolve);\n\n // Ads failed\n this.on('error', reject);\n });\n\n this.load();\n }\n\n get enabled() {\n const { config } = this;\n\n return (\n this.player.isHTML5 &&\n this.player.isVideo &&\n config.enabled &&\n (!is.empty(config.publisherId) || is.url(config.tagUrl))\n );\n }\n\n /**\n * Load the IMA SDK\n */\n load = () => {\n if (!this.enabled) {\n return;\n }\n\n // Check if the Google IMA3 SDK is loaded or load it ourselves\n if (!is.object(window.google) || !is.object(window.google.ima)) {\n loadScript(this.player.config.urls.googleIMA.sdk)\n .then(() => {\n this.ready();\n })\n .catch(() => {\n // Script failed to load or is blocked\n this.trigger('error', new Error('Google IMA SDK failed to load'));\n });\n } else {\n this.ready();\n }\n };\n\n /**\n * Get the ads instance ready\n */\n ready = () => {\n // Double check we're enabled\n if (!this.enabled) {\n destroy(this);\n }\n\n // Start ticking our safety timer. If the whole advertisement\n // thing doesn't resolve within our set time; we bail\n this.startSafetyTimer(12000, 'ready()');\n\n // Clear the safety timer\n this.managerPromise.then(() => {\n this.clearSafetyTimer('onAdsManagerLoaded()');\n });\n\n // Set listeners on the Plyr instance\n this.listeners();\n\n // Setup the IMA SDK\n this.setupIMA();\n };\n\n // Build the tag URL\n get tagUrl() {\n const { config } = this;\n\n if (is.url(config.tagUrl)) {\n return config.tagUrl;\n }\n\n const params = {\n AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',\n AV_CHANNELID: '5a0458dc28a06145e4519d21',\n AV_URL: window.location.hostname,\n cb: Date.now(),\n AV_WIDTH: 640,\n AV_HEIGHT: 480,\n AV_CDIM2: config.publisherId,\n };\n\n const base = 'https://go.aniview.com/api/adserver6/vast/';\n\n return `${base}?${buildUrlParams(params)}`;\n }\n\n /**\n * In order for the SDK to display ads for our video, we need to tell it where to put them,\n * so here we define our ad container. This div is set up to render on top of the video player.\n * Using the code below, we tell the SDK to render ads within that div. We also provide a\n * handle to the content video player - the SDK will poll the current time of our player to\n * properly place mid-rolls. After we create the ad display container, we initialize it. On\n * mobile devices, this initialization is done as the result of a user action.\n */\n setupIMA = () => {\n // Create the container for our advertisements\n this.elements.container = createElement('div', {\n class: this.player.config.classNames.ads,\n });\n\n this.player.elements.container.appendChild(this.elements.container);\n\n // So we can run VPAID2\n google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);\n\n // Set language\n google.ima.settings.setLocale(this.player.config.ads.language);\n\n // Set playback for iOS10+\n google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline);\n\n // We assume the adContainer is the video container of the plyr element that will house the ads\n this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container, this.player.media);\n\n // Create ads loader\n this.loader = new google.ima.AdsLoader(this.elements.displayContainer);\n\n // Listen and respond to ads loaded and error events\n this.loader.addEventListener(\n google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,\n (event) => this.onAdsManagerLoaded(event),\n false,\n );\n this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, (error) => this.onAdError(error), false);\n\n // Request video ads to be pre-loaded\n this.requestAds();\n };\n\n /**\n * Request advertisements\n */\n requestAds = () => {\n const { container } = this.player.elements;\n\n try {\n // Request video ads\n const request = new google.ima.AdsRequest();\n request.adTagUrl = this.tagUrl;\n\n // Specify the linear and nonlinear slot sizes. This helps the SDK\n // to select the correct creative if multiple are returned\n request.linearAdSlotWidth = container.offsetWidth;\n request.linearAdSlotHeight = container.offsetHeight;\n request.nonLinearAdSlotWidth = container.offsetWidth;\n request.nonLinearAdSlotHeight = container.offsetHeight;\n\n // We only overlay ads as we only support video.\n request.forceNonLinearFullSlot = false;\n\n // Mute based on current state\n request.setAdWillPlayMuted(!this.player.muted);\n\n this.loader.requestAds(request);\n } catch (error) {\n this.onAdError(error);\n }\n };\n\n /**\n * Update the ad countdown\n * @param {Boolean} start\n */\n pollCountdown = (start = false) => {\n if (!start) {\n clearInterval(this.countdownTimer);\n this.elements.container.removeAttribute('data-badge-text');\n return;\n }\n\n const update = () => {\n const time = formatTime(Math.max(this.manager.getRemainingTime(), 0));\n const label = `${i18n.get('advertisement', this.player.config)} - ${time}`;\n this.elements.container.setAttribute('data-badge-text', label);\n };\n\n this.countdownTimer = setInterval(update, 100);\n };\n\n /**\n * This method is called whenever the ads are ready inside the AdDisplayContainer\n * @param {Event} adsManagerLoadedEvent\n */\n onAdsManagerLoaded = (event) => {\n // Load could occur after a source change (race condition)\n if (!this.enabled) {\n return;\n }\n\n // Get the ads manager\n const settings = new google.ima.AdsRenderingSettings();\n\n // Tell the SDK to save and restore content video state on our behalf\n settings.restoreCustomPlaybackStateOnAdBreakComplete = true;\n settings.enablePreloading = true;\n\n // The SDK is polling currentTime on the contentPlayback. And needs a duration\n // so it can determine when to start the mid- and post-roll\n this.manager = event.getAdsManager(this.player, settings);\n\n // Get the cue points for any mid-rolls by filtering out the pre- and post-roll\n this.cuePoints = this.manager.getCuePoints();\n\n // Add listeners to the required events\n // Advertisement error events\n this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, (error) => this.onAdError(error));\n\n // Advertisement regular events\n Object.keys(google.ima.AdEvent.Type).forEach((type) => {\n this.manager.addEventListener(google.ima.AdEvent.Type[type], (e) => this.onAdEvent(e));\n });\n\n // Resolve our adsManager\n this.trigger('loaded');\n };\n\n addCuePoints = () => {\n // Add advertisement cue's within the time line if available\n if (!is.empty(this.cuePoints)) {\n this.cuePoints.forEach((cuePoint) => {\n if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {\n const seekElement = this.player.elements.progress;\n\n if (is.element(seekElement)) {\n const cuePercentage = (100 / this.player.duration) * cuePoint;\n const cue = createElement('span', {\n class: this.player.config.classNames.cues,\n });\n\n cue.style.left = `${cuePercentage.toString()}%`;\n seekElement.appendChild(cue);\n }\n }\n });\n }\n };\n\n /**\n * This is where all the event handling takes place. Retrieve the ad from the event. Some\n * events (e.g. ALL_ADS_COMPLETED) don't have the ad object associated\n * https://developers.google.com/interactive-media-ads/docs/sdks/html5/v3/apis#ima.AdEvent.Type\n * @param {Event} event\n */\n onAdEvent = (event) => {\n const { container } = this.player.elements;\n // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)\n // don't have ad object associated\n const ad = event.getAd();\n const adData = event.getAdData();\n\n // Proxy event\n const dispatchEvent = (type) => {\n triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`);\n };\n\n // Bubble the event\n dispatchEvent(event.type);\n\n switch (event.type) {\n case google.ima.AdEvent.Type.LOADED:\n // This is the first event sent for an ad - it is possible to determine whether the\n // ad is a video ad or an overlay\n this.trigger('loaded');\n\n // Start countdown\n this.pollCountdown(true);\n\n if (!ad.isLinear()) {\n // Position AdDisplayContainer correctly for overlay\n ad.width = container.offsetWidth;\n ad.height = container.offsetHeight;\n }\n\n // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex());\n // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset());\n\n break;\n\n case google.ima.AdEvent.Type.STARTED:\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n\n break;\n\n case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:\n // All ads for the current videos are done. We can now request new advertisements\n // in case the video is re-played\n\n // TODO: Example for what happens when a next video in a playlist would be loaded.\n // So here we load a new video when all ads are done.\n // Then we load new ads within a new adsManager. When the video\n // Is started - after - the ads are loaded, then we get ads.\n // You can also easily test cancelling and reloading by running\n // player.ads.cancel() and player.ads.play from the console I guess.\n // this.player.source = {\n // type: 'video',\n // title: 'View From A Blue Moon',\n // sources: [{\n // src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type:\n // 'video/mp4', }], poster:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks:\n // [ { kind: 'captions', label: 'English', srclang: 'en', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',\n // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ],\n // };\n\n // TODO: So there is still this thing where a video should only be allowed to start\n // playing when the IMA SDK is ready or has failed\n\n if (this.player.ended) {\n this.loadAds();\n } else {\n // The SDK won't allow new ads to be called without receiving a contentComplete()\n this.loader.contentComplete();\n }\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:\n // This event indicates the ad has started - the video player can adjust the UI,\n // for example display a pause button and remaining time. Fired when content should\n // be paused. This usually happens right before an ad is about to cover the content\n\n this.pauseContent();\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:\n // This event indicates the ad has finished - the video player can perform\n // appropriate UI actions, such as removing the timer for remaining time detection.\n // Fired when content should be resumed. This usually happens when an ad finishes\n // or collapses\n\n this.pollCountdown();\n\n this.resumeContent();\n\n break;\n\n case google.ima.AdEvent.Type.LOG:\n if (adData.adError) {\n this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);\n }\n\n break;\n\n default:\n break;\n }\n };\n\n /**\n * Any ad error handling comes through here\n * @param {Event} event\n */\n onAdError = (event) => {\n this.cancel();\n this.player.debug.warn('Ads error', event);\n };\n\n /**\n * Setup hooks for Plyr and window events. This ensures\n * the mid- and post-roll launch at the correct time. And\n * resize the advertisement when the player resizes\n */\n listeners = () => {\n const { container } = this.player.elements;\n let time;\n\n this.player.on('canplay', () => {\n this.addCuePoints();\n });\n\n this.player.on('ended', () => {\n this.loader.contentComplete();\n });\n\n this.player.on('timeupdate', () => {\n time = this.player.currentTime;\n });\n\n this.player.on('seeked', () => {\n const seekedTime = this.player.currentTime;\n\n if (is.empty(this.cuePoints)) {\n return;\n }\n\n this.cuePoints.forEach((cuePoint, index) => {\n if (time < cuePoint && cuePoint < seekedTime) {\n this.manager.discardAdBreak();\n this.cuePoints.splice(index, 1);\n }\n });\n });\n\n // Listen to the resizing of the window. And resize ad accordingly\n // TODO: eventually implement ResizeObserver\n window.addEventListener('resize', () => {\n if (this.manager) {\n this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n }\n });\n };\n\n /**\n * Initialize the adsManager and start playing advertisements\n */\n play = () => {\n const { container } = this.player.elements;\n\n if (!this.managerPromise) {\n this.resumeContent();\n }\n\n // Play the requested advertisement whenever the adsManager is ready\n this.managerPromise\n .then(() => {\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n\n // Initialize the container. Must be done via a user action on mobile devices\n this.elements.displayContainer.initialize();\n\n try {\n if (!this.initialized) {\n // Initialize the ads manager. Ad rules playlist will start at this time\n this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n\n // Call play to start showing the ad. Single video and overlay ads will\n // start at this time; the call will be ignored for ad rules\n this.manager.start();\n }\n\n this.initialized = true;\n } catch (adError) {\n // An error may be thrown if there was a problem with the\n // VAST response\n this.onAdError(adError);\n }\n })\n .catch(() => {});\n };\n\n /**\n * Resume our video\n */\n resumeContent = () => {\n // Hide the advertisement container\n this.elements.container.style.zIndex = '';\n\n // Ad is stopped\n this.playing = false;\n\n // Play video\n silencePromise(this.player.media.play());\n };\n\n /**\n * Pause our video\n */\n pauseContent = () => {\n // Show the advertisement container\n this.elements.container.style.zIndex = 3;\n\n // Ad is playing\n this.playing = true;\n\n // Pause our video.\n this.player.media.pause();\n };\n\n /**\n * Destroy the adsManager so we can grab new ads after this. If we don't then we're not\n * allowed to call new ads based on google policies, as they interpret this as an accidental\n * video requests. https://developers.google.com/interactive-\n * media-ads/docs/sdks/android/faq#8\n */\n cancel = () => {\n // Pause our video\n if (this.initialized) {\n this.resumeContent();\n }\n\n // Tell our instance that we're done for now\n this.trigger('error');\n\n // Re-create our adsManager\n this.loadAds();\n };\n\n /**\n * Re-create our adsManager\n */\n loadAds = () => {\n // Tell our adsManager to go bye bye\n this.managerPromise\n .then(() => {\n // Destroy our adsManager\n if (this.manager) {\n this.manager.destroy();\n }\n\n // Re-set our adsManager promises\n this.managerPromise = new Promise((resolve) => {\n this.on('loaded', resolve);\n this.player.debug.log(this.manager);\n });\n // Now that the manager has been destroyed set it to also be un-initialized\n this.initialized = false;\n\n // Now request some new advertisements\n this.requestAds();\n })\n .catch(() => {});\n };\n\n /**\n * Handles callbacks after an ad event was invoked\n * @param {String} event - Event type\n */\n trigger = (event, ...args) => {\n const handlers = this.events[event];\n\n if (is.array(handlers)) {\n handlers.forEach((handler) => {\n if (is.function(handler)) {\n handler.apply(this, args);\n }\n });\n }\n };\n\n /**\n * Add event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n * @return {Ads}\n */\n on = (event, callback) => {\n if (!is.array(this.events[event])) {\n this.events[event] = [];\n }\n\n this.events[event].push(callback);\n\n return this;\n };\n\n /**\n * Setup a safety timer for when the ad network doesn't respond for whatever reason.\n * The advertisement has 12 seconds to get its things together. We stop this timer when the\n * advertisement is playing, or when a user action is required to start, then we clear the\n * timer on ad ready\n * @param {Number} time\n * @param {String} from\n */\n startSafetyTimer = (time, from) => {\n this.player.debug.log(`Safety timer invoked from: ${from}`);\n\n this.safetyTimer = setTimeout(() => {\n this.cancel();\n this.clearSafetyTimer('startSafetyTimer()');\n }, time);\n };\n\n /**\n * Clear our safety timer(s)\n * @param {String} from\n */\n clearSafetyTimer = (from) => {\n if (!is.nullOrUndefined(this.safetyTimer)) {\n this.player.debug.log(`Safety timer cleared from: ${from}`);\n\n clearTimeout(this.safetyTimer);\n this.safetyTimer = null;\n }\n };\n}\n\nexport default Ads;\n","import { createElement } from '../utils/elements';\nimport { once } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport { formatTime } from '../utils/time';\n\n// Arg: vttDataString example: \"WEBVTT\\n\\n1\\n00:00:05.000 --> 00:00:10.000\\n1080p-00001.jpg\"\nconst parseVtt = (vttDataString) => {\n const processedList = [];\n const frames = vttDataString.split(/\\r\\n\\r\\n|\\n\\n|\\r\\r/);\n\n frames.forEach((frame) => {\n const result = {};\n const lines = frame.split(/\\r\\n|\\n|\\r/);\n\n lines.forEach((line) => {\n if (!is.number(result.startTime)) {\n // The line with start and end times on it is the first line of interest\n const matchTimes = line.match(\n /([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})/,\n ); // Note that this currently ignores caption formatting directives that are optionally on the end of this line - fine for non-captions VTT\n\n if (matchTimes) {\n result.startTime =\n Number(matchTimes[1] || 0) * 60 * 60 +\n Number(matchTimes[2]) * 60 +\n Number(matchTimes[3]) +\n Number(`0.${matchTimes[4]}`);\n result.endTime =\n Number(matchTimes[6] || 0) * 60 * 60 +\n Number(matchTimes[7]) * 60 +\n Number(matchTimes[8]) +\n Number(`0.${matchTimes[9]}`);\n }\n } else if (!is.empty(line.trim()) && is.empty(result.text)) {\n // If we already have the startTime, then we're definitely up to the text line(s)\n const lineSplit = line.trim().split('#xywh=');\n [result.text] = lineSplit;\n\n // If there's content in lineSplit[1], then we have sprites. If not, then it's just one frame per image\n if (lineSplit[1]) {\n [result.x, result.y, result.w, result.h] = lineSplit[1].split(',');\n }\n }\n });\n\n if (result.text) {\n processedList.push(result);\n }\n });\n\n return processedList;\n};\n\n/**\n * Preview thumbnails for seek hover and scrubbing\n * Seeking: Hover over the seek bar (desktop only): shows a small preview container above the seek bar\n * 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\n *\n * Notes:\n * - 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\n * - 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\n * - 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\n */\n\nconst fitRatio = (ratio, outer) => {\n const targetRatio = outer.width / outer.height;\n const result = {};\n if (ratio > targetRatio) {\n result.width = outer.width;\n result.height = (1 / ratio) * outer.width;\n } else {\n result.height = outer.height;\n result.width = ratio * outer.height;\n }\n\n return result;\n};\n\nclass PreviewThumbnails {\n /**\n * PreviewThumbnails constructor.\n * @param {Plyr} player\n * @return {PreviewThumbnails}\n */\n constructor(player) {\n this.player = player;\n this.thumbnails = [];\n this.loaded = false;\n this.lastMouseMoveTime = Date.now();\n this.mouseDown = false;\n this.loadedImages = [];\n\n this.elements = {\n thumb: {},\n scrubbing: {},\n };\n\n this.load();\n }\n\n get enabled() {\n return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;\n }\n\n load = () => {\n // Toggle the regular seek tooltip\n if (this.player.elements.display.seekTooltip) {\n this.player.elements.display.seekTooltip.hidden = this.enabled;\n }\n\n if (!this.enabled) {\n return;\n }\n\n this.getThumbnails().then(() => {\n if (!this.enabled) {\n return;\n }\n\n // Render DOM elements\n this.render();\n\n // Check to see if thumb container size was specified manually in CSS\n this.determineContainerAutoSizing();\n\n this.loaded = true;\n });\n };\n\n // Download VTT files and parse them\n getThumbnails = () => {\n return new Promise((resolve) => {\n const { src } = this.player.config.previewThumbnails;\n\n if (is.empty(src)) {\n throw new Error('Missing previewThumbnails.src config attribute');\n }\n\n // Resolve promise\n const sortAndResolve = () => {\n // Sort smallest to biggest (e.g., [120p, 480p, 1080p])\n this.thumbnails.sort((x, y) => x.height - y.height);\n\n this.player.debug.log('Preview thumbnails', this.thumbnails);\n\n resolve();\n };\n\n // Via callback()\n if (is.function(src)) {\n src((thumbnails) => {\n this.thumbnails = thumbnails;\n sortAndResolve();\n });\n }\n // VTT urls\n else {\n // If string, convert into single-element list\n const urls = is.string(src) ? [src] : src;\n // Loop through each src URL. Download and process the VTT file, storing the resulting data in this.thumbnails\n const promises = urls.map((u) => this.getThumbnail(u));\n // Resolve\n Promise.all(promises).then(sortAndResolve);\n }\n });\n };\n\n // Process individual VTT file\n getThumbnail = (url) => {\n return new Promise((resolve) => {\n fetch(url).then((response) => {\n const thumbnail = {\n frames: parseVtt(response),\n height: null,\n urlPrefix: '',\n };\n\n // If the URLs don't start with '/', then we need to set their relative path to be the location of the VTT file\n // If the URLs do start with '/', then they obviously don't need a prefix, so it will remain blank\n // If the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file\n if (\n !thumbnail.frames[0].text.startsWith('/') &&\n !thumbnail.frames[0].text.startsWith('http://') &&\n !thumbnail.frames[0].text.startsWith('https://')\n ) {\n thumbnail.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1);\n }\n\n // Download the first frame, so that we can determine/set the height of this thumbnailsDef\n const tempImage = new Image();\n\n tempImage.onload = () => {\n thumbnail.height = tempImage.naturalHeight;\n thumbnail.width = tempImage.naturalWidth;\n\n this.thumbnails.push(thumbnail);\n\n resolve();\n };\n\n tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;\n });\n });\n };\n\n startMove = (event) => {\n if (!this.loaded) {\n return;\n }\n\n if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {\n return;\n }\n\n // Wait until media has a duration\n if (!this.player.media.duration) {\n return;\n }\n\n if (event.type === 'touchmove') {\n // Calculate seek hover position as approx video seconds\n this.seekTime = this.player.media.duration * (this.player.elements.inputs.seek.value / 100);\n } else {\n // Calculate seek hover position as approx video seconds\n const clientRect = this.player.elements.progress.getBoundingClientRect();\n const percentage = (100 / clientRect.width) * (event.pageX - clientRect.left);\n this.seekTime = this.player.media.duration * (percentage / 100);\n\n if (this.seekTime < 0) {\n // The mousemove fires for 10+px out to the left\n this.seekTime = 0;\n }\n\n if (this.seekTime > this.player.media.duration - 1) {\n // Took 1 second off the duration for safety, because different players can disagree on the real duration of a video\n this.seekTime = this.player.media.duration - 1;\n }\n\n this.mousePosX = event.pageX;\n\n // Set time text inside image container\n this.elements.thumb.time.innerText = formatTime(this.seekTime);\n }\n\n // Download and show image\n this.showImageAtCurrentTime();\n };\n\n endMove = () => {\n this.toggleThumbContainer(false, true);\n };\n\n startScrubbing = (event) => {\n // Only act on left mouse button (0), or touch device (event.button does not exist or is false)\n if (is.nullOrUndefined(event.button) || event.button === false || event.button === 0) {\n this.mouseDown = true;\n\n // Wait until media has a duration\n if (this.player.media.duration) {\n this.toggleScrubbingContainer(true);\n this.toggleThumbContainer(false, true);\n\n // Download and show image\n this.showImageAtCurrentTime();\n }\n }\n };\n\n endScrubbing = () => {\n this.mouseDown = false;\n\n // Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview\n if (Math.ceil(this.lastTime) === Math.ceil(this.player.media.currentTime)) {\n // The video was already seeked/loaded at the chosen time - hide immediately\n this.toggleScrubbingContainer(false);\n } else {\n // The video hasn't seeked yet. Wait for that\n once.call(this.player, this.player.media, 'timeupdate', () => {\n // Re-check mousedown - we might have already started scrubbing again\n if (!this.mouseDown) {\n this.toggleScrubbingContainer(false);\n }\n });\n }\n };\n\n /**\n * Setup hooks for Plyr and window events\n */\n listeners = () => {\n // 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\n this.player.on('play', () => {\n this.toggleThumbContainer(false, true);\n });\n\n this.player.on('seeked', () => {\n this.toggleThumbContainer(false);\n });\n\n this.player.on('timeupdate', () => {\n this.lastTime = this.player.media.currentTime;\n });\n };\n\n /**\n * Create HTML elements for image containers\n */\n render = () => {\n // Create HTML element: plyr__preview-thumbnail-container\n this.elements.thumb.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.thumbContainer,\n });\n\n // Wrapper for the image for styling\n this.elements.thumb.imageContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.imageContainer,\n });\n this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer);\n\n // Create HTML element, parent+span: time text (e.g., 01:32:00)\n const timeContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.timeContainer,\n });\n\n this.elements.thumb.time = createElement('span', {}, '00:00');\n timeContainer.appendChild(this.elements.thumb.time);\n\n this.elements.thumb.container.appendChild(timeContainer);\n\n // Inject the whole thumb\n if (is.element(this.player.elements.progress)) {\n this.player.elements.progress.appendChild(this.elements.thumb.container);\n }\n\n // Create HTML element: plyr__preview-scrubbing-container\n this.elements.scrubbing.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.scrubbingContainer,\n });\n\n this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);\n };\n\n destroy = () => {\n if (this.elements.thumb.container) {\n this.elements.thumb.container.remove();\n }\n if (this.elements.scrubbing.container) {\n this.elements.scrubbing.container.remove();\n }\n };\n\n showImageAtCurrentTime = () => {\n if (this.mouseDown) {\n this.setScrubbingContainerSize();\n } else {\n this.setThumbContainerSizeAndPos();\n }\n\n // Find the desired thumbnail index\n // TODO: Handle a video longer than the thumbs where thumbNum is null\n const thumbNum = this.thumbnails[0].frames.findIndex(\n (frame) => this.seekTime >= frame.startTime && this.seekTime <= frame.endTime,\n );\n const hasThumb = thumbNum >= 0;\n let qualityIndex = 0;\n\n // Show the thumb container if we're not scrubbing\n if (!this.mouseDown) {\n this.toggleThumbContainer(hasThumb);\n }\n\n // No matching thumb found\n if (!hasThumb) {\n return;\n }\n\n // Check to see if we've already downloaded higher quality versions of this image\n this.thumbnails.forEach((thumbnail, index) => {\n if (this.loadedImages.includes(thumbnail.frames[thumbNum].text)) {\n qualityIndex = index;\n }\n });\n\n // Only proceed if either thumbnum or thumbfilename has changed\n if (thumbNum !== this.showingThumb) {\n this.showingThumb = thumbNum;\n this.loadImage(qualityIndex);\n }\n };\n\n // Show the image that's currently specified in this.showingThumb\n loadImage = (qualityIndex = 0) => {\n const thumbNum = this.showingThumb;\n const thumbnail = this.thumbnails[qualityIndex];\n const { urlPrefix } = thumbnail;\n const frame = thumbnail.frames[thumbNum];\n const thumbFilename = thumbnail.frames[thumbNum].text;\n const thumbUrl = urlPrefix + thumbFilename;\n\n if (!this.currentImageElement || this.currentImageElement.dataset.filename !== thumbFilename) {\n // If we're already loading a previous image, remove its onload handler - we don't want it to load after this one\n // Only do this if not using sprites. Without sprites we really want to show as many images as possible, as a best-effort\n if (this.loadingImage && this.usingSprites) {\n this.loadingImage.onload = null;\n }\n\n // We're building and adding a new image. In other implementations of similar functionality (YouTube), background image\n // is instead used. But this causes issues with larger images in Firefox and Safari - switching between background\n // images causes a flicker. Putting a new image over the top does not\n const previewImage = new Image();\n previewImage.src = thumbUrl;\n previewImage.dataset.index = thumbNum;\n previewImage.dataset.filename = thumbFilename;\n this.showingThumbFilename = thumbFilename;\n\n this.player.debug.log(`Loading image: ${thumbUrl}`);\n\n // For some reason, passing the named function directly causes it to execute immediately. So I've wrapped it in an anonymous function...\n previewImage.onload = () => this.showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, true);\n this.loadingImage = previewImage;\n this.removeOldImages(previewImage);\n } else {\n // Update the existing image\n this.showImage(this.currentImageElement, frame, qualityIndex, thumbNum, thumbFilename, false);\n this.currentImageElement.dataset.index = thumbNum;\n this.removeOldImages(this.currentImageElement);\n }\n };\n\n showImage = (previewImage, frame, qualityIndex, thumbNum, thumbFilename, newImage = true) => {\n this.player.debug.log(\n `Showing thumb: ${thumbFilename}. num: ${thumbNum}. qual: ${qualityIndex}. newimg: ${newImage}`,\n );\n this.setImageSizeAndOffset(previewImage, frame);\n\n if (newImage) {\n this.currentImageContainer.appendChild(previewImage);\n this.currentImageElement = previewImage;\n\n if (!this.loadedImages.includes(thumbFilename)) {\n this.loadedImages.push(thumbFilename);\n }\n }\n\n // Preload images before and after the current one\n // Show higher quality of the same frame\n // 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\n this.preloadNearby(thumbNum, true)\n .then(this.preloadNearby(thumbNum, false))\n .then(this.getHigherQuality(qualityIndex, previewImage, frame, thumbFilename));\n };\n\n // Remove all preview images that aren't the designated current image\n removeOldImages = (currentImage) => {\n // Get a list of all images, convert it from a DOM list to an array\n Array.from(this.currentImageContainer.children).forEach((image) => {\n if (image.tagName.toLowerCase() !== 'img') {\n return;\n }\n\n const removeDelay = this.usingSprites ? 500 : 1000;\n\n if (image.dataset.index !== currentImage.dataset.index && !image.dataset.deleting) {\n // 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\n // First set attribute 'deleting' to prevent multi-handling of this on repeat firing of this function\n // eslint-disable-next-line no-param-reassign\n image.dataset.deleting = true;\n\n // This has to be set before the timeout - to prevent issues switching between hover and scrub\n const { currentImageContainer } = this;\n\n setTimeout(() => {\n currentImageContainer.removeChild(image);\n this.player.debug.log(`Removing thumb: ${image.dataset.filename}`);\n }, removeDelay);\n }\n });\n };\n\n // Preload images before and after the current one. Only if the user is still hovering/seeking the same frame\n // This will only preload the lowest quality\n preloadNearby = (thumbNum, forward = true) => {\n return new Promise((resolve) => {\n setTimeout(() => {\n const oldThumbFilename = this.thumbnails[0].frames[thumbNum].text;\n\n if (this.showingThumbFilename === oldThumbFilename) {\n // 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\n let thumbnailsClone;\n if (forward) {\n thumbnailsClone = this.thumbnails[0].frames.slice(thumbNum);\n } else {\n thumbnailsClone = this.thumbnails[0].frames.slice(0, thumbNum).reverse();\n }\n\n let foundOne = false;\n\n thumbnailsClone.forEach((frame) => {\n const newThumbFilename = frame.text;\n\n if (newThumbFilename !== oldThumbFilename) {\n // Found one with a different filename. Make sure it hasn't already been loaded on this page visit\n if (!this.loadedImages.includes(newThumbFilename)) {\n foundOne = true;\n this.player.debug.log(`Preloading thumb filename: ${newThumbFilename}`);\n\n const { urlPrefix } = this.thumbnails[0];\n const thumbURL = urlPrefix + newThumbFilename;\n const previewImage = new Image();\n previewImage.src = thumbURL;\n previewImage.onload = () => {\n this.player.debug.log(`Preloaded thumb filename: ${newThumbFilename}`);\n if (!this.loadedImages.includes(newThumbFilename)) this.loadedImages.push(newThumbFilename);\n\n // We don't resolve until the thumb is loaded\n resolve();\n };\n }\n }\n });\n\n // If there are none to preload then we want to resolve immediately\n if (!foundOne) {\n resolve();\n }\n }\n }, 300);\n });\n };\n\n // If user has been hovering current image for half a second, look for a higher quality one\n getHigherQuality = (currentQualityIndex, previewImage, frame, thumbFilename) => {\n if (currentQualityIndex < this.thumbnails.length - 1) {\n // 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\n let previewImageHeight = previewImage.naturalHeight;\n\n if (this.usingSprites) {\n previewImageHeight = frame.h;\n }\n\n if (previewImageHeight < this.thumbContainerHeight) {\n // Recurse back to the loadImage function - show a higher quality one, but only if the viewer is on this frame for a while\n setTimeout(() => {\n // Make sure the mouse hasn't already moved on and started hovering at another image\n if (this.showingThumbFilename === thumbFilename) {\n this.player.debug.log(`Showing higher quality thumb for: ${thumbFilename}`);\n this.loadImage(currentQualityIndex + 1);\n }\n }, 300);\n }\n }\n };\n\n get currentImageContainer() {\n if (this.mouseDown) {\n return this.elements.scrubbing.container;\n }\n\n return this.elements.thumb.imageContainer;\n }\n\n get usingSprites() {\n return Object.keys(this.thumbnails[0].frames[0]).includes('w');\n }\n\n get thumbAspectRatio() {\n if (this.usingSprites) {\n return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;\n }\n\n return this.thumbnails[0].width / this.thumbnails[0].height;\n }\n\n get thumbContainerHeight() {\n if (this.mouseDown) {\n const { height } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight,\n });\n return height;\n }\n\n // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset)\n if (this.sizeSpecifiedInCSS) {\n return this.elements.thumb.imageContainer.clientHeight;\n }\n\n return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);\n }\n\n get currentImageElement() {\n if (this.mouseDown) {\n return this.currentScrubbingImageElement;\n }\n\n return this.currentThumbnailImageElement;\n }\n\n set currentImageElement(element) {\n if (this.mouseDown) {\n this.currentScrubbingImageElement = element;\n } else {\n this.currentThumbnailImageElement = element;\n }\n }\n\n toggleThumbContainer = (toggle = false, clearShowing = false) => {\n const className = this.player.config.classNames.previewThumbnails.thumbContainerShown;\n this.elements.thumb.container.classList.toggle(className, toggle);\n\n if (!toggle && clearShowing) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n };\n\n toggleScrubbingContainer = (toggle = false) => {\n const className = this.player.config.classNames.previewThumbnails.scrubbingContainerShown;\n this.elements.scrubbing.container.classList.toggle(className, toggle);\n\n if (!toggle) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n };\n\n determineContainerAutoSizing = () => {\n if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) {\n // This will prevent auto sizing in this.setThumbContainerSizeAndPos()\n this.sizeSpecifiedInCSS = true;\n }\n };\n\n // 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\n setThumbContainerSizeAndPos = () => {\n if (!this.sizeSpecifiedInCSS) {\n const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${this.thumbContainerHeight}px`;\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (\n this.elements.thumb.imageContainer.clientHeight > 20 &&\n this.elements.thumb.imageContainer.clientWidth < 20\n ) {\n const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (\n this.elements.thumb.imageContainer.clientHeight < 20 &&\n this.elements.thumb.imageContainer.clientWidth > 20\n ) {\n const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`;\n }\n\n this.setThumbContainerPos();\n };\n\n setThumbContainerPos = () => {\n const seekbarRect = this.player.elements.progress.getBoundingClientRect();\n const plyrRect = this.player.elements.container.getBoundingClientRect();\n const { container } = this.elements.thumb;\n // Find the lowest and highest desired left-position, so we don't slide out the side of the video container\n const minVal = plyrRect.left - seekbarRect.left + 10;\n const maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10;\n // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth\n let previewPos = this.mousePosX - seekbarRect.left - container.clientWidth / 2;\n\n if (previewPos < minVal) {\n previewPos = minVal;\n }\n\n if (previewPos > maxVal) {\n previewPos = maxVal;\n }\n\n container.style.left = `${previewPos}px`;\n };\n\n // Can't use 100% width, in case the video is a different aspect ratio to the video container\n setScrubbingContainerSize = () => {\n const { width, height } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight,\n });\n this.elements.scrubbing.container.style.width = `${width}px`;\n this.elements.scrubbing.container.style.height = `${height}px`;\n };\n\n // Sprites need to be offset to the correct location\n setImageSizeAndOffset = (previewImage, frame) => {\n if (!this.usingSprites) {\n return;\n }\n\n // Find difference between height and preview container height\n const multiplier = this.thumbContainerHeight / frame.h;\n\n // eslint-disable-next-line no-param-reassign\n previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.left = `-${frame.x * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.top = `-${frame.y * multiplier}px`;\n };\n}\n\nexport default PreviewThumbnails;\n","// ==========================================================================\n// Plyr source update\n// ==========================================================================\n\nimport { providers } from './config/types';\nimport html5 from './html5';\nimport media from './media';\nimport PreviewThumbnails from './plugins/preview-thumbnails';\nimport support from './support';\nimport ui from './ui';\nimport { createElement, insertElement, removeElement } from './utils/elements';\nimport is from './utils/is';\nimport { getDeep } from './utils/objects';\n\nconst source = {\n // Add elements to HTML5 media (source, tracks, etc)\n insertElements(type, attributes) {\n if (is.string(attributes)) {\n insertElement(type, this.media, {\n src: attributes,\n });\n } else if (is.array(attributes)) {\n attributes.forEach((attribute) => {\n insertElement(type, this.media, attribute);\n });\n }\n },\n\n // Update source\n // Sources are not checked for support so be careful\n change(input) {\n if (!getDeep(input, 'sources.length')) {\n this.debug.warn('Invalid source format');\n return;\n }\n\n // Cancel current network requests\n html5.cancelRequests.call(this);\n\n // Destroy instance and re-setup\n this.destroy.call(\n this,\n () => {\n // Reset quality options\n this.options.quality = [];\n\n // Remove elements\n removeElement(this.media);\n this.media = null;\n\n // Reset class name\n if (is.element(this.elements.container)) {\n this.elements.container.removeAttribute('class');\n }\n\n // Set the type and provider\n const { sources, type } = input;\n const [{ provider = providers.html5, src }] = sources;\n const tagName = provider === 'html5' ? type : 'div';\n const attributes = provider === 'html5' ? {} : { src };\n\n Object.assign(this, {\n provider,\n type,\n // Check for support\n supported: support.check(type, provider, this.config.playsinline),\n // Create new element\n media: createElement(tagName, attributes),\n });\n\n // Inject the new element\n this.elements.container.appendChild(this.media);\n\n // Autoplay the new source?\n if (is.boolean(input.autoplay)) {\n this.config.autoplay = input.autoplay;\n }\n\n // Set attributes for audio and video\n if (this.isHTML5) {\n if (this.config.crossorigin) {\n this.media.setAttribute('crossorigin', '');\n }\n if (this.config.autoplay) {\n this.media.setAttribute('autoplay', '');\n }\n if (!is.empty(input.poster)) {\n this.poster = input.poster;\n }\n if (this.config.loop.active) {\n this.media.setAttribute('loop', '');\n }\n if (this.config.muted) {\n this.media.setAttribute('muted', '');\n }\n if (this.config.playsinline) {\n this.media.setAttribute('playsinline', '');\n }\n }\n\n // Restore class hook\n ui.addStyleHook.call(this);\n\n // Set new sources for html5\n if (this.isHTML5) {\n source.insertElements.call(this, 'source', sources);\n }\n\n // Set video title\n this.config.title = input.title;\n\n // Set up from scratch\n media.setup.call(this);\n\n // HTML5 stuff\n if (this.isHTML5) {\n // Setup captions\n if (Object.keys(input).includes('tracks')) {\n source.insertElements.call(this, 'track', input.tracks);\n }\n }\n\n // If HTML5 or embed but not fully supported, setupInterface and call ready now\n if (this.isHTML5 || (this.isEmbed && !this.supported.ui)) {\n // Setup interface\n ui.build.call(this);\n }\n\n // Load HTML5 sources\n if (this.isHTML5) {\n this.media.load();\n }\n\n // Update previewThumbnails config & reload plugin\n if (!is.empty(input.previewThumbnails)) {\n Object.assign(this.config.previewThumbnails, input.previewThumbnails);\n\n // Cleanup previewThumbnails plugin if it was loaded\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n // Create new instance if it is still enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n // Update the fullscreen support\n this.fullscreen.update();\n },\n true,\n );\n },\n};\n\nexport default source;\n","// ==========================================================================\n// Plyr\n// plyr.js v3.6.12\n// https://github.com/sampotts/plyr\n// License: The MIT License (MIT)\n// ==========================================================================\n\nimport captions from './captions';\nimport defaults from './config/defaults';\nimport { pip } from './config/states';\nimport { getProviderByUrl, providers, types } from './config/types';\nimport Console from './console';\nimport controls from './controls';\nimport Fullscreen from './fullscreen';\nimport html5 from './html5';\nimport Listeners from './listeners';\nimport media from './media';\nimport Ads from './plugins/ads';\nimport PreviewThumbnails from './plugins/preview-thumbnails';\nimport source from './source';\nimport Storage from './storage';\nimport support from './support';\nimport ui from './ui';\nimport { closest } from './utils/arrays';\nimport { createElement, hasClass, removeElement, replaceElement, toggleClass, wrap } from './utils/elements';\nimport { off, on, once, triggerEvent, unbindListeners } from './utils/events';\nimport is from './utils/is';\nimport loadSprite from './utils/load-sprite';\nimport { clamp } from './utils/numbers';\nimport { cloneDeep, extend } from './utils/objects';\nimport { silencePromise } from './utils/promise';\nimport { getAspectRatio, reduceAspectRatio, setAspectRatio, validateAspectRatio } from './utils/style';\nimport { parseUrl } from './utils/urls';\n\n// Private properties\n// TODO: Use a WeakMap for private globals\n// const globals = new WeakMap();\n\n// Plyr instance\nclass Plyr {\n constructor(target, options) {\n this.timers = {};\n\n // State\n this.ready = false;\n this.loading = false;\n this.failed = false;\n\n // Touch device\n this.touch = support.touch;\n\n // Set the media element\n this.media = target;\n\n // String selector passed\n if (is.string(this.media)) {\n this.media = document.querySelectorAll(this.media);\n }\n\n // jQuery, NodeList or Array passed, use first element\n if ((window.jQuery && this.media instanceof jQuery) || is.nodeList(this.media) || is.array(this.media)) {\n // eslint-disable-next-line\n this.media = this.media[0];\n }\n\n // Set config\n this.config = extend(\n {},\n defaults,\n Plyr.defaults,\n options || {},\n (() => {\n try {\n return JSON.parse(this.media.getAttribute('data-plyr-config'));\n } catch (_) {\n return {};\n }\n })(),\n );\n\n // Elements cache\n this.elements = {\n container: null,\n fullscreen: null,\n captions: null,\n buttons: {},\n display: {},\n progress: {},\n inputs: {},\n settings: {\n popup: null,\n menu: null,\n panels: {},\n buttons: {},\n },\n };\n\n // Captions\n this.captions = {\n active: null,\n currentTrack: -1,\n meta: new WeakMap(),\n };\n\n // Fullscreen\n this.fullscreen = {\n active: false,\n };\n\n // Options\n this.options = {\n speed: [],\n quality: [],\n };\n\n // Debugging\n // TODO: move to globals\n this.debug = new Console(this.config.debug);\n\n // Log config options and support\n this.debug.log('Config', this.config);\n this.debug.log('Support', support);\n\n // We need an element to setup\n if (is.nullOrUndefined(this.media) || !is.element(this.media)) {\n this.debug.error('Setup failed: no suitable element passed');\n return;\n }\n\n // Bail if the element is initialized\n if (this.media.plyr) {\n this.debug.warn('Target already setup');\n return;\n }\n\n // Bail if not enabled\n if (!this.config.enabled) {\n this.debug.error('Setup failed: disabled by config');\n return;\n }\n\n // Bail if disabled or no basic support\n // You may want to disable certain UAs etc\n if (!support.check().api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n // Cache original element state for .destroy()\n const clone = this.media.cloneNode(true);\n clone.autoplay = false;\n this.elements.original = clone;\n\n // Set media type based on tag or data attribute\n // Supported: video, audio, vimeo, youtube\n const type = this.media.tagName.toLowerCase();\n // Embed properties\n let iframe = null;\n let url = null;\n\n // Different setup based on type\n switch (type) {\n case 'div':\n // Find the frame\n iframe = this.media.querySelector('iframe');\n\n // <iframe> type\n if (is.element(iframe)) {\n // Detect provider\n url = parseUrl(iframe.getAttribute('src'));\n this.provider = getProviderByUrl(url.toString());\n\n // Rework elements\n this.elements.container = this.media;\n this.media = iframe;\n\n // Reset classname\n this.elements.container.className = '';\n\n // Get attributes from URL and set config\n if (url.search.length) {\n const truthy = ['1', 'true'];\n\n if (truthy.includes(url.searchParams.get('autoplay'))) {\n this.config.autoplay = true;\n }\n if (truthy.includes(url.searchParams.get('loop'))) {\n this.config.loop.active = true;\n }\n\n // TODO: replace fullscreen.iosNative with this playsinline config option\n // YouTube requires the playsinline in the URL\n if (this.isYouTube) {\n this.config.playsinline = truthy.includes(url.searchParams.get('playsinline'));\n this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language?\n } else {\n this.config.playsinline = true;\n }\n }\n } else {\n // <div> with attributes\n this.provider = this.media.getAttribute(this.config.attributes.embed.provider);\n\n // Remove attribute\n this.media.removeAttribute(this.config.attributes.embed.provider);\n }\n\n // Unsupported or missing provider\n if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) {\n this.debug.error('Setup failed: Invalid provider');\n return;\n }\n\n // Audio will come later for external providers\n this.type = types.video;\n\n break;\n\n case 'video':\n case 'audio':\n this.type = type;\n this.provider = providers.html5;\n\n // Get config from attributes\n if (this.media.hasAttribute('crossorigin')) {\n this.config.crossorigin = true;\n }\n if (this.media.hasAttribute('autoplay')) {\n this.config.autoplay = true;\n }\n if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) {\n this.config.playsinline = true;\n }\n if (this.media.hasAttribute('muted')) {\n this.config.muted = true;\n }\n if (this.media.hasAttribute('loop')) {\n this.config.loop.active = true;\n }\n\n break;\n\n default:\n this.debug.error('Setup failed: unsupported type');\n return;\n }\n\n // Check for support again but with type\n this.supported = support.check(this.type, this.provider, this.config.playsinline);\n\n // If no support for even API, bail\n if (!this.supported.api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n this.eventListeners = [];\n\n // Create listeners\n this.listeners = new Listeners(this);\n\n // Setup local storage for user settings\n this.storage = new Storage(this);\n\n // Store reference\n this.media.plyr = this;\n\n // Wrap media\n if (!is.element(this.elements.container)) {\n this.elements.container = createElement('div', { tabindex: 0 });\n wrap(this.media, this.elements.container);\n }\n\n // Migrate custom properties from media to container (so they work 😉)\n ui.migrateStyles.call(this);\n\n // Add style hook\n ui.addStyleHook.call(this);\n\n // Setup media\n media.setup.call(this);\n\n // Listen for events if debugging\n if (this.config.debug) {\n on.call(this, this.elements.container, this.config.events.join(' '), (event) => {\n this.debug.log(`event: ${event.type}`);\n });\n }\n\n // Setup fullscreen\n this.fullscreen = new Fullscreen(this);\n\n // Setup interface\n // If embed but not fully supported, build interface now to avoid flash of controls\n if (this.isHTML5 || (this.isEmbed && !this.supported.ui)) {\n ui.build.call(this);\n }\n\n // Container listeners\n this.listeners.container();\n\n // Global listeners\n this.listeners.global();\n\n // Setup ads if provided\n if (this.config.ads.enabled) {\n this.ads = new Ads(this);\n }\n\n // Autoplay if required\n if (this.isHTML5 && this.config.autoplay) {\n this.once('canplay', () => silencePromise(this.play()));\n }\n\n // Seek time will be recorded (in listeners.js) so we can prevent hiding controls for a few seconds after seek\n this.lastSeekTime = 0;\n\n // Setup preview thumbnails if enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n // ---------------------------------------\n // API\n // ---------------------------------------\n\n /**\n * Types and provider helpers\n */\n get isHTML5() {\n return this.provider === providers.html5;\n }\n\n get isEmbed() {\n return this.isYouTube || this.isVimeo;\n }\n\n get isYouTube() {\n return this.provider === providers.youtube;\n }\n\n get isVimeo() {\n return this.provider === providers.vimeo;\n }\n\n get isVideo() {\n return this.type === types.video;\n }\n\n get isAudio() {\n return this.type === types.audio;\n }\n\n /**\n * Play the media, or play the advertisement (if they are not blocked)\n */\n play = () => {\n if (!is.function(this.media.play)) {\n return null;\n }\n\n // Intecept play with ads\n if (this.ads && this.ads.enabled) {\n this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play()));\n }\n\n // Return the promise (for HTML5)\n return this.media.play();\n };\n\n /**\n * Pause the media\n */\n pause = () => {\n if (!this.playing || !is.function(this.media.pause)) {\n return null;\n }\n\n return this.media.pause();\n };\n\n /**\n * Get playing state\n */\n get playing() {\n return Boolean(this.ready && !this.paused && !this.ended);\n }\n\n /**\n * Get paused state\n */\n get paused() {\n return Boolean(this.media.paused);\n }\n\n /**\n * Get stopped state\n */\n get stopped() {\n return Boolean(this.paused && this.currentTime === 0);\n }\n\n /**\n * Get ended state\n */\n get ended() {\n return Boolean(this.media.ended);\n }\n\n /**\n * Toggle playback based on current status\n * @param {Boolean} input\n */\n togglePlay = (input) => {\n // Toggle based on current state if nothing passed\n const toggle = is.boolean(input) ? input : !this.playing;\n\n if (toggle) {\n return this.play();\n }\n\n return this.pause();\n };\n\n /**\n * Stop playback\n */\n stop = () => {\n if (this.isHTML5) {\n this.pause();\n this.restart();\n } else if (is.function(this.media.stop)) {\n this.media.stop();\n }\n };\n\n /**\n * Restart playback\n */\n restart = () => {\n this.currentTime = 0;\n };\n\n /**\n * Rewind\n * @param {Number} seekTime - how far to rewind in seconds. Defaults to the config.seekTime\n */\n rewind = (seekTime) => {\n this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime;\n };\n\n /**\n * Fast forward\n * @param {Number} seekTime - how far to fast forward in seconds. Defaults to the config.seekTime\n */\n forward = (seekTime) => {\n this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime;\n };\n\n /**\n * Seek to a time\n * @param {Number} input - where to seek to in seconds. Defaults to 0 (the start)\n */\n set currentTime(input) {\n // Bail if media duration isn't available yet\n if (!this.duration) {\n return;\n }\n\n // Validate input\n const inputIsValid = is.number(input) && input > 0;\n\n // Set\n this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0;\n\n // Logging\n this.debug.log(`Seeking to ${this.currentTime} seconds`);\n }\n\n /**\n * Get current time\n */\n get currentTime() {\n return Number(this.media.currentTime);\n }\n\n /**\n * Get buffered\n */\n get buffered() {\n const { buffered } = this.media;\n\n // YouTube / Vimeo return a float between 0-1\n if (is.number(buffered)) {\n return buffered;\n }\n\n // HTML5\n // TODO: Handle buffered chunks of the media\n // (i.e. seek to another section buffers only that section)\n if (buffered && buffered.length && this.duration > 0) {\n return buffered.end(0) / this.duration;\n }\n\n return 0;\n }\n\n /**\n * Get seeking status\n */\n get seeking() {\n return Boolean(this.media.seeking);\n }\n\n /**\n * Get the duration of the current media\n */\n get duration() {\n // Faux duration set via config\n const fauxDuration = parseFloat(this.config.duration);\n // Media duration can be NaN or Infinity before the media has loaded\n const realDuration = (this.media || {}).duration;\n const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration;\n\n // If config duration is funky, use regular duration\n return fauxDuration || duration;\n }\n\n /**\n * Set the player volume\n * @param {Number} value - must be between 0 and 1. Defaults to the value from local storage and config.volume if not set in storage\n */\n set volume(value) {\n let volume = value;\n const max = 1;\n const min = 0;\n\n if (is.string(volume)) {\n volume = Number(volume);\n }\n\n // Load volume from storage if no value specified\n if (!is.number(volume)) {\n volume = this.storage.get('volume');\n }\n\n // Use config if all else fails\n if (!is.number(volume)) {\n ({ volume } = this.config);\n }\n\n // Maximum is volumeMax\n if (volume > max) {\n volume = max;\n }\n // Minimum is volumeMin\n if (volume < min) {\n volume = min;\n }\n\n // Update config\n this.config.volume = volume;\n\n // Set the player volume\n this.media.volume = volume;\n\n // If muted, and we're increasing volume manually, reset muted state\n if (!is.empty(value) && this.muted && volume > 0) {\n this.muted = false;\n }\n }\n\n /**\n * Get the current player volume\n */\n get volume() {\n return Number(this.media.volume);\n }\n\n /**\n * Increase volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n increaseVolume = (step) => {\n const volume = this.media.muted ? 0 : this.volume;\n this.volume = volume + (is.number(step) ? step : 0);\n };\n\n /**\n * Decrease volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n decreaseVolume = (step) => {\n this.increaseVolume(-step);\n };\n\n /**\n * Set muted state\n * @param {Boolean} mute\n */\n set muted(mute) {\n let toggle = mute;\n\n // Load muted state from storage\n if (!is.boolean(toggle)) {\n toggle = this.storage.get('muted');\n }\n\n // Use config if all else fails\n if (!is.boolean(toggle)) {\n toggle = this.config.muted;\n }\n\n // Update config\n this.config.muted = toggle;\n\n // Set mute on the player\n this.media.muted = toggle;\n }\n\n /**\n * Get current muted state\n */\n get muted() {\n return Boolean(this.media.muted);\n }\n\n /**\n * Check if the media has audio\n */\n get hasAudio() {\n // Assume yes for all non HTML5 (as we can't tell...)\n if (!this.isHTML5) {\n return true;\n }\n\n if (this.isAudio) {\n return true;\n }\n\n // Get audio tracks\n return (\n Boolean(this.media.mozHasAudio) ||\n Boolean(this.media.webkitAudioDecodedByteCount) ||\n Boolean(this.media.audioTracks && this.media.audioTracks.length)\n );\n }\n\n /**\n * Set playback speed\n * @param {Number} speed - the speed of playback (0.5-2.0)\n */\n set speed(input) {\n let speed = null;\n\n if (is.number(input)) {\n speed = input;\n }\n\n if (!is.number(speed)) {\n speed = this.storage.get('speed');\n }\n\n if (!is.number(speed)) {\n speed = this.config.speed.selected;\n }\n\n // Clamp to min/max\n const { minimumSpeed: min, maximumSpeed: max } = this;\n speed = clamp(speed, min, max);\n\n // Update config\n this.config.speed.selected = speed;\n\n // Set media speed\n setTimeout(() => {\n if (this.media) {\n this.media.playbackRate = speed;\n }\n }, 0);\n }\n\n /**\n * Get current playback speed\n */\n get speed() {\n return Number(this.media.playbackRate);\n }\n\n /**\n * Get the minimum allowed speed\n */\n get minimumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.min(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 0.5;\n }\n\n // https://stackoverflow.com/a/32320020/1191319\n return 0.0625;\n }\n\n /**\n * Get the maximum allowed speed\n */\n get maximumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.max(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 2;\n }\n\n // https://stackoverflow.com/a/32320020/1191319\n return 16;\n }\n\n /**\n * Set playback quality\n * Currently HTML5 & YouTube only\n * @param {Number} input - Quality level\n */\n set quality(input) {\n const config = this.config.quality;\n const options = this.options.quality;\n\n if (!options.length) {\n return;\n }\n\n let quality = [\n !is.empty(input) && Number(input),\n this.storage.get('quality'),\n config.selected,\n config.default,\n ].find(is.number);\n\n let updateStorage = true;\n\n if (!options.includes(quality)) {\n const value = closest(options, quality);\n this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`);\n quality = value;\n\n // Don't update storage if quality is not supported\n updateStorage = false;\n }\n\n // Update config\n config.selected = quality;\n\n // Set quality\n this.media.quality = quality;\n\n // Save to storage\n if (updateStorage) {\n this.storage.set({ quality });\n }\n }\n\n /**\n * Get current quality level\n */\n get quality() {\n return this.media.quality;\n }\n\n /**\n * Toggle loop\n * TODO: Finish fancy new logic. Set the indicator on load as user may pass loop as config\n * @param {Boolean} input - Whether to loop or not\n */\n set loop(input) {\n const toggle = is.boolean(input) ? input : this.config.loop.active;\n this.config.loop.active = toggle;\n this.media.loop = toggle;\n\n // Set default to be a true toggle\n /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle';\n\n switch (type) {\n case 'start':\n if (this.config.loop.end && this.config.loop.end <= this.currentTime) {\n this.config.loop.end = null;\n }\n this.config.loop.start = this.currentTime;\n // this.config.loop.indicator.start = this.elements.display.played.value;\n break;\n\n case 'end':\n if (this.config.loop.start >= this.currentTime) {\n return this;\n }\n this.config.loop.end = this.currentTime;\n // this.config.loop.indicator.end = this.elements.display.played.value;\n break;\n\n case 'all':\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n this.config.loop.indicator.start = 0;\n this.config.loop.indicator.end = 100;\n break;\n\n case 'toggle':\n if (this.config.loop.active) {\n this.config.loop.start = 0;\n this.config.loop.end = null;\n } else {\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n }\n break;\n\n default:\n this.config.loop.start = 0;\n this.config.loop.end = null;\n break;\n } */\n }\n\n /**\n * Get current loop state\n */\n get loop() {\n return Boolean(this.media.loop);\n }\n\n /**\n * Set new media source\n * @param {Object} input - The new source object (see docs)\n */\n set source(input) {\n source.change.call(this, input);\n }\n\n /**\n * Get current source\n */\n get source() {\n return this.media.currentSrc;\n }\n\n /**\n * Get a download URL (either source or custom)\n */\n get download() {\n const { download } = this.config.urls;\n\n return is.url(download) ? download : this.source;\n }\n\n /**\n * Set the download URL\n */\n set download(input) {\n if (!is.url(input)) {\n return;\n }\n\n this.config.urls.download = input;\n\n controls.setDownloadUrl.call(this);\n }\n\n /**\n * Set the poster image for a video\n * @param {String} input - the URL for the new poster image\n */\n set poster(input) {\n if (!this.isVideo) {\n this.debug.warn('Poster can only be set for video');\n return;\n }\n\n ui.setPoster.call(this, input, false).catch(() => {});\n }\n\n /**\n * Get the current poster image\n */\n get poster() {\n if (!this.isVideo) {\n return null;\n }\n\n return this.media.getAttribute('poster') || this.media.getAttribute('data-poster');\n }\n\n /**\n * Get the current aspect ratio in use\n */\n get ratio() {\n if (!this.isVideo) {\n return null;\n }\n\n const ratio = reduceAspectRatio(getAspectRatio.call(this));\n\n return is.array(ratio) ? ratio.join(':') : ratio;\n }\n\n /**\n * Set video aspect ratio\n */\n set ratio(input) {\n if (!this.isVideo) {\n this.debug.warn('Aspect ratio can only be set for video');\n return;\n }\n\n if (!is.string(input) || !validateAspectRatio(input)) {\n this.debug.error(`Invalid aspect ratio specified (${input})`);\n return;\n }\n\n this.config.ratio = reduceAspectRatio(input);\n\n setAspectRatio.call(this);\n }\n\n /**\n * Set the autoplay state\n * @param {Boolean} input - Whether to autoplay or not\n */\n set autoplay(input) {\n const toggle = is.boolean(input) ? input : this.config.autoplay;\n this.config.autoplay = toggle;\n }\n\n /**\n * Get the current autoplay state\n */\n get autoplay() {\n return Boolean(this.config.autoplay);\n }\n\n /**\n * Toggle captions\n * @param {Boolean} input - Whether to enable captions\n */\n toggleCaptions(input) {\n captions.toggle.call(this, input, false);\n }\n\n /**\n * Set the caption track by index\n * @param {Number} - Caption index\n */\n set currentTrack(input) {\n captions.set.call(this, input, false);\n captions.setup();\n }\n\n /**\n * Get the current caption track index (-1 if disabled)\n */\n get currentTrack() {\n const { toggled, currentTrack } = this.captions;\n return toggled ? currentTrack : -1;\n }\n\n /**\n * Set the wanted language for captions\n * Since tracks can be added later it won't update the actual caption track until there is a matching track\n * @param {String} - Two character ISO language code (e.g. EN, FR, PT, etc)\n */\n set language(input) {\n captions.setLanguage.call(this, input, false);\n }\n\n /**\n * Get the current track's language\n */\n get language() {\n return (captions.getCurrentTrack.call(this) || {}).language;\n }\n\n /**\n * Toggle picture-in-picture playback on WebKit/MacOS\n * TODO: update player with state, support, enabled\n * TODO: detect outside changes\n */\n set pip(input) {\n // Bail if no support\n if (!support.pip) {\n return;\n }\n\n // Toggle based on current state if not passed\n const toggle = is.boolean(input) ? input : !this.pip;\n\n // Toggle based on current state\n // Safari\n if (is.function(this.media.webkitSetPresentationMode)) {\n this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive);\n }\n\n // Chrome\n if (is.function(this.media.requestPictureInPicture)) {\n if (!this.pip && toggle) {\n this.media.requestPictureInPicture();\n } else if (this.pip && !toggle) {\n document.exitPictureInPicture();\n }\n }\n }\n\n /**\n * Get the current picture-in-picture state\n */\n get pip() {\n if (!support.pip) {\n return null;\n }\n\n // Safari\n if (!is.empty(this.media.webkitPresentationMode)) {\n return this.media.webkitPresentationMode === pip.active;\n }\n\n // Chrome\n return this.media === document.pictureInPictureElement;\n }\n\n /**\n * Sets the preview thubmnails for the current source\n */\n setPreviewThumbnails(thumbnailSource) {\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n Object.assign(this.config.previewThumbnails, thumbnailSource);\n\n // Create new instance if it is still enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n /**\n * Trigger the airplay dialog\n * TODO: update player with state, support, enabled\n */\n airplay = () => {\n // Show dialog if supported\n if (support.airplay) {\n this.media.webkitShowPlaybackTargetPicker();\n }\n };\n\n /**\n * Toggle the player controls\n * @param {Boolean} [toggle] - Whether to show the controls\n */\n toggleControls = (toggle) => {\n // Don't toggle if missing UI support or if it's audio\n if (this.supported.ui && !this.isAudio) {\n // Get state before change\n const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls);\n // Negate the argument if not undefined since adding the class to hides the controls\n const force = typeof toggle === 'undefined' ? undefined : !toggle;\n // Apply and get updated state\n const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force);\n\n // Close menu\n if (\n hiding &&\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n !is.empty(this.config.settings)\n ) {\n controls.toggleMenu.call(this, false);\n }\n\n // Trigger event on change\n if (hiding !== isHidden) {\n const eventName = hiding ? 'controlshidden' : 'controlsshown';\n triggerEvent.call(this, this.media, eventName);\n }\n\n return !hiding;\n }\n\n return false;\n };\n\n /**\n * Add event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n on = (event, callback) => {\n on.call(this, this.elements.container, event, callback);\n };\n\n /**\n * Add event listeners once\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n once = (event, callback) => {\n once.call(this, this.elements.container, event, callback);\n };\n\n /**\n * Remove event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n off = (event, callback) => {\n off(this.elements.container, event, callback);\n };\n\n /**\n * Destroy an instance\n * Event listeners are removed when elements are removed\n * http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory\n * @param {Function} callback - Callback for when destroy is complete\n * @param {Boolean} soft - Whether it's a soft destroy (for source changes etc)\n */\n destroy = (callback, soft = false) => {\n if (!this.ready) {\n return;\n }\n\n const done = () => {\n // Reset overflow (incase destroyed while in fullscreen)\n document.body.style.overflow = '';\n\n // GC for embed\n this.embed = null;\n\n // If it's a soft destroy, make minimal changes\n if (soft) {\n if (Object.keys(this.elements).length) {\n // Remove elements\n removeElement(this.elements.buttons.play);\n removeElement(this.elements.captions);\n removeElement(this.elements.controls);\n removeElement(this.elements.wrapper);\n\n // Clear for GC\n this.elements.buttons.play = null;\n this.elements.captions = null;\n this.elements.controls = null;\n this.elements.wrapper = null;\n }\n\n // Callback\n if (is.function(callback)) {\n callback();\n }\n } else {\n // Unbind listeners\n unbindListeners.call(this);\n\n // Cancel current network requests\n html5.cancelRequests.call(this);\n\n // Replace the container with the original element provided\n replaceElement(this.elements.original, this.elements.container);\n\n // Event\n triggerEvent.call(this, this.elements.original, 'destroyed', true);\n\n // Callback\n if (is.function(callback)) {\n callback.call(this.elements.original);\n }\n\n // Reset state\n this.ready = false;\n\n // Clear for garbage collection\n setTimeout(() => {\n this.elements = null;\n this.media = null;\n }, 200);\n }\n };\n\n // Stop playback\n this.stop();\n\n // Clear timeouts\n clearTimeout(this.timers.loading);\n clearTimeout(this.timers.controls);\n clearTimeout(this.timers.resized);\n\n // Provider specific stuff\n if (this.isHTML5) {\n // Restore native video controls\n ui.toggleNativeControls.call(this, true);\n\n // Clean up\n done();\n } else if (this.isYouTube) {\n // Clear timers\n clearInterval(this.timers.buffering);\n clearInterval(this.timers.playing);\n\n // Destroy YouTube API\n if (this.embed !== null && is.function(this.embed.destroy)) {\n this.embed.destroy();\n }\n\n // Clean up\n done();\n } else if (this.isVimeo) {\n // Destroy Vimeo API\n // then clean up (wait, to prevent postmessage errors)\n if (this.embed !== null) {\n this.embed.unload().then(done);\n }\n\n // Vimeo does not always return\n setTimeout(done, 200);\n }\n };\n\n /**\n * Check for support for a mime type (HTML5 only)\n * @param {String} type - Mime type\n */\n supports = (type) => support.mime.call(this, type);\n\n /**\n * Check for support\n * @param {String} type - Player type (audio/video)\n * @param {String} provider - Provider (html5/youtube/vimeo)\n * @param {Boolean} inline - Where player has `playsinline` sttribute\n */\n static supported(type, provider, inline) {\n return support.check(type, provider, inline);\n }\n\n /**\n * Load an SVG sprite into the page\n * @param {String} url - URL for the SVG sprite\n * @param {String} [id] - Unique ID\n */\n static loadSprite(url, id) {\n return loadSprite(url, id);\n }\n\n /**\n * Setup multiple instances\n * @param {*} selector\n * @param {Object} options\n */\n static setup(selector, options = {}) {\n let targets = null;\n\n if (is.string(selector)) {\n targets = Array.from(document.querySelectorAll(selector));\n } else if (is.nodeList(selector)) {\n targets = Array.from(selector);\n } else if (is.array(selector)) {\n targets = selector.filter(is.element);\n }\n\n if (is.empty(targets)) {\n return null;\n }\n\n return targets.map((t) => new Plyr(t, options));\n }\n}\n\nPlyr.defaults = cloneDeep(defaults);\n\nexport default Plyr;\n","/**\n * Returns a number whose value is limited to the given range.\n *\n * Example: limit the output of this computation to between 0 and 255\n * (x * 255).clamp(0, 255)\n *\n * @param {Number} input\n * @param {Number} min The lower boundary of the output range\n * @param {Number} max The upper boundary of the output range\n * @returns A number in the range [min, max]\n * @type Number\n */\nexport function clamp(input = 0, min = 0, max = 255) {\n return Math.min(Math.max(input, min), max);\n}\n\nexport default { clamp };\n"]}
\ No newline at end of file diff --git a/extlib/plyr/plyr.polyfilled.min.mjs b/extlib/plyr/plyr.polyfilled.min.mjs new file mode 100644 index 00000000..9ec22df6 --- /dev/null +++ b/extlib/plyr/plyr.polyfilled.min.mjs @@ -0,0 +1 @@ +!function(){if("undefined"!=typeof window)try{var e=new window.CustomEvent("test",{cancelable:!0});if(e.preventDefault(),!0!==e.defaultPrevented)throw new Error("Could not prevent default")}catch(e){var t=function(e,t){var i,s;return(t=t||{}).bubbles=!!t.bubbles,t.cancelable=!!t.cancelable,(i=document.createEvent("CustomEvent")).initCustomEvent(e,t.bubbles,t.cancelable,t.detail),s=i.preventDefault,i.preventDefault=function(){s.call(this);try{Object.defineProperty(this,"defaultPrevented",{get:function(){return!0}})}catch(e){this.defaultPrevented=!0}},i};t.prototype=window.Event.prototype,window.CustomEvent=t}}();var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(e,t){return e(t={exports:{}},t.exports),t.exports}function _defineProperty$1(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}function _createClass(e,t,i){return t&&_defineProperties(e.prototype,t),i&&_defineProperties(e,i),e}function _defineProperty(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function ownKeys(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(i),!0).forEach((function(t){_defineProperty(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ownKeys(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}!function(e){var t=function(){try{return!!Symbol.iterator}catch(e){return!1}}(),i=function(e){var i={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return t&&(i[Symbol.iterator]=function(){return i}),i},s=function(e){return encodeURIComponent(e).replace(/%20/g,"+")},n=function(e){return decodeURIComponent(String(e).replace(/\+/g," "))};(function(){try{var t=e.URLSearchParams;return"a=1"===new t("?a=1").toString()&&"function"==typeof t.prototype.set&&"function"==typeof t.prototype.entries}catch(e){return!1}})()||function(){var n=function(e){Object.defineProperty(this,"_entries",{writable:!0,value:{}});var t=typeof e;if("undefined"===t);else if("string"===t)""!==e&&this._fromString(e);else if(e instanceof n){var i=this;e.forEach((function(e,t){i.append(t,e)}))}else{if(null===e||"object"!==t)throw new TypeError("Unsupported input's type for URLSearchParams");if("[object Array]"===Object.prototype.toString.call(e))for(var s=0;s<e.length;s++){var r=e[s];if("[object Array]"!==Object.prototype.toString.call(r)&&2===r.length)throw new TypeError("Expected [string, any] as entry at index "+s+" of URLSearchParams's input");this.append(r[0],r[1])}else for(var o in e)e.hasOwnProperty(o)&&this.append(o,e[o])}},r=n.prototype;r.append=function(e,t){e in this._entries?this._entries[e].push(String(t)):this._entries[e]=[String(t)]},r.delete=function(e){delete this._entries[e]},r.get=function(e){return e in this._entries?this._entries[e][0]:null},r.getAll=function(e){return e in this._entries?this._entries[e].slice(0):[]},r.has=function(e){return e in this._entries},r.set=function(e,t){this._entries[e]=[String(t)]},r.forEach=function(e,t){var i;for(var s in this._entries)if(this._entries.hasOwnProperty(s)){i=this._entries[s];for(var n=0;n<i.length;n++)e.call(t,i[n],s,this)}},r.keys=function(){var e=[];return this.forEach((function(t,i){e.push(i)})),i(e)},r.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),i(e)},r.entries=function(){var e=[];return this.forEach((function(t,i){e.push([i,t])})),i(e)},t&&(r[Symbol.iterator]=r.entries),r.toString=function(){var e=[];return this.forEach((function(t,i){e.push(s(i)+"="+s(t))})),e.join("&")},e.URLSearchParams=n}();var r=e.URLSearchParams.prototype;"function"!=typeof r.sort&&(r.sort=function(){var e=this,t=[];this.forEach((function(i,s){t.push([s,i]),e._entries||e.delete(s)})),t.sort((function(e,t){return e[0]<t[0]?-1:e[0]>t[0]?1:0})),e._entries&&(e._entries={});for(var i=0;i<t.length;i++)this.append(t[i][0],t[i][1])}),"function"!=typeof r._fromString&&Object.defineProperty(r,"_fromString",{enumerable:!1,configurable:!1,writable:!1,value:function(e){if(this._entries)this._entries={};else{var t=[];this.forEach((function(e,i){t.push(i)}));for(var i=0;i<t.length;i++)this.delete(t[i])}var s,r=(e=e.replace(/^\?/,"")).split("&");for(i=0;i<r.length;i++)s=r[i].split("="),this.append(n(s[0]),s.length>1?n(s[1]):"")}})}(void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof window?window:"undefined"!=typeof self?self:commonjsGlobal),function(e){if(function(){try{var t=new e.URL("b","http://a");return t.pathname="c d","http://a/c%20d"===t.href&&t.searchParams}catch(e){return!1}}()||function(){var t=e.URL,i=function(t,i){"string"!=typeof t&&(t=String(t)),i&&"string"!=typeof i&&(i=String(i));var s,n=document;if(i&&(void 0===e.location||i!==e.location.href)){i=i.toLowerCase(),(s=(n=document.implementation.createHTMLDocument("")).createElement("base")).href=i,n.head.appendChild(s);try{if(0!==s.href.indexOf(i))throw new Error(s.href)}catch(e){throw new Error("URL unable to set base "+i+" due to "+e)}}var r=n.createElement("a");r.href=t,s&&(n.body.appendChild(r),r.href=r.href);var o=n.createElement("input");if(o.type="url",o.value=t,":"===r.protocol||!/:/.test(r.href)||!o.checkValidity()&&!i)throw new TypeError("Invalid URL");Object.defineProperty(this,"_anchorElement",{value:r});var a=new e.URLSearchParams(this.search),l=!0,c=!0,u=this;["append","delete","set"].forEach((function(e){var t=a[e];a[e]=function(){t.apply(a,arguments),l&&(c=!1,u.search=a.toString(),c=!0)}})),Object.defineProperty(this,"searchParams",{value:a,enumerable:!0});var h=void 0;Object.defineProperty(this,"_updateSearchParams",{enumerable:!1,configurable:!1,writable:!1,value:function(){this.search!==h&&(h=this.search,c&&(l=!1,this.searchParams._fromString(this.search),l=!0))}})},s=i.prototype;["hash","host","hostname","port","protocol"].forEach((function(e){!function(e){Object.defineProperty(s,e,{get:function(){return this._anchorElement[e]},set:function(t){this._anchorElement[e]=t},enumerable:!0})}(e)})),Object.defineProperty(s,"search",{get:function(){return this._anchorElement.search},set:function(e){this._anchorElement.search=e,this._updateSearchParams()},enumerable:!0}),Object.defineProperties(s,{toString:{get:function(){var e=this;return function(){return e.href}}},href:{get:function(){return this._anchorElement.href.replace(/\?$/,"")},set:function(e){this._anchorElement.href=e,this._updateSearchParams()},enumerable:!0},pathname:{get:function(){return this._anchorElement.pathname.replace(/(^\/?)/,"/")},set:function(e){this._anchorElement.pathname=e},enumerable:!0},origin:{get:function(){var e={"http:":80,"https:":443,"ftp:":21}[this._anchorElement.protocol],t=this._anchorElement.port!=e&&""!==this._anchorElement.port;return this._anchorElement.protocol+"//"+this._anchorElement.hostname+(t?":"+this._anchorElement.port:"")},enumerable:!0},password:{get:function(){return""},set:function(e){},enumerable:!0},username:{get:function(){return""},set:function(e){},enumerable:!0}}),i.createObjectURL=function(e){return t.createObjectURL.apply(t,arguments)},i.revokeObjectURL=function(e){return t.revokeObjectURL.apply(t,arguments)},e.URL=i}(),void 0!==e.location&&!("origin"in e.location)){var t=function(){return e.location.protocol+"//"+e.location.hostname+(e.location.port?":"+e.location.port:"")};try{Object.defineProperty(e.location,"origin",{get:t,enumerable:!0})}catch(i){setInterval((function(){e.location.origin=t()}),100)}}}(void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof window?window:"undefined"!=typeof self?self:commonjsGlobal);var defaults$1={addCSS:!0,thumbWidth:15,watch:!0};function matches$1(e,t){return function(){return Array.from(document.querySelectorAll(t)).includes(this)}.call(e,t)}function trigger(e,t){if(e&&t){var i=new Event(t,{bubbles:!0});e.dispatchEvent(i)}}var getConstructor$1=function(e){return null!=e?e.constructor:null},instanceOf$1=function(e,t){return!!(e&&t&&e instanceof t)},isNullOrUndefined$1=function(e){return null==e},isObject$1=function(e){return getConstructor$1(e)===Object},isNumber$1=function(e){return getConstructor$1(e)===Number&&!Number.isNaN(e)},isString$1=function(e){return getConstructor$1(e)===String},isBoolean$1=function(e){return getConstructor$1(e)===Boolean},isFunction$1=function(e){return getConstructor$1(e)===Function},isArray$1=function(e){return Array.isArray(e)},isNodeList$1=function(e){return instanceOf$1(e,NodeList)},isElement$1=function(e){return instanceOf$1(e,Element)},isEvent$1=function(e){return instanceOf$1(e,Event)},isEmpty$1=function(e){return isNullOrUndefined$1(e)||(isString$1(e)||isArray$1(e)||isNodeList$1(e))&&!e.length||isObject$1(e)&&!Object.keys(e).length},is$1={nullOrUndefined:isNullOrUndefined$1,object:isObject$1,number:isNumber$1,string:isString$1,boolean:isBoolean$1,function:isFunction$1,array:isArray$1,nodeList:isNodeList$1,element:isElement$1,event:isEvent$1,empty:isEmpty$1};function getDecimalPlaces(e){var t="".concat(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0}function round(e,t){if(1>t){var i=getDecimalPlaces(t);return parseFloat(e.toFixed(i))}return Math.round(e/t)*t}var RangeTouch=function(){function e(t,i){_classCallCheck(this,e),is$1.element(t)?this.element=t:is$1.string(t)&&(this.element=document.querySelector(t)),is$1.element(this.element)&&is$1.empty(this.element.rangeTouch)&&(this.config=_objectSpread2({},defaults$1,{},i),this.init())}return _createClass(e,[{key:"init",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect="none",this.element.style.webKitUserSelect="none",this.element.style.touchAction="manipulation"),this.listeners(!0),this.element.rangeTouch=this)}},{key:"destroy",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect="",this.element.style.webKitUserSelect="",this.element.style.touchAction=""),this.listeners(!1),this.element.rangeTouch=null)}},{key:"listeners",value:function(e){var t=this,i=e?"addEventListener":"removeEventListener";["touchstart","touchmove","touchend"].forEach((function(e){t.element[i](e,(function(e){return t.set(e)}),!1)}))}},{key:"get",value:function(t){if(!e.enabled||!is$1.event(t))return null;var i,s=t.target,n=t.changedTouches[0],r=parseFloat(s.getAttribute("min"))||0,o=parseFloat(s.getAttribute("max"))||100,a=parseFloat(s.getAttribute("step"))||1,l=s.getBoundingClientRect(),c=100/l.width*(this.config.thumbWidth/2)/100;return 0>(i=100/l.width*(n.clientX-l.left))?i=0:100<i&&(i=100),50>i?i-=(100-2*i)*c:50<i&&(i+=2*(i-50)*c),r+round(i/100*(o-r),a)}},{key:"set",value:function(t){e.enabled&&is$1.event(t)&&!t.target.disabled&&(t.preventDefault(),t.target.value=this.get(t),trigger(t.target,"touchend"===t.type?"change":"input"))}}],[{key:"setup",value:function(t){var i=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},s=null;if(is$1.empty(t)||is$1.string(t)?s=Array.from(document.querySelectorAll(is$1.string(t)?t:'input[type="range"]')):is$1.element(t)?s=[t]:is$1.nodeList(t)?s=Array.from(t):is$1.array(t)&&(s=t.filter(is$1.element)),is$1.empty(s))return null;var n=_objectSpread2({},defaults$1,{},i);if(is$1.string(t)&&n.watch){var r=new MutationObserver((function(i){Array.from(i).forEach((function(i){Array.from(i.addedNodes).forEach((function(i){is$1.element(i)&&matches$1(i,t)&&new e(i,n)}))}))}));r.observe(document.body,{childList:!0,subtree:!0})}return s.map((function(t){return new e(t,i)}))}},{key:"enabled",get:function(){return"ontouchstart"in document.documentElement}}]),e}();const getConstructor=e=>null!=e?e.constructor:null,instanceOf=(e,t)=>Boolean(e&&t&&e instanceof t),isNullOrUndefined=e=>null==e,isObject=e=>getConstructor(e)===Object,isNumber=e=>getConstructor(e)===Number&&!Number.isNaN(e),isString=e=>getConstructor(e)===String,isBoolean=e=>getConstructor(e)===Boolean,isFunction=e=>getConstructor(e)===Function,isArray=e=>Array.isArray(e),isWeakMap=e=>instanceOf(e,WeakMap),isNodeList=e=>instanceOf(e,NodeList),isTextNode=e=>getConstructor(e)===Text,isEvent=e=>instanceOf(e,Event),isKeyboardEvent=e=>instanceOf(e,KeyboardEvent),isCue=e=>instanceOf(e,window.TextTrackCue)||instanceOf(e,window.VTTCue),isTrack=e=>instanceOf(e,TextTrack)||!isNullOrUndefined(e)&&isString(e.kind),isPromise=e=>instanceOf(e,Promise)&&isFunction(e.then),isElement=e=>null!==e&&"object"==typeof e&&1===e.nodeType&&"object"==typeof e.style&&"object"==typeof e.ownerDocument,isEmpty=e=>isNullOrUndefined(e)||(isString(e)||isArray(e)||isNodeList(e))&&!e.length||isObject(e)&&!Object.keys(e).length,isUrl=e=>{if(instanceOf(e,window.URL))return!0;if(!isString(e))return!1;let t=e;e.startsWith("http://")&&e.startsWith("https://")||(t=`http://${e}`);try{return!isEmpty(new URL(t).hostname)}catch(e){return!1}};var is={nullOrUndefined:isNullOrUndefined,object:isObject,number:isNumber,string:isString,boolean:isBoolean,function:isFunction,array:isArray,weakMap:isWeakMap,nodeList:isNodeList,element:isElement,textNode:isTextNode,event:isEvent,keyboardEvent:isKeyboardEvent,cue:isCue,track:isTrack,promise:isPromise,url:isUrl,empty:isEmpty};const transitionEndEvent=(()=>{const e=document.createElement("span"),t={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},i=Object.keys(t).find((t=>void 0!==e.style[t]));return!!is.string(i)&&t[i]})();function repaint(e,t){setTimeout((()=>{try{e.hidden=!0,e.offsetHeight,e.hidden=!1}catch(e){}}),t)}const browser={isIE:Boolean(window.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:"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1||/(iPad|iPhone|iPod)/gi.test(navigator.platform)};function cloneDeep(e){return JSON.parse(JSON.stringify(e))}function getDeep(e,t){return t.split(".").reduce(((e,t)=>e&&e[t]),e)}function extend(e={},...t){if(!t.length)return e;const i=t.shift();return is.object(i)?(Object.keys(i).forEach((t=>{is.object(i[t])?(Object.keys(e).includes(t)||Object.assign(e,{[t]:{}}),extend(e[t],i[t])):Object.assign(e,{[t]:i[t]})})),extend(e,...t)):e}function wrap(e,t){const i=e.length?e:[e];Array.from(i).reverse().forEach(((e,i)=>{const s=i>0?t.cloneNode(!0):t,n=e.parentNode,r=e.nextSibling;s.appendChild(e),r?n.insertBefore(s,r):n.appendChild(s)}))}function setAttributes(e,t){is.element(e)&&!is.empty(t)&&Object.entries(t).filter((([,e])=>!is.nullOrUndefined(e))).forEach((([t,i])=>e.setAttribute(t,i)))}function createElement(e,t,i){const s=document.createElement(e);return is.object(t)&&setAttributes(s,t),is.string(i)&&(s.innerText=i),s}function insertAfter(e,t){is.element(e)&&is.element(t)&&t.parentNode.insertBefore(e,t.nextSibling)}function insertElement(e,t,i,s){is.element(t)&&t.appendChild(createElement(e,i,s))}function removeElement(e){is.nodeList(e)||is.array(e)?Array.from(e).forEach(removeElement):is.element(e)&&is.element(e.parentNode)&&e.parentNode.removeChild(e)}function emptyElement(e){if(!is.element(e))return;let{length:t}=e.childNodes;for(;t>0;)e.removeChild(e.lastChild),t-=1}function replaceElement(e,t){return is.element(t)&&is.element(t.parentNode)&&is.element(e)?(t.parentNode.replaceChild(e,t),e):null}function getAttributesFromSelector(e,t){if(!is.string(e)||is.empty(e))return{};const i={},s=extend({},t);return e.split(",").forEach((e=>{const t=e.trim(),n=t.replace(".",""),r=t.replace(/[[\]]/g,"").split("="),[o]=r,a=r.length>1?r[1].replace(/["']/g,""):"";switch(t.charAt(0)){case".":is.string(s.class)?i.class=`${s.class} ${n}`:i.class=n;break;case"#":i.id=t.replace("#","");break;case"[":i[o]=a}})),extend(s,i)}function toggleHidden(e,t){if(!is.element(e))return;let i=t;is.boolean(i)||(i=!e.hidden),e.hidden=i}function toggleClass(e,t,i){if(is.nodeList(e))return Array.from(e).map((e=>toggleClass(e,t,i)));if(is.element(e)){let s="toggle";return void 0!==i&&(s=i?"add":"remove"),e.classList[s](t),e.classList.contains(t)}return!1}function hasClass(e,t){return is.element(e)&&e.classList.contains(t)}function matches(e,t){const{prototype:i}=Element;return(i.matches||i.webkitMatchesSelector||i.mozMatchesSelector||i.msMatchesSelector||function(){return Array.from(document.querySelectorAll(t)).includes(this)}).call(e,t)}function closest$1(e,t){const{prototype:i}=Element;return(i.closest||function(){let e=this;do{if(matches.matches(e,t))return e;e=e.parentElement||e.parentNode}while(null!==e&&1===e.nodeType);return null}).call(e,t)}function getElements(e){return this.elements.container.querySelectorAll(e)}function getElement(e){return this.elements.container.querySelector(e)}function setFocus(e=null,t=!1){is.element(e)&&(e.focus({preventScroll:!0}),t&&toggleClass(e,this.config.classNames.tabFocus))}const defaultCodecs={"audio/ogg":"vorbis","audio/wav":"1","video/webm":"vp8, vorbis","video/mp4":"avc1.42E01E, mp4a.40.2","video/ogg":"theora"},support={audio:"canPlayType"in document.createElement("audio"),video:"canPlayType"in document.createElement("video"),check(e,t,i){const s=browser.isIPhone&&i&&support.playsinline,n=support[e]||"html5"!==t;return{api:n,ui:n&&support.rangeInput&&("video"!==e||!browser.isIPhone||s)}},pip:!(browser.isIPhone||!is.function(createElement("video").webkitSetPresentationMode)&&(!document.pictureInPictureEnabled||createElement("video").disablePictureInPicture)),airplay:is.function(window.WebKitPlaybackTargetAvailabilityEvent),playsinline:"playsInline"in document.createElement("video"),mime(e){if(is.empty(e))return!1;const[t]=e.split("/");let i=e;if(!this.isHTML5||t!==this.type)return!1;Object.keys(defaultCodecs).includes(i)&&(i+=`; codecs="${defaultCodecs[e]}"`);try{return Boolean(i&&this.media.canPlayType(i).replace(/no/,""))}catch(e){return!1}},textTracks:"textTracks"in document.createElement("video"),rangeInput:(()=>{const e=document.createElement("input");return e.type="range","range"===e.type})(),touch:"ontouchstart"in document.documentElement,transitions:!1!==transitionEndEvent,reducedMotion:"matchMedia"in window&&window.matchMedia("(prefers-reduced-motion)").matches},supportsPassiveListeners=(()=>{let e=!1;try{const t=Object.defineProperty({},"passive",{get:()=>(e=!0,null)});window.addEventListener("test",null,t),window.removeEventListener("test",null,t)}catch(e){}return e})();function toggleListener(e,t,i,s=!1,n=!0,r=!1){if(!e||!("addEventListener"in e)||is.empty(t)||!is.function(i))return;const o=t.split(" ");let a=r;supportsPassiveListeners&&(a={passive:n,capture:r}),o.forEach((t=>{this&&this.eventListeners&&s&&this.eventListeners.push({element:e,type:t,callback:i,options:a}),e[s?"addEventListener":"removeEventListener"](t,i,a)}))}function on(e,t="",i,s=!0,n=!1){toggleListener.call(this,e,t,i,!0,s,n)}function off(e,t="",i,s=!0,n=!1){toggleListener.call(this,e,t,i,!1,s,n)}function once(e,t="",i,s=!0,n=!1){const r=(...o)=>{off(e,t,r,s,n),i.apply(this,o)};toggleListener.call(this,e,t,r,!0,s,n)}function triggerEvent(e,t="",i=!1,s={}){if(!is.element(e)||is.empty(t))return;const n=new CustomEvent(t,{bubbles:i,detail:{...s,plyr:this}});e.dispatchEvent(n)}function unbindListeners(){this&&this.eventListeners&&(this.eventListeners.forEach((e=>{const{element:t,type:i,callback:s,options:n}=e;t.removeEventListener(i,s,n)})),this.eventListeners=[])}function ready(){return new Promise((e=>this.ready?setTimeout(e,0):on.call(this,this.elements.container,"ready",e))).then((()=>{}))}function silencePromise(e){is.promise(e)&&e.then(null,(()=>{}))}function dedupe(e){return is.array(e)?e.filter(((t,i)=>e.indexOf(t)===i)):e}function closest(e,t){return is.array(e)&&e.length?e.reduce(((e,i)=>Math.abs(i-t)<Math.abs(e-t)?i:e)):null}function supportsCSS(e){return!(!window||!window.CSS)&&window.CSS.supports(e)}const standardRatios=[[1,1],[4,3],[3,4],[5,4],[4,5],[3,2],[2,3],[16,10],[10,16],[16,9],[9,16],[21,9],[9,21],[32,9],[9,32]].reduce(((e,[t,i])=>({...e,[t/i]:[t,i]})),{});function validateAspectRatio(e){if(!(is.array(e)||is.string(e)&&e.includes(":")))return!1;return(is.array(e)?e:e.split(":")).map(Number).every(is.number)}function reduceAspectRatio(e){if(!is.array(e)||!e.every(is.number))return null;const[t,i]=e,s=(e,t)=>0===t?e:s(t,e%t),n=s(t,i);return[t/n,i/n]}function getAspectRatio(e){const t=e=>validateAspectRatio(e)?e.split(":").map(Number):null;let i=t(e);if(null===i&&(i=t(this.config.ratio)),null===i&&!is.empty(this.embed)&&is.array(this.embed.ratio)&&({ratio:i}=this.embed),null===i&&this.isHTML5){const{videoWidth:e,videoHeight:t}=this.media;i=[e,t]}return reduceAspectRatio(i)}function setAspectRatio(e){if(!this.isVideo)return{};const{wrapper:t}=this.elements,i=getAspectRatio.call(this,e);if(!is.array(i))return{};const[s,n]=reduceAspectRatio(i),r=100/s*n;if(supportsCSS(`aspect-ratio: ${s}/${n}`)?t.style.aspectRatio=`${s}/${n}`:t.style.paddingBottom=`${r}%`,this.isVimeo&&!this.config.vimeo.premium&&this.supported.ui){const e=100/this.media.offsetWidth*parseInt(window.getComputedStyle(this.media).paddingBottom,10),i=(e-r)/(e/50);this.fullscreen.active?t.style.paddingBottom=null:this.media.style.transform=`translateY(-${i}%)`}else this.isHTML5&&t.classList.add(this.config.classNames.videoFixedRatio);return{padding:r,ratio:i}}function roundAspectRatio(e,t,i=.05){const s=e/t,n=closest(Object.keys(standardRatios),s);return Math.abs(n-s)<=i?standardRatios[n]:[e,t]}function getViewportSize(){return[Math.max(document.documentElement.clientWidth||0,window.innerWidth||0),Math.max(document.documentElement.clientHeight||0,window.innerHeight||0)]}const html5={getSources(){if(!this.isHTML5)return[];return Array.from(this.media.querySelectorAll("source")).filter((e=>{const t=e.getAttribute("type");return!!is.empty(t)||support.mime.call(this,t)}))},getQualityOptions(){return this.config.quality.forced?this.config.quality.options:html5.getSources.call(this).map((e=>Number(e.getAttribute("data-res")))).filter(Boolean)},setup(){if(!this.isHTML5)return;const e=this;e.options.speed=e.config.speed.options,is.empty(this.config.ratio)||setAspectRatio.call(e),Object.defineProperty(e.media,"quality",{get(){const t=html5.getSources.call(e).find((t=>t.getAttribute("src")===e.source));return t&&Number(t.getAttribute("data-res"))},set(t){if(e.quality!==t){if(e.config.quality.forced&&is.function(e.config.quality.onChange))e.config.quality.onChange(t);else{const i=html5.getSources.call(e).find((e=>Number(e.getAttribute("data-res"))===t));if(!i)return;const{currentTime:s,paused:n,preload:r,readyState:o,playbackRate:a}=e.media;e.media.src=i.getAttribute("src"),("none"!==r||o)&&(e.once("loadedmetadata",(()=>{e.speed=a,e.currentTime=s,n||silencePromise(e.play())})),e.media.load())}triggerEvent.call(e,e.media,"qualitychange",!1,{quality:t})}}})},cancelRequests(){this.isHTML5&&(removeElement(html5.getSources.call(this)),this.media.setAttribute("src",this.config.blankVideo),this.media.load(),this.debug.log("Cancelled network requests"))}};function generateId(e){return`${e}-${Math.floor(1e4*Math.random())}`}function format(e,...t){return is.empty(e)?e:e.toString().replace(/{(\d+)}/g,((e,i)=>t[i].toString()))}function getPercentage(e,t){return 0===e||0===t||Number.isNaN(e)||Number.isNaN(t)?0:(e/t*100).toFixed(2)}const replaceAll=(e="",t="",i="")=>e.replace(new RegExp(t.toString().replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1"),"g"),i.toString()),toTitleCase=(e="")=>e.toString().replace(/\w\S*/g,(e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()));function toPascalCase(e=""){let t=e.toString();return t=replaceAll(t,"-"," "),t=replaceAll(t,"_"," "),t=toTitleCase(t),replaceAll(t," ","")}function toCamelCase(e=""){let t=e.toString();return t=toPascalCase(t),t.charAt(0).toLowerCase()+t.slice(1)}function stripHTML(e){const t=document.createDocumentFragment(),i=document.createElement("div");return t.appendChild(i),i.innerHTML=e,t.firstChild.innerText}function getHTML(e){const t=document.createElement("div");return t.appendChild(e),t.innerHTML}const resources={pip:"PIP",airplay:"AirPlay",html5:"HTML5",vimeo:"Vimeo",youtube:"YouTube"},i18n={get(e="",t={}){if(is.empty(e)||is.empty(t))return"";let i=getDeep(t.i18n,e);if(is.empty(i))return Object.keys(resources).includes(e)?resources[e]:"";const s={"{seektime}":t.seekTime,"{title}":t.title};return Object.entries(s).forEach((([e,t])=>{i=replaceAll(i,e,t)})),i}};class Storage{constructor(e){_defineProperty$1(this,"get",(e=>{if(!Storage.supported||!this.enabled)return null;const t=window.localStorage.getItem(this.key);if(is.empty(t))return null;const i=JSON.parse(t);return is.string(e)&&e.length?i[e]:i})),_defineProperty$1(this,"set",(e=>{if(!Storage.supported||!this.enabled)return;if(!is.object(e))return;let t=this.get();is.empty(t)&&(t={}),extend(t,e);try{window.localStorage.setItem(this.key,JSON.stringify(t))}catch(e){}})),this.enabled=e.config.storage.enabled,this.key=e.config.storage.key}static get supported(){try{if(!("localStorage"in window))return!1;const e="___test";return window.localStorage.setItem(e,e),window.localStorage.removeItem(e),!0}catch(e){return!1}}}function fetch(e,t="text"){return new Promise(((i,s)=>{try{const s=new XMLHttpRequest;if(!("withCredentials"in s))return;s.addEventListener("load",(()=>{if("text"===t)try{i(JSON.parse(s.responseText))}catch(e){i(s.responseText)}else i(s.response)})),s.addEventListener("error",(()=>{throw new Error(s.status)})),s.open("GET",e,!0),s.responseType=t,s.send()}catch(e){s(e)}}))}function loadSprite(e,t){if(!is.string(e))return;const i=is.string(t);let s=!1;const n=()=>null!==document.getElementById(t),r=(e,t)=>{e.innerHTML=t,i&&n()||document.body.insertAdjacentElement("afterbegin",e)};if(!i||!n()){const n=Storage.supported,o=document.createElement("div");if(o.setAttribute("hidden",""),i&&o.setAttribute("id",t),n){const e=window.localStorage.getItem(`cache-${t}`);if(s=null!==e,s){const t=JSON.parse(e);r(o,t.content)}}fetch(e).then((e=>{if(!is.empty(e)){if(n)try{window.localStorage.setItem(`cache-${t}`,JSON.stringify({content:e}))}catch(e){}r(o,e)}})).catch((()=>{}))}}const getHours=e=>Math.trunc(e/60/60%60,10),getMinutes=e=>Math.trunc(e/60%60,10),getSeconds=e=>Math.trunc(e%60,10);function formatTime(e=0,t=!1,i=!1){if(!is.number(e))return formatTime(void 0,t,i);const s=e=>`0${e}`.slice(-2);let n=getHours(e);const r=(o=e,Math.trunc(o/60%60,10));var o;const a=getSeconds(e);return n=t||n>0?`${n}:`:"",`${i&&e>0?"-":""}${n}${s(r)}:${s(a)}`}const controls={getIconUrl(){const e=new URL(this.config.iconUrl,window.location),t=window.location.host?window.location.host:window.top.location.host,i=e.host!==t||browser.isIE&&!window.svg4everybody;return{url:this.config.iconUrl,cors:i}},findElements(){try{return this.elements.controls=getElement.call(this,this.config.selectors.controls.wrapper),this.elements.buttons={play:getElements.call(this,this.config.selectors.buttons.play),pause:getElement.call(this,this.config.selectors.buttons.pause),restart:getElement.call(this,this.config.selectors.buttons.restart),rewind:getElement.call(this,this.config.selectors.buttons.rewind),fastForward:getElement.call(this,this.config.selectors.buttons.fastForward),mute:getElement.call(this,this.config.selectors.buttons.mute),pip:getElement.call(this,this.config.selectors.buttons.pip),airplay:getElement.call(this,this.config.selectors.buttons.airplay),settings:getElement.call(this,this.config.selectors.buttons.settings),captions:getElement.call(this,this.config.selectors.buttons.captions),fullscreen:getElement.call(this,this.config.selectors.buttons.fullscreen)},this.elements.progress=getElement.call(this,this.config.selectors.progress),this.elements.inputs={seek:getElement.call(this,this.config.selectors.inputs.seek),volume:getElement.call(this,this.config.selectors.inputs.volume)},this.elements.display={buffer:getElement.call(this,this.config.selectors.display.buffer),currentTime:getElement.call(this,this.config.selectors.display.currentTime),duration:getElement.call(this,this.config.selectors.display.duration)},is.element(this.elements.progress)&&(this.elements.display.seekTooltip=this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`)),!0}catch(e){return this.debug.warn("It looks like there is a problem with your custom controls HTML",e),this.toggleNativeControls(!0),!1}},createIcon(e,t){const i="http://www.w3.org/2000/svg",s=controls.getIconUrl.call(this),n=`${s.cors?"":s.url}#${this.config.iconPrefix}`,r=document.createElementNS(i,"svg");setAttributes(r,extend(t,{"aria-hidden":"true",focusable:"false"}));const o=document.createElementNS(i,"use"),a=`${n}-${e}`;return"href"in o&&o.setAttributeNS("http://www.w3.org/1999/xlink","href",a),o.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",a),r.appendChild(o),r},createLabel(e,t={}){const i=i18n.get(e,this.config);return createElement("span",{...t,class:[t.class,this.config.classNames.hidden].filter(Boolean).join(" ")},i)},createBadge(e){if(is.empty(e))return null;const t=createElement("span",{class:this.config.classNames.menu.value});return t.appendChild(createElement("span",{class:this.config.classNames.menu.badge},e)),t},createButton(e,t){const i=extend({},t);let s=toCamelCase(e);const n={element:"button",toggle:!1,label:null,icon:null,labelPressed:null,iconPressed:null};switch(["element","icon","label"].forEach((e=>{Object.keys(i).includes(e)&&(n[e]=i[e],delete i[e])})),"button"!==n.element||Object.keys(i).includes("type")||(i.type="button"),Object.keys(i).includes("class")?i.class.split(" ").some((e=>e===this.config.classNames.control))||extend(i,{class:`${i.class} ${this.config.classNames.control}`}):i.class=this.config.classNames.control,e){case"play":n.toggle=!0,n.label="play",n.labelPressed="pause",n.icon="play",n.iconPressed="pause";break;case"mute":n.toggle=!0,n.label="mute",n.labelPressed="unmute",n.icon="volume",n.iconPressed="muted";break;case"captions":n.toggle=!0,n.label="enableCaptions",n.labelPressed="disableCaptions",n.icon="captions-off",n.iconPressed="captions-on";break;case"fullscreen":n.toggle=!0,n.label="enterFullscreen",n.labelPressed="exitFullscreen",n.icon="enter-fullscreen",n.iconPressed="exit-fullscreen";break;case"play-large":i.class+=` ${this.config.classNames.control}--overlaid`,s="play",n.label="play",n.icon="play";break;default:is.empty(n.label)&&(n.label=s),is.empty(n.icon)&&(n.icon=e)}const r=createElement(n.element);return n.toggle?(r.appendChild(controls.createIcon.call(this,n.iconPressed,{class:"icon--pressed"})),r.appendChild(controls.createIcon.call(this,n.icon,{class:"icon--not-pressed"})),r.appendChild(controls.createLabel.call(this,n.labelPressed,{class:"label--pressed"})),r.appendChild(controls.createLabel.call(this,n.label,{class:"label--not-pressed"}))):(r.appendChild(controls.createIcon.call(this,n.icon)),r.appendChild(controls.createLabel.call(this,n.label))),extend(i,getAttributesFromSelector(this.config.selectors.buttons[s],i)),setAttributes(r,i),"play"===s?(is.array(this.elements.buttons[s])||(this.elements.buttons[s]=[]),this.elements.buttons[s].push(r)):this.elements.buttons[s]=r,r},createRange(e,t){const i=createElement("input",extend(getAttributesFromSelector(this.config.selectors.inputs[e]),{type:"range",min:0,max:100,step:.01,value:0,autocomplete:"off",role:"slider","aria-label":i18n.get(e,this.config),"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":0},t));return this.elements.inputs[e]=i,controls.updateRangeFill.call(this,i),RangeTouch.setup(i),i},createProgress(e,t){const i=createElement("progress",extend(getAttributesFromSelector(this.config.selectors.display[e]),{min:0,max:100,value:0,role:"progressbar","aria-hidden":!0},t));if("volume"!==e){i.appendChild(createElement("span",null,"0"));const t={played:"played",buffer:"buffered"}[e],s=t?i18n.get(t,this.config):"";i.innerText=`% ${s.toLowerCase()}`}return this.elements.display[e]=i,i},createTime(e,t){const i=getAttributesFromSelector(this.config.selectors.display[e],t),s=createElement("div",extend(i,{class:`${i.class?i.class:""} ${this.config.classNames.display.time} `.trim(),"aria-label":i18n.get(e,this.config)}),"00:00");return this.elements.display[e]=s,s},bindMenuItemShortcuts(e,t){on.call(this,e,"keydown keyup",(i=>{if(![32,38,39,40].includes(i.which))return;if(i.preventDefault(),i.stopPropagation(),"keydown"===i.type)return;const s=matches(e,'[role="menuitemradio"]');if(!s&&[32,39].includes(i.which))controls.showMenuPanel.call(this,t,!0);else{let t;32!==i.which&&(40===i.which||s&&39===i.which?(t=e.nextElementSibling,is.element(t)||(t=e.parentNode.firstElementChild)):(t=e.previousElementSibling,is.element(t)||(t=e.parentNode.lastElementChild)),setFocus.call(this,t,!0))}}),!1),on.call(this,e,"keyup",(e=>{13===e.which&&controls.focusFirstMenuItem.call(this,null,!0)}))},createMenuItem({value:e,list:t,type:i,title:s,badge:n=null,checked:r=!1}){const o=getAttributesFromSelector(this.config.selectors.inputs[i]),a=createElement("button",extend(o,{type:"button",role:"menuitemradio",class:`${this.config.classNames.control} ${o.class?o.class:""}`.trim(),"aria-checked":r,value:e})),l=createElement("span");l.innerHTML=s,is.element(n)&&l.appendChild(n),a.appendChild(l),Object.defineProperty(a,"checked",{enumerable:!0,get:()=>"true"===a.getAttribute("aria-checked"),set(e){e&&Array.from(a.parentNode.children).filter((e=>matches(e,'[role="menuitemradio"]'))).forEach((e=>e.setAttribute("aria-checked","false"))),a.setAttribute("aria-checked",e?"true":"false")}}),this.listeners.bind(a,"click keyup",(t=>{if(!is.keyboardEvent(t)||32===t.which){switch(t.preventDefault(),t.stopPropagation(),a.checked=!0,i){case"language":this.currentTrack=Number(e);break;case"quality":this.quality=e;break;case"speed":this.speed=parseFloat(e)}controls.showMenuPanel.call(this,"home",is.keyboardEvent(t))}}),i,!1),controls.bindMenuItemShortcuts.call(this,a,i),t.appendChild(a)},formatTime(e=0,t=!1){if(!is.number(e))return e;return formatTime(e,getHours(this.duration)>0,t)},updateTimeDisplay(e=null,t=0,i=!1){is.element(e)&&is.number(t)&&(e.innerText=controls.formatTime(t,i))},updateVolume(){this.supported.ui&&(is.element(this.elements.inputs.volume)&&controls.setRange.call(this,this.elements.inputs.volume,this.muted?0:this.volume),is.element(this.elements.buttons.mute)&&(this.elements.buttons.mute.pressed=this.muted||0===this.volume))},setRange(e,t=0){is.element(e)&&(e.value=t,controls.updateRangeFill.call(this,e))},updateProgress(e){if(!this.supported.ui||!is.event(e))return;let t=0;const i=(e,t)=>{const i=is.number(t)?t:0,s=is.element(e)?e:this.elements.display.buffer;if(is.element(s)){s.value=i;const e=s.getElementsByTagName("span")[0];is.element(e)&&(e.childNodes[0].nodeValue=i)}};if(e)switch(e.type){case"timeupdate":case"seeking":case"seeked":t=getPercentage(this.currentTime,this.duration),"timeupdate"===e.type&&controls.setRange.call(this,this.elements.inputs.seek,t);break;case"playing":case"progress":i(this.elements.display.buffer,100*this.buffered)}},updateRangeFill(e){const t=is.event(e)?e.target:e;if(is.element(t)&&"range"===t.getAttribute("type")){if(matches(t,this.config.selectors.inputs.seek)){t.setAttribute("aria-valuenow",this.currentTime);const e=controls.formatTime(this.currentTime),i=controls.formatTime(this.duration),s=i18n.get("seekLabel",this.config);t.setAttribute("aria-valuetext",s.replace("{currentTime}",e).replace("{duration}",i))}else if(matches(t,this.config.selectors.inputs.volume)){const e=100*t.value;t.setAttribute("aria-valuenow",e),t.setAttribute("aria-valuetext",`${e.toFixed(1)}%`)}else t.setAttribute("aria-valuenow",t.value);browser.isWebkit&&t.style.setProperty("--value",t.value/t.max*100+"%")}},updateSeekTooltip(e){if(!this.config.tooltips.seek||!is.element(this.elements.inputs.seek)||!is.element(this.elements.display.seekTooltip)||0===this.duration)return;const t=`${this.config.classNames.tooltip}--visible`,i=e=>toggleClass(this.elements.display.seekTooltip,t,e);if(this.touch)return void i(!1);let s=0;const n=this.elements.progress.getBoundingClientRect();if(is.event(e))s=100/n.width*(e.pageX-n.left);else{if(!hasClass(this.elements.display.seekTooltip,t))return;s=parseFloat(this.elements.display.seekTooltip.style.left,10)}s<0?s=0:s>100&&(s=100),controls.updateTimeDisplay.call(this,this.elements.display.seekTooltip,this.duration/100*s),this.elements.display.seekTooltip.style.left=`${s}%`,is.event(e)&&["mouseenter","mouseleave"].includes(e.type)&&i("mouseenter"===e.type)},timeUpdate(e){const t=!is.element(this.elements.display.duration)&&this.config.invertTime;controls.updateTimeDisplay.call(this,this.elements.display.currentTime,t?this.duration-this.currentTime:this.currentTime,t),e&&"timeupdate"===e.type&&this.media.seeking||controls.updateProgress.call(this,e)},durationUpdate(){if(!this.supported.ui||!this.config.invertTime&&this.currentTime)return;if(this.duration>=2**32)return toggleHidden(this.elements.display.currentTime,!0),void toggleHidden(this.elements.progress,!0);is.element(this.elements.inputs.seek)&&this.elements.inputs.seek.setAttribute("aria-valuemax",this.duration);const e=is.element(this.elements.display.duration);!e&&this.config.displayDuration&&this.paused&&controls.updateTimeDisplay.call(this,this.elements.display.currentTime,this.duration),e&&controls.updateTimeDisplay.call(this,this.elements.display.duration,this.duration),controls.updateSeekTooltip.call(this)},toggleMenuButton(e,t){toggleHidden(this.elements.settings.buttons[e],!t)},updateSetting(e,t,i){const s=this.elements.settings.panels[e];let n=null,r=t;if("captions"===e)n=this.currentTrack;else{if(n=is.empty(i)?this[e]:i,is.empty(n)&&(n=this.config[e].default),!is.empty(this.options[e])&&!this.options[e].includes(n))return void this.debug.warn(`Unsupported value of '${n}' for ${e}`);if(!this.config[e].options.includes(n))return void this.debug.warn(`Disabled value of '${n}' for ${e}`)}if(is.element(r)||(r=s&&s.querySelector('[role="menu"]')),!is.element(r))return;this.elements.settings.buttons[e].querySelector(`.${this.config.classNames.menu.value}`).innerHTML=controls.getLabel.call(this,e,n);const o=r&&r.querySelector(`[value="${n}"]`);is.element(o)&&(o.checked=!0)},getLabel(e,t){switch(e){case"speed":return 1===t?i18n.get("normal",this.config):`${t}×`;case"quality":if(is.number(t)){const e=i18n.get(`qualityLabel.${t}`,this.config);return e.length?e:`${t}p`}return toTitleCase(t);case"captions":return captions.getLabel.call(this);default:return null}},setQualityMenu(e){if(!is.element(this.elements.settings.panels.quality))return;const t="quality",i=this.elements.settings.panels.quality.querySelector('[role="menu"]');is.array(e)&&(this.options.quality=dedupe(e).filter((e=>this.config.quality.options.includes(e))));const s=!is.empty(this.options.quality)&&this.options.quality.length>1;if(controls.toggleMenuButton.call(this,t,s),emptyElement(i),controls.checkMenu.call(this),!s)return;const n=e=>{const t=i18n.get(`qualityBadge.${e}`,this.config);return t.length?controls.createBadge.call(this,t):null};this.options.quality.sort(((e,t)=>{const i=this.config.quality.options;return i.indexOf(e)>i.indexOf(t)?1:-1})).forEach((e=>{controls.createMenuItem.call(this,{value:e,list:i,type:t,title:controls.getLabel.call(this,"quality",e),badge:n(e)})})),controls.updateSetting.call(this,t,i)},setCaptionsMenu(){if(!is.element(this.elements.settings.panels.captions))return;const e="captions",t=this.elements.settings.panels.captions.querySelector('[role="menu"]'),i=captions.getTracks.call(this),s=Boolean(i.length);if(controls.toggleMenuButton.call(this,e,s),emptyElement(t),controls.checkMenu.call(this),!s)return;const n=i.map(((e,i)=>({value:i,checked:this.captions.toggled&&this.currentTrack===i,title:captions.getLabel.call(this,e),badge:e.language&&controls.createBadge.call(this,e.language.toUpperCase()),list:t,type:"language"})));n.unshift({value:-1,checked:!this.captions.toggled,title:i18n.get("disabled",this.config),list:t,type:"language"}),n.forEach(controls.createMenuItem.bind(this)),controls.updateSetting.call(this,e,t)},setSpeedMenu(){if(!is.element(this.elements.settings.panels.speed))return;const e="speed",t=this.elements.settings.panels.speed.querySelector('[role="menu"]');this.options.speed=this.options.speed.filter((e=>e>=this.minimumSpeed&&e<=this.maximumSpeed));const i=!is.empty(this.options.speed)&&this.options.speed.length>1;controls.toggleMenuButton.call(this,e,i),emptyElement(t),controls.checkMenu.call(this),i&&(this.options.speed.forEach((i=>{controls.createMenuItem.call(this,{value:i,list:t,type:e,title:controls.getLabel.call(this,"speed",i)})})),controls.updateSetting.call(this,e,t))},checkMenu(){const{buttons:e}=this.elements.settings,t=!is.empty(e)&&Object.values(e).some((e=>!e.hidden));toggleHidden(this.elements.settings.menu,!t)},focusFirstMenuItem(e,t=!1){if(this.elements.settings.popup.hidden)return;let i=e;is.element(i)||(i=Object.values(this.elements.settings.panels).find((e=>!e.hidden)));const s=i.querySelector('[role^="menuitem"]');setFocus.call(this,s,t)},toggleMenu(e){const{popup:t}=this.elements.settings,i=this.elements.buttons.settings;if(!is.element(t)||!is.element(i))return;const{hidden:s}=t;let n=s;if(is.boolean(e))n=e;else if(is.keyboardEvent(e)&&27===e.which)n=!1;else if(is.event(e)){const s=is.function(e.composedPath)?e.composedPath()[0]:e.target,r=t.contains(s);if(r||!r&&e.target!==i&&n)return}i.setAttribute("aria-expanded",n),toggleHidden(t,!n),toggleClass(this.elements.container,this.config.classNames.menu.open,n),n&&is.keyboardEvent(e)?controls.focusFirstMenuItem.call(this,null,!0):n||s||setFocus.call(this,i,is.keyboardEvent(e))},getMenuSize(e){const t=e.cloneNode(!0);t.style.position="absolute",t.style.opacity=0,t.removeAttribute("hidden"),e.parentNode.appendChild(t);const i=t.scrollWidth,s=t.scrollHeight;return removeElement(t),{width:i,height:s}},showMenuPanel(e="",t=!1){const i=this.elements.container.querySelector(`#plyr-settings-${this.id}-${e}`);if(!is.element(i))return;const s=i.parentNode,n=Array.from(s.children).find((e=>!e.hidden));if(support.transitions&&!support.reducedMotion){s.style.width=`${n.scrollWidth}px`,s.style.height=`${n.scrollHeight}px`;const e=controls.getMenuSize.call(this,i),t=e=>{e.target===s&&["width","height"].includes(e.propertyName)&&(s.style.width="",s.style.height="",off.call(this,s,transitionEndEvent,t))};on.call(this,s,transitionEndEvent,t),s.style.width=`${e.width}px`,s.style.height=`${e.height}px`}toggleHidden(n,!0),toggleHidden(i,!1),controls.focusFirstMenuItem.call(this,i,t)},setDownloadUrl(){const e=this.elements.buttons.download;is.element(e)&&e.setAttribute("href",this.download)},create(e){const{bindMenuItemShortcuts:t,createButton:i,createProgress:s,createRange:n,createTime:r,setQualityMenu:o,setSpeedMenu:a,showMenuPanel:l}=controls;this.elements.controls=null,is.array(this.config.controls)&&this.config.controls.includes("play-large")&&this.elements.container.appendChild(i.call(this,"play-large"));const c=createElement("div",getAttributesFromSelector(this.config.selectors.controls.wrapper));this.elements.controls=c;const u={class:"plyr__controls__item"};return dedupe(is.array(this.config.controls)?this.config.controls:[]).forEach((o=>{if("restart"===o&&c.appendChild(i.call(this,"restart",u)),"rewind"===o&&c.appendChild(i.call(this,"rewind",u)),"play"===o&&c.appendChild(i.call(this,"play",u)),"fast-forward"===o&&c.appendChild(i.call(this,"fast-forward",u)),"progress"===o){const t=createElement("div",{class:`${u.class} plyr__progress__container`}),i=createElement("div",getAttributesFromSelector(this.config.selectors.progress));if(i.appendChild(n.call(this,"seek",{id:`plyr-seek-${e.id}`})),i.appendChild(s.call(this,"buffer")),this.config.tooltips.seek){const e=createElement("span",{class:this.config.classNames.tooltip},"00:00");i.appendChild(e),this.elements.display.seekTooltip=e}this.elements.progress=i,t.appendChild(this.elements.progress),c.appendChild(t)}if("current-time"===o&&c.appendChild(r.call(this,"currentTime",u)),"duration"===o&&c.appendChild(r.call(this,"duration",u)),"mute"===o||"volume"===o){let{volume:t}=this.elements;if(is.element(t)&&c.contains(t)||(t=createElement("div",extend({},u,{class:`${u.class} plyr__volume`.trim()})),this.elements.volume=t,c.appendChild(t)),"mute"===o&&t.appendChild(i.call(this,"mute")),"volume"===o&&!browser.isIos){const i={max:1,step:.05,value:this.config.volume};t.appendChild(n.call(this,"volume",extend(i,{id:`plyr-volume-${e.id}`})))}}if("captions"===o&&c.appendChild(i.call(this,"captions",u)),"settings"===o&&!is.empty(this.config.settings)){const s=createElement("div",extend({},u,{class:`${u.class} plyr__menu`.trim(),hidden:""}));s.appendChild(i.call(this,"settings",{"aria-haspopup":!0,"aria-controls":`plyr-settings-${e.id}`,"aria-expanded":!1}));const n=createElement("div",{class:"plyr__menu__container",id:`plyr-settings-${e.id}`,hidden:""}),r=createElement("div"),o=createElement("div",{id:`plyr-settings-${e.id}-home`}),a=createElement("div",{role:"menu"});o.appendChild(a),r.appendChild(o),this.elements.settings.panels.home=o,this.config.settings.forEach((i=>{const s=createElement("button",extend(getAttributesFromSelector(this.config.selectors.buttons.settings),{type:"button",class:`${this.config.classNames.control} ${this.config.classNames.control}--forward`,role:"menuitem","aria-haspopup":!0,hidden:""}));t.call(this,s,i),on.call(this,s,"click",(()=>{l.call(this,i,!1)}));const n=createElement("span",null,i18n.get(i,this.config)),o=createElement("span",{class:this.config.classNames.menu.value});o.innerHTML=e[i],n.appendChild(o),s.appendChild(n),a.appendChild(s);const c=createElement("div",{id:`plyr-settings-${e.id}-${i}`,hidden:""}),u=createElement("button",{type:"button",class:`${this.config.classNames.control} ${this.config.classNames.control}--back`});u.appendChild(createElement("span",{"aria-hidden":!0},i18n.get(i,this.config))),u.appendChild(createElement("span",{class:this.config.classNames.hidden},i18n.get("menuBack",this.config))),on.call(this,c,"keydown",(e=>{37===e.which&&(e.preventDefault(),e.stopPropagation(),l.call(this,"home",!0))}),!1),on.call(this,u,"click",(()=>{l.call(this,"home",!1)})),c.appendChild(u),c.appendChild(createElement("div",{role:"menu"})),r.appendChild(c),this.elements.settings.buttons[i]=s,this.elements.settings.panels[i]=c})),n.appendChild(r),s.appendChild(n),c.appendChild(s),this.elements.settings.popup=n,this.elements.settings.menu=s}if("pip"===o&&support.pip&&c.appendChild(i.call(this,"pip",u)),"airplay"===o&&support.airplay&&c.appendChild(i.call(this,"airplay",u)),"download"===o){const e=extend({},u,{element:"a",href:this.download,target:"_blank"});this.isHTML5&&(e.download="");const{download:t}=this.config.urls;!is.url(t)&&this.isEmbed&&extend(e,{icon:`logo-${this.provider}`,label:this.provider}),c.appendChild(i.call(this,"download",e))}"fullscreen"===o&&c.appendChild(i.call(this,"fullscreen",u))})),this.isHTML5&&o.call(this,html5.getQualityOptions.call(this)),a.call(this),c},inject(){if(this.config.loadSprite){const e=controls.getIconUrl.call(this);e.cors&&loadSprite(e.url,"sprite-plyr")}this.id=Math.floor(1e4*Math.random());let e=null;this.elements.controls=null;const t={id:this.id,seektime:this.config.seekTime,title:this.config.title};let i=!0;is.function(this.config.controls)&&(this.config.controls=this.config.controls.call(this,t)),this.config.controls||(this.config.controls=[]),is.element(this.config.controls)||is.string(this.config.controls)?e=this.config.controls:(e=controls.create.call(this,{id:this.id,seektime:this.config.seekTime,speed:this.speed,quality:this.quality,captions:captions.getLabel.call(this)}),i=!1);let s;i&&is.string(this.config.controls)&&(e=(e=>{let i=e;return Object.entries(t).forEach((([e,t])=>{i=replaceAll(i,`{${e}}`,t)})),i})(e)),is.string(this.config.selectors.controls.container)&&(s=document.querySelector(this.config.selectors.controls.container)),is.element(s)||(s=this.elements.container);if(s[is.element(e)?"insertAdjacentElement":"insertAdjacentHTML"]("afterbegin",e),is.element(this.elements.controls)||controls.findElements.call(this),!is.empty(this.elements.buttons)){const e=e=>{const t=this.config.classNames.controlPressed;Object.defineProperty(e,"pressed",{enumerable:!0,get:()=>hasClass(e,t),set(i=!1){toggleClass(e,t,i)}})};Object.values(this.elements.buttons).filter(Boolean).forEach((t=>{is.array(t)||is.nodeList(t)?Array.from(t).filter(Boolean).forEach(e):e(t)}))}if(browser.isEdge&&repaint(s),this.config.tooltips.controls){const{classNames:e,selectors:t}=this.config,i=`${t.controls.wrapper} ${t.labels} .${e.hidden}`,s=getElements.call(this,i);Array.from(s).forEach((e=>{toggleClass(e,this.config.classNames.hidden,!1),toggleClass(e,this.config.classNames.tooltip,!0)}))}}};function parseUrl(e,t=!0){let i=e;if(t){const e=document.createElement("a");e.href=i,i=e.href}try{return new URL(i)}catch(e){return null}}function buildUrlParams(e){const t=new URLSearchParams;return is.object(e)&&Object.entries(e).forEach((([e,i])=>{t.set(e,i)})),t}const captions={setup(){if(!this.supported.ui)return;if(!this.isVideo||this.isYouTube||this.isHTML5&&!support.textTracks)return void(is.array(this.config.controls)&&this.config.controls.includes("settings")&&this.config.settings.includes("captions")&&controls.setCaptionsMenu.call(this));if(is.element(this.elements.captions)||(this.elements.captions=createElement("div",getAttributesFromSelector(this.config.selectors.captions)),insertAfter(this.elements.captions,this.elements.wrapper)),browser.isIE&&window.URL){const e=this.media.querySelectorAll("track");Array.from(e).forEach((e=>{const t=e.getAttribute("src"),i=parseUrl(t);null!==i&&i.hostname!==window.location.href.hostname&&["http:","https:"].includes(i.protocol)&&fetch(t,"blob").then((t=>{e.setAttribute("src",window.URL.createObjectURL(t))})).catch((()=>{removeElement(e)}))}))}const e=dedupe((navigator.languages||[navigator.language||navigator.userLanguage||"en"]).map((e=>e.split("-")[0])));let t=(this.storage.get("language")||this.config.captions.language||"auto").toLowerCase();"auto"===t&&([t]=e);let i=this.storage.get("captions");if(is.boolean(i)||({active:i}=this.config.captions),Object.assign(this.captions,{toggled:!1,active:i,language:t,languages:e}),this.isHTML5){const e=this.config.captions.update?"addtrack removetrack":"removetrack";on.call(this,this.media.textTracks,e,captions.update.bind(this))}setTimeout(captions.update.bind(this),0)},update(){const e=captions.getTracks.call(this,!0),{active:t,language:i,meta:s,currentTrackNode:n}=this.captions,r=Boolean(e.find((e=>e.language===i)));this.isHTML5&&this.isVideo&&e.filter((e=>!s.get(e))).forEach((e=>{this.debug.log("Track added",e),s.set(e,{default:"showing"===e.mode}),"showing"===e.mode&&(e.mode="hidden"),on.call(this,e,"cuechange",(()=>captions.updateCues.call(this)))})),(r&&this.language!==i||!e.includes(n))&&(captions.setLanguage.call(this,i),captions.toggle.call(this,t&&r)),this.elements&&toggleClass(this.elements.container,this.config.classNames.captions.enabled,!is.empty(e)),is.array(this.config.controls)&&this.config.controls.includes("settings")&&this.config.settings.includes("captions")&&controls.setCaptionsMenu.call(this)},toggle(e,t=!0){if(!this.supported.ui)return;const{toggled:i}=this.captions,s=this.config.classNames.captions.active,n=is.nullOrUndefined(e)?!i:e;if(n!==i){if(t||(this.captions.active=n,this.storage.set({captions:n})),!this.language&&n&&!t){const e=captions.getTracks.call(this),t=captions.findTrack.call(this,[this.captions.language,...this.captions.languages],!0);return this.captions.language=t.language,void captions.set.call(this,e.indexOf(t))}this.elements.buttons.captions&&(this.elements.buttons.captions.pressed=n),toggleClass(this.elements.container,s,n),this.captions.toggled=n,controls.updateSetting.call(this,"captions"),triggerEvent.call(this,this.media,n?"captionsenabled":"captionsdisabled")}setTimeout((()=>{n&&this.captions.toggled&&(this.captions.currentTrackNode.mode="hidden")}))},set(e,t=!0){const i=captions.getTracks.call(this);if(-1!==e)if(is.number(e))if(e in i){if(this.captions.currentTrack!==e){this.captions.currentTrack=e;const s=i[e],{language:n}=s||{};this.captions.currentTrackNode=s,controls.updateSetting.call(this,"captions"),t||(this.captions.language=n,this.storage.set({language:n})),this.isVimeo&&this.embed.enableTextTrack(n),triggerEvent.call(this,this.media,"languagechange")}captions.toggle.call(this,!0,t),this.isHTML5&&this.isVideo&&captions.updateCues.call(this)}else this.debug.warn("Track not found",e);else this.debug.warn("Invalid caption argument",e);else captions.toggle.call(this,!1,t)},setLanguage(e,t=!0){if(!is.string(e))return void this.debug.warn("Invalid language argument",e);const i=e.toLowerCase();this.captions.language=i;const s=captions.getTracks.call(this),n=captions.findTrack.call(this,[i]);captions.set.call(this,s.indexOf(n),t)},getTracks(e=!1){return Array.from((this.media||{}).textTracks||[]).filter((t=>!this.isHTML5||e||this.captions.meta.has(t))).filter((e=>["captions","subtitles"].includes(e.kind)))},findTrack(e,t=!1){const i=captions.getTracks.call(this),s=e=>Number((this.captions.meta.get(e)||{}).default),n=Array.from(i).sort(((e,t)=>s(t)-s(e)));let r;return e.every((e=>(r=n.find((t=>t.language===e)),!r))),r||(t?n[0]:void 0)},getCurrentTrack(){return captions.getTracks.call(this)[this.currentTrack]},getLabel(e){let t=e;return!is.track(t)&&support.textTracks&&this.captions.toggled&&(t=captions.getCurrentTrack.call(this)),is.track(t)?is.empty(t.label)?is.empty(t.language)?i18n.get("enabled",this.config):e.language.toUpperCase():t.label:i18n.get("disabled",this.config)},updateCues(e){if(!this.supported.ui)return;if(!is.element(this.elements.captions))return void this.debug.warn("No captions element to render to");if(!is.nullOrUndefined(e)&&!Array.isArray(e))return void this.debug.warn("updateCues: Invalid input",e);let t=e;if(!t){const e=captions.getCurrentTrack.call(this);t=Array.from((e||{}).activeCues||[]).map((e=>e.getCueAsHTML())).map(getHTML)}const i=t.map((e=>e.trim())).join("\n");if(i!==this.elements.captions.innerHTML){emptyElement(this.elements.captions);const e=createElement("span",getAttributesFromSelector(this.config.selectors.caption));e.innerHTML=i,this.elements.captions.appendChild(e),triggerEvent.call(this,this.media,"cuechange")}}},defaults={enabled:!0,title:"",debug:!1,autoplay:!1,autopause:!0,playsinline:!0,seekTime:10,volume:1,muted:!1,duration:null,displayDuration:!0,invertTime:!0,toggleInvert:!0,ratio:null,clickToPlay:!0,hideControls:!0,resetOnEnd:!1,disableContextMenu:!0,loadSprite:!0,iconPrefix:"plyr",iconUrl:"https://cdn.plyr.io/3.6.12/plyr.svg",blankVideo:"https://cdn.plyr.io/static/blank.mp4",quality:{default:576,options:[4320,2880,2160,1440,1080,720,576,480,360,240],forced:!1,onChange:null},loop:{active:!1},speed:{selected:1,options:[.5,.75,1,1.25,1.5,1.75,2,4]},keyboard:{focused:!0,global:!1},tooltips:{controls:!1,seek:!0},captions:{active:!1,language:"auto",update:!1},fullscreen:{enabled:!0,fallback:!0,iosNative:!1},storage:{enabled:!0,key:"plyr"},controls:["play-large","play","progress","current-time","mute","volume","captions","settings","pip","airplay","fullscreen"],settings:["captions","quality","speed"],i18n:{restart:"Restart",rewind:"Rewind {seektime}s",play:"Play",pause:"Pause",fastForward:"Forward {seektime}s",seek:"Seek",seekLabel:"{currentTime} of {duration}",played:"Played",buffered:"Buffered",currentTime:"Current time",duration:"Duration",volume:"Volume",mute:"Mute",unmute:"Unmute",enableCaptions:"Enable captions",disableCaptions:"Disable captions",download:"Download",enterFullscreen:"Enter fullscreen",exitFullscreen:"Exit fullscreen",frameTitle:"Player for {title}",captions:"Captions",settings:"Settings",pip:"PIP",menuBack:"Go back to previous menu",speed:"Speed",normal:"Normal",quality:"Quality",loop:"Loop",start:"Start",end:"End",all:"All",reset:"Reset",disabled:"Disabled",enabled:"Enabled",advertisement:"Ad",qualityBadge:{2160:"4K",1440:"HD",1080:"HD",720:"HD",576:"SD",480:"SD"}},urls:{download:null,vimeo:{sdk:"https://player.vimeo.com/api/player.js",iframe:"https://player.vimeo.com/video/{0}?{1}",api:"https://vimeo.com/api/oembed.json?url={0}"},youtube:{sdk:"https://www.youtube.com/iframe_api",api:"https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}"},googleIMA:{sdk:"https://imasdk.googleapis.com/js/sdkloader/ima3.js"}},listeners:{seek:null,play:null,pause:null,restart:null,rewind:null,fastForward:null,mute:null,volume:null,captions:null,download:null,fullscreen:null,pip:null,airplay:null,speed:null,quality:null,loop:null,language:null},events:["ended","progress","stalled","playing","waiting","canplay","canplaythrough","loadstart","loadeddata","loadedmetadata","timeupdate","volumechange","play","pause","error","seeking","seeked","emptied","ratechange","cuechange","download","enterfullscreen","exitfullscreen","captionsenabled","captionsdisabled","languagechange","controlshidden","controlsshown","ready","statechange","qualitychange","adsloaded","adscontentpause","adscontentresume","adstarted","adsmidpoint","adscomplete","adsallcomplete","adsimpression","adsclick"],selectors:{editable:"input, textarea, select, [contenteditable]",container:".plyr",controls:{container:null,wrapper:".plyr__controls"},labels:"[data-plyr]",buttons:{play:'[data-plyr="play"]',pause:'[data-plyr="pause"]',restart:'[data-plyr="restart"]',rewind:'[data-plyr="rewind"]',fastForward:'[data-plyr="fast-forward"]',mute:'[data-plyr="mute"]',captions:'[data-plyr="captions"]',download:'[data-plyr="download"]',fullscreen:'[data-plyr="fullscreen"]',pip:'[data-plyr="pip"]',airplay:'[data-plyr="airplay"]',settings:'[data-plyr="settings"]',loop:'[data-plyr="loop"]'},inputs:{seek:'[data-plyr="seek"]',volume:'[data-plyr="volume"]',speed:'[data-plyr="speed"]',language:'[data-plyr="language"]',quality:'[data-plyr="quality"]'},display:{currentTime:".plyr__time--current",duration:".plyr__time--duration",buffer:".plyr__progress__buffer",loop:".plyr__progress__loop",volume:".plyr__volume--display"},progress:".plyr__progress",captions:".plyr__captions",caption:".plyr__caption"},classNames:{type:"plyr--{0}",provider:"plyr--{0}",video:"plyr__video-wrapper",embed:"plyr__video-embed",videoFixedRatio:"plyr__video-wrapper--fixed-ratio",embedContainer:"plyr__video-embed__container",poster:"plyr__poster",posterEnabled:"plyr__poster-enabled",ads:"plyr__ads",control:"plyr__control",controlPressed:"plyr__control--pressed",playing:"plyr--playing",paused:"plyr--paused",stopped:"plyr--stopped",loading:"plyr--loading",hover:"plyr--hover",tooltip:"plyr__tooltip",cues:"plyr__cues",hidden:"plyr__sr-only",hideControls:"plyr--hide-controls",isIos:"plyr--is-ios",isTouch:"plyr--is-touch",uiSupported:"plyr--full-ui",noTransition:"plyr--no-transition",display:{time:"plyr__time"},menu:{value:"plyr__menu__value",badge:"plyr__badge",open:"plyr--menu-open"},captions:{enabled:"plyr--captions-enabled",active:"plyr--captions-active"},fullscreen:{enabled:"plyr--fullscreen-enabled",fallback:"plyr--fullscreen-fallback"},pip:{supported:"plyr--pip-supported",active:"plyr--pip-active"},airplay:{supported:"plyr--airplay-supported",active:"plyr--airplay-active"},tabFocus:"plyr__tab-focus",previewThumbnails:{thumbContainer:"plyr__preview-thumb",thumbContainerShown:"plyr__preview-thumb--is-shown",imageContainer:"plyr__preview-thumb__image-container",timeContainer:"plyr__preview-thumb__time-container",scrubbingContainer:"plyr__preview-scrubbing",scrubbingContainerShown:"plyr__preview-scrubbing--is-shown"}},attributes:{embed:{provider:"data-plyr-provider",id:"data-plyr-embed-id",hash:"data-plyr-embed-hash"}},ads:{enabled:!1,publisherId:"",tagUrl:""},previewThumbnails:{enabled:!1,src:""},vimeo:{byline:!1,portrait:!1,title:!1,speed:!0,transparent:!1,customControls:!0,referrerPolicy:null,premium:!1},youtube:{rel:0,showinfo:0,iv_load_policy:3,modestbranding:1,customControls:!0,noCookie:!1}},pip={active:"picture-in-picture",inactive:"inline"},providers={html5:"html5",youtube:"youtube",vimeo:"vimeo"},types={audio:"audio",video:"video"};function getProviderByUrl(e){return/^(https?:\/\/)?(www\.)?(youtube\.com|youtube-nocookie\.com|youtu\.?be)\/.+$/.test(e)?providers.youtube:/^https?:\/\/player.vimeo.com\/video\/\d{0,9}(?=\b|\/)/.test(e)?providers.vimeo:null}const noop=()=>{};class Console{constructor(e=!1){this.enabled=window.console&&e,this.enabled&&this.log("Debugging enabled")}get log(){return this.enabled?Function.prototype.bind.call(console.log,console):noop}get warn(){return this.enabled?Function.prototype.bind.call(console.warn,console):noop}get error(){return this.enabled?Function.prototype.bind.call(console.error,console):noop}}class Fullscreen{constructor(e){_defineProperty$1(this,"onChange",(()=>{if(!this.enabled)return;const e=this.player.elements.buttons.fullscreen;is.element(e)&&(e.pressed=this.active);const t=this.target===this.player.media?this.target:this.player.elements.container;triggerEvent.call(this.player,t,this.active?"enterfullscreen":"exitfullscreen",!0)})),_defineProperty$1(this,"toggleFallback",((e=!1)=>{if(e?this.scrollPosition={x:window.scrollX||0,y:window.scrollY||0}:window.scrollTo(this.scrollPosition.x,this.scrollPosition.y),document.body.style.overflow=e?"hidden":"",toggleClass(this.target,this.player.config.classNames.fullscreen.fallback,e),browser.isIos){let t=document.head.querySelector('meta[name="viewport"]');const i="viewport-fit=cover";t||(t=document.createElement("meta"),t.setAttribute("name","viewport"));const s=is.string(t.content)&&t.content.includes(i);e?(this.cleanupViewport=!s,s||(t.content+=`,${i}`)):this.cleanupViewport&&(t.content=t.content.split(",").filter((e=>e.trim()!==i)).join(","))}this.onChange()})),_defineProperty$1(this,"trapFocus",(e=>{if(browser.isIos||!this.active||"Tab"!==e.key||9!==e.keyCode)return;const t=document.activeElement,i=getElements.call(this.player,"a[href], button:not(:disabled), input:not(:disabled), [tabindex]"),[s]=i,n=i[i.length-1];t!==n||e.shiftKey?t===s&&e.shiftKey&&(n.focus(),e.preventDefault()):(s.focus(),e.preventDefault())})),_defineProperty$1(this,"update",(()=>{if(this.enabled){let e;e=this.forceFallback?"Fallback (forced)":Fullscreen.native?"Native":"Fallback",this.player.debug.log(`${e} fullscreen enabled`)}else this.player.debug.log("Fullscreen not supported and fallback disabled");toggleClass(this.player.elements.container,this.player.config.classNames.fullscreen.enabled,this.enabled)})),_defineProperty$1(this,"enter",(()=>{this.enabled&&(browser.isIos&&this.player.config.fullscreen.iosNative?this.player.isVimeo?this.player.embed.requestFullscreen():this.target.webkitEnterFullscreen():!Fullscreen.native||this.forceFallback?this.toggleFallback(!0):this.prefix?is.empty(this.prefix)||this.target[`${this.prefix}Request${this.property}`]():this.target.requestFullscreen({navigationUI:"hide"}))})),_defineProperty$1(this,"exit",(()=>{if(this.enabled)if(browser.isIos&&this.player.config.fullscreen.iosNative)this.target.webkitExitFullscreen(),silencePromise(this.player.play());else if(!Fullscreen.native||this.forceFallback)this.toggleFallback(!1);else if(this.prefix){if(!is.empty(this.prefix)){const e="moz"===this.prefix?"Cancel":"Exit";document[`${this.prefix}${e}${this.property}`]()}}else(document.cancelFullScreen||document.exitFullscreen).call(document)})),_defineProperty$1(this,"toggle",(()=>{this.active?this.exit():this.enter()})),this.player=e,this.prefix=Fullscreen.prefix,this.property=Fullscreen.property,this.scrollPosition={x:0,y:0},this.forceFallback="force"===e.config.fullscreen.fallback,this.player.elements.fullscreen=e.config.fullscreen.container&&closest$1(this.player.elements.container,e.config.fullscreen.container),on.call(this.player,document,"ms"===this.prefix?"MSFullscreenChange":`${this.prefix}fullscreenchange`,(()=>{this.onChange()})),on.call(this.player,this.player.elements.container,"dblclick",(e=>{is.element(this.player.elements.controls)&&this.player.elements.controls.contains(e.target)||this.player.listeners.proxy(e,this.toggle,"fullscreen")})),on.call(this,this.player.elements.container,"keydown",(e=>this.trapFocus(e))),this.update()}static get native(){return!!(document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled)}get usingNative(){return Fullscreen.native&&!this.forceFallback}static get prefix(){if(is.function(document.exitFullscreen))return"";let e="";return["webkit","moz","ms"].some((t=>!(!is.function(document[`${t}ExitFullscreen`])&&!is.function(document[`${t}CancelFullScreen`]))&&(e=t,!0))),e}static get property(){return"moz"===this.prefix?"FullScreen":"Fullscreen"}get enabled(){return(Fullscreen.native||this.player.config.fullscreen.fallback)&&this.player.config.fullscreen.enabled&&this.player.supported.ui&&this.player.isVideo}get active(){if(!this.enabled)return!1;if(!Fullscreen.native||this.forceFallback)return hasClass(this.target,this.player.config.classNames.fullscreen.fallback);const e=this.prefix?this.target.getRootNode()[`${this.prefix}${this.property}Element`]:this.target.getRootNode().fullscreenElement;return e&&e.shadowRoot?e===this.target.getRootNode().host:e===this.target}get target(){return browser.isIos&&this.player.config.fullscreen.iosNative?this.player.media:this.player.elements.fullscreen||this.player.elements.container}}function loadImage(e,t=1){return new Promise(((i,s)=>{const n=new Image,r=()=>{delete n.onload,delete n.onerror,(n.naturalWidth>=t?i:s)(n)};Object.assign(n,{onload:r,onerror:r,src:e})}))}const ui={addStyleHook(){toggleClass(this.elements.container,this.config.selectors.container.replace(".",""),!0),toggleClass(this.elements.container,this.config.classNames.uiSupported,this.supported.ui)},toggleNativeControls(e=!1){e&&this.isHTML5?this.media.setAttribute("controls",""):this.media.removeAttribute("controls")},build(){if(this.listeners.media(),!this.supported.ui)return this.debug.warn(`Basic support only for ${this.provider} ${this.type}`),void ui.toggleNativeControls.call(this,!0);is.element(this.elements.controls)||(controls.inject.call(this),this.listeners.controls()),ui.toggleNativeControls.call(this),this.isHTML5&&captions.setup.call(this),this.volume=null,this.muted=null,this.loop=null,this.quality=null,this.speed=null,controls.updateVolume.call(this),controls.timeUpdate.call(this),controls.durationUpdate.call(this),ui.checkPlaying.call(this),toggleClass(this.elements.container,this.config.classNames.pip.supported,support.pip&&this.isHTML5&&this.isVideo),toggleClass(this.elements.container,this.config.classNames.airplay.supported,support.airplay&&this.isHTML5),toggleClass(this.elements.container,this.config.classNames.isIos,browser.isIos),toggleClass(this.elements.container,this.config.classNames.isTouch,this.touch),this.ready=!0,setTimeout((()=>{triggerEvent.call(this,this.media,"ready")}),0),ui.setTitle.call(this),this.poster&&ui.setPoster.call(this,this.poster,!1).catch((()=>{})),this.config.duration&&controls.durationUpdate.call(this)},setTitle(){let e=i18n.get("play",this.config);if(is.string(this.config.title)&&!is.empty(this.config.title)&&(e+=`, ${this.config.title}`),Array.from(this.elements.buttons.play||[]).forEach((t=>{t.setAttribute("aria-label",e)})),this.isEmbed){const e=getElement.call(this,"iframe");if(!is.element(e))return;const t=is.empty(this.config.title)?"video":this.config.title,i=i18n.get("frameTitle",this.config);e.setAttribute("title",i.replace("{title}",t))}},togglePoster(e){toggleClass(this.elements.container,this.config.classNames.posterEnabled,e)},setPoster(e,t=!0){return t&&this.poster?Promise.reject(new Error("Poster already set")):(this.media.setAttribute("data-poster",e),this.elements.poster.removeAttribute("hidden"),ready.call(this).then((()=>loadImage(e))).catch((t=>{throw e===this.poster&&ui.togglePoster.call(this,!1),t})).then((()=>{if(e!==this.poster)throw new Error("setPoster cancelled by later call to setPoster")})).then((()=>(Object.assign(this.elements.poster.style,{backgroundImage:`url('${e}')`,backgroundSize:""}),ui.togglePoster.call(this,!0),e))))},checkPlaying(e){toggleClass(this.elements.container,this.config.classNames.playing,this.playing),toggleClass(this.elements.container,this.config.classNames.paused,this.paused),toggleClass(this.elements.container,this.config.classNames.stopped,this.stopped),Array.from(this.elements.buttons.play||[]).forEach((e=>{Object.assign(e,{pressed:this.playing}),e.setAttribute("aria-label",i18n.get(this.playing?"pause":"play",this.config))})),is.event(e)&&"timeupdate"===e.type||ui.toggleControls.call(this)},checkLoading(e){this.loading=["stalled","waiting"].includes(e.type),clearTimeout(this.timers.loading),this.timers.loading=setTimeout((()=>{toggleClass(this.elements.container,this.config.classNames.loading,this.loading),ui.toggleControls.call(this)}),this.loading?250:0)},toggleControls(e){const{controls:t}=this.elements;if(t&&this.config.hideControls){const i=this.touch&&this.lastSeekTime+2e3>Date.now();this.toggleControls(Boolean(e||this.loading||this.paused||t.pressed||t.hover||i))}},migrateStyles(){Object.values({...this.media.style}).filter((e=>!is.empty(e)&&is.string(e)&&e.startsWith("--plyr"))).forEach((e=>{this.elements.container.style.setProperty(e,this.media.style.getPropertyValue(e)),this.media.style.removeProperty(e)})),is.empty(this.media.style)&&this.media.removeAttribute("style")}};class Listeners{constructor(e){_defineProperty$1(this,"firstTouch",(()=>{const{player:e}=this,{elements:t}=e;e.touch=!0,toggleClass(t.container,e.config.classNames.isTouch,!0)})),_defineProperty$1(this,"setTabFocus",(e=>{const{player:t}=this,{elements:i}=t;if(clearTimeout(this.focusTimer),"keydown"===e.type&&9!==e.which)return;"keydown"===e.type&&(this.lastKeyDown=e.timeStamp);const s=e.timeStamp-this.lastKeyDown<=20;("focus"!==e.type||s)&&((()=>{const e=t.config.classNames.tabFocus;toggleClass(getElements.call(t,`.${e}`),e,!1)})(),"focusout"!==e.type&&(this.focusTimer=setTimeout((()=>{const e=document.activeElement;i.container.contains(e)&&toggleClass(document.activeElement,t.config.classNames.tabFocus,!0)}),10)))})),_defineProperty$1(this,"global",((e=!0)=>{const{player:t}=this;t.config.keyboard.global&&toggleListener.call(t,window,"keydown keyup",this.handleKey,e,!1),toggleListener.call(t,document.body,"click",this.toggleMenu,e),once.call(t,document.body,"touchstart",this.firstTouch),toggleListener.call(t,document.body,"keydown focus blur focusout",this.setTabFocus,e,!1,!0)})),_defineProperty$1(this,"container",(()=>{const{player:e}=this,{config:t,elements:i,timers:s}=e;!t.keyboard.global&&t.keyboard.focused&&on.call(e,i.container,"keydown keyup",this.handleKey,!1),on.call(e,i.container,"mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen",(t=>{const{controls:n}=i;n&&"enterfullscreen"===t.type&&(n.pressed=!1,n.hover=!1);let r=0;["touchstart","touchmove","mousemove"].includes(t.type)&&(ui.toggleControls.call(e,!0),r=e.touch?3e3:2e3),clearTimeout(s.controls),s.controls=setTimeout((()=>ui.toggleControls.call(e,!1)),r)}));const n=()=>{if(!e.isVimeo||e.config.vimeo.premium)return;const t=i.wrapper,{active:s}=e.fullscreen,[n,r]=getAspectRatio.call(e),o=supportsCSS(`aspect-ratio: ${n} / ${r}`);if(!s)return void(o?(t.style.width=null,t.style.height=null):(t.style.maxWidth=null,t.style.margin=null));const[a,l]=getViewportSize(),c=a/l>n/r;o?(t.style.width=c?"auto":"100%",t.style.height=c?"100%":"auto"):(t.style.maxWidth=c?l/r*n+"px":null,t.style.margin=c?"0 auto":null)},r=()=>{clearTimeout(s.resized),s.resized=setTimeout(n,50)};on.call(e,i.container,"enterfullscreen exitfullscreen",(t=>{const{target:s}=e.fullscreen;if(s!==i.container)return;if(!e.isEmbed&&is.empty(e.config.ratio))return;n();("enterfullscreen"===t.type?on:off).call(e,window,"resize",r)}))})),_defineProperty$1(this,"media",(()=>{const{player:e}=this,{elements:t}=e;if(on.call(e,e.media,"timeupdate seeking seeked",(t=>controls.timeUpdate.call(e,t))),on.call(e,e.media,"durationchange loadeddata loadedmetadata",(t=>controls.durationUpdate.call(e,t))),on.call(e,e.media,"ended",(()=>{e.isHTML5&&e.isVideo&&e.config.resetOnEnd&&(e.restart(),e.pause())})),on.call(e,e.media,"progress playing seeking seeked",(t=>controls.updateProgress.call(e,t))),on.call(e,e.media,"volumechange",(t=>controls.updateVolume.call(e,t))),on.call(e,e.media,"playing play pause ended emptied timeupdate",(t=>ui.checkPlaying.call(e,t))),on.call(e,e.media,"waiting canplay seeked playing",(t=>ui.checkLoading.call(e,t))),e.supported.ui&&e.config.clickToPlay&&!e.isAudio){const i=getElement.call(e,`.${e.config.classNames.video}`);if(!is.element(i))return;on.call(e,t.container,"click",(s=>{([t.container,i].includes(s.target)||i.contains(s.target))&&(e.touch&&e.config.hideControls||(e.ended?(this.proxy(s,e.restart,"restart"),this.proxy(s,(()=>{silencePromise(e.play())}),"play")):this.proxy(s,(()=>{silencePromise(e.togglePlay())}),"play")))}))}e.supported.ui&&e.config.disableContextMenu&&on.call(e,t.wrapper,"contextmenu",(e=>{e.preventDefault()}),!1),on.call(e,e.media,"volumechange",(()=>{e.storage.set({volume:e.volume,muted:e.muted})})),on.call(e,e.media,"ratechange",(()=>{controls.updateSetting.call(e,"speed"),e.storage.set({speed:e.speed})})),on.call(e,e.media,"qualitychange",(t=>{controls.updateSetting.call(e,"quality",null,t.detail.quality)})),on.call(e,e.media,"ready qualitychange",(()=>{controls.setDownloadUrl.call(e)}));const i=e.config.events.concat(["keyup","keydown"]).join(" ");on.call(e,e.media,i,(i=>{let{detail:s={}}=i;"error"===i.type&&(s=e.media.error),triggerEvent.call(e,t.container,i.type,!0,s)}))})),_defineProperty$1(this,"proxy",((e,t,i)=>{const{player:s}=this,n=s.config.listeners[i];let r=!0;is.function(n)&&(r=n.call(s,e)),!1!==r&&is.function(t)&&t.call(s,e)})),_defineProperty$1(this,"bind",((e,t,i,s,n=!0)=>{const{player:r}=this,o=r.config.listeners[s],a=is.function(o);on.call(r,e,t,(e=>this.proxy(e,i,s)),n&&!a)})),_defineProperty$1(this,"controls",(()=>{const{player:e}=this,{elements:t}=e,i=browser.isIE?"change":"input";if(t.buttons.play&&Array.from(t.buttons.play).forEach((t=>{this.bind(t,"click",(()=>{silencePromise(e.togglePlay())}),"play")})),this.bind(t.buttons.restart,"click",e.restart,"restart"),this.bind(t.buttons.rewind,"click",(()=>{e.lastSeekTime=Date.now(),e.rewind()}),"rewind"),this.bind(t.buttons.fastForward,"click",(()=>{e.lastSeekTime=Date.now(),e.forward()}),"fastForward"),this.bind(t.buttons.mute,"click",(()=>{e.muted=!e.muted}),"mute"),this.bind(t.buttons.captions,"click",(()=>e.toggleCaptions())),this.bind(t.buttons.download,"click",(()=>{triggerEvent.call(e,e.media,"download")}),"download"),this.bind(t.buttons.fullscreen,"click",(()=>{e.fullscreen.toggle()}),"fullscreen"),this.bind(t.buttons.pip,"click",(()=>{e.pip="toggle"}),"pip"),this.bind(t.buttons.airplay,"click",e.airplay,"airplay"),this.bind(t.buttons.settings,"click",(t=>{t.stopPropagation(),t.preventDefault(),controls.toggleMenu.call(e,t)}),null,!1),this.bind(t.buttons.settings,"keyup",(t=>{const i=t.which;[13,32].includes(i)&&(13!==i?(t.preventDefault(),t.stopPropagation(),controls.toggleMenu.call(e,t)):controls.focusFirstMenuItem.call(e,null,!0))}),null,!1),this.bind(t.settings.menu,"keydown",(t=>{27===t.which&&controls.toggleMenu.call(e,t)})),this.bind(t.inputs.seek,"mousedown mousemove",(e=>{const i=t.progress.getBoundingClientRect(),s=100/i.width*(e.pageX-i.left);e.currentTarget.setAttribute("seek-value",s)})),this.bind(t.inputs.seek,"mousedown mouseup keydown keyup touchstart touchend",(t=>{const i=t.currentTarget,s=t.keyCode?t.keyCode:t.which,n="play-on-seeked";if(is.keyboardEvent(t)&&39!==s&&37!==s)return;e.lastSeekTime=Date.now();const r=i.hasAttribute(n),o=["mouseup","touchend","keyup"].includes(t.type);r&&o?(i.removeAttribute(n),silencePromise(e.play())):!o&&e.playing&&(i.setAttribute(n,""),e.pause())})),browser.isIos){const t=getElements.call(e,'input[type="range"]');Array.from(t).forEach((e=>this.bind(e,i,(e=>repaint(e.target)))))}this.bind(t.inputs.seek,i,(t=>{const i=t.currentTarget;let s=i.getAttribute("seek-value");is.empty(s)&&(s=i.value),i.removeAttribute("seek-value"),e.currentTime=s/i.max*e.duration}),"seek"),this.bind(t.progress,"mouseenter mouseleave mousemove",(t=>controls.updateSeekTooltip.call(e,t))),this.bind(t.progress,"mousemove touchmove",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.startMove(t)})),this.bind(t.progress,"mouseleave touchend click",(()=>{const{previewThumbnails:t}=e;t&&t.loaded&&t.endMove(!1,!0)})),this.bind(t.progress,"mousedown touchstart",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.startScrubbing(t)})),this.bind(t.progress,"mouseup touchend",(t=>{const{previewThumbnails:i}=e;i&&i.loaded&&i.endScrubbing(t)})),browser.isWebkit&&Array.from(getElements.call(e,'input[type="range"]')).forEach((t=>{this.bind(t,"input",(t=>controls.updateRangeFill.call(e,t.target)))})),e.config.toggleInvert&&!is.element(t.display.duration)&&this.bind(t.display.currentTime,"click",(()=>{0!==e.currentTime&&(e.config.invertTime=!e.config.invertTime,controls.timeUpdate.call(e))})),this.bind(t.inputs.volume,i,(t=>{e.volume=t.target.value}),"volume"),this.bind(t.controls,"mouseenter mouseleave",(i=>{t.controls.hover=!e.touch&&"mouseenter"===i.type})),t.fullscreen&&Array.from(t.fullscreen.children).filter((e=>!e.contains(t.container))).forEach((i=>{this.bind(i,"mouseenter mouseleave",(i=>{t.controls&&(t.controls.hover=!e.touch&&"mouseenter"===i.type)}))})),this.bind(t.controls,"mousedown mouseup touchstart touchend touchcancel",(e=>{t.controls.pressed=["mousedown","touchstart"].includes(e.type)})),this.bind(t.controls,"focusin",(()=>{const{config:i,timers:s}=e;toggleClass(t.controls,i.classNames.noTransition,!0),ui.toggleControls.call(e,!0),setTimeout((()=>{toggleClass(t.controls,i.classNames.noTransition,!1)}),0);const n=this.touch?3e3:4e3;clearTimeout(s.controls),s.controls=setTimeout((()=>ui.toggleControls.call(e,!1)),n)})),this.bind(t.inputs.volume,"wheel",(t=>{const i=t.webkitDirectionInvertedFromDevice,[s,n]=[t.deltaX,-t.deltaY].map((e=>i?-e:e)),r=Math.sign(Math.abs(s)>Math.abs(n)?s:n);e.increaseVolume(r/50);const{volume:o}=e.media;(1===r&&o<1||-1===r&&o>0)&&t.preventDefault()}),"volume",!1)})),this.player=e,this.lastKey=null,this.focusTimer=null,this.lastKeyDown=null,this.handleKey=this.handleKey.bind(this),this.toggleMenu=this.toggleMenu.bind(this),this.setTabFocus=this.setTabFocus.bind(this),this.firstTouch=this.firstTouch.bind(this)}handleKey(e){const{player:t}=this,{elements:i}=t,s=e.keyCode?e.keyCode:e.which,n="keydown"===e.type,r=n&&s===this.lastKey;if(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;if(!is.number(s))return;if(n){const n=document.activeElement;if(is.element(n)){const{editable:s}=t.config.selectors,{seek:r}=i.inputs;if(n!==r&&matches(n,s))return;if(32===e.which&&matches(n,'button, [role^="menuitem"]'))return}switch([32,37,38,39,40,48,49,50,51,52,53,54,56,57,67,70,73,75,76,77,79].includes(s)&&(e.preventDefault(),e.stopPropagation()),s){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:r||(t.currentTime=t.duration/10*(s-48));break;case 32:case 75:r||silencePromise(t.togglePlay());break;case 38:t.increaseVolume(.1);break;case 40:t.decreaseVolume(.1);break;case 77:r||(t.muted=!t.muted);break;case 39:t.forward();break;case 37:t.rewind();break;case 70:t.fullscreen.toggle();break;case 67:r||t.toggleCaptions();break;case 76:t.loop=!t.loop}27===s&&!t.fullscreen.usingNative&&t.fullscreen.active&&t.fullscreen.toggle(),this.lastKey=s}else this.lastKey=null}toggleMenu(e){controls.toggleMenu.call(this.player,e)}}var loadjs_umd=createCommonjsModule((function(e,t){e.exports=function(){var e=function(){},t={},i={},s={};function n(e,t){e=e.push?e:[e];var n,r,o,a=[],l=e.length,c=l;for(n=function(e,i){i.length&&a.push(e),--c||t(a)};l--;)r=e[l],(o=i[r])?n(r,o):(s[r]=s[r]||[]).push(n)}function r(e,t){if(e){var n=s[e];if(i[e]=t,n)for(;n.length;)n[0](e,t),n.splice(0,1)}}function o(t,i){t.call&&(t={success:t}),i.length?(t.error||e)(i):(t.success||e)(t)}function a(t,i,s,n){var r,o,l=document,c=s.async,u=(s.numRetries||0)+1,h=s.before||e,d=t.replace(/[\?|#].*$/,""),m=t.replace(/^(css|img)!/,"");n=n||0,/(^css!|\.css$)/.test(d)?((o=l.createElement("link")).rel="stylesheet",o.href=m,(r="hideFocus"in o)&&o.relList&&(r=0,o.rel="preload",o.as="style")):/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(d)?(o=l.createElement("img")).src=m:((o=l.createElement("script")).src=t,o.async=void 0===c||c),o.onload=o.onerror=o.onbeforeload=function(e){var l=e.type[0];if(r)try{o.sheet.cssText.length||(l="e")}catch(e){18!=e.code&&(l="e")}if("e"==l){if((n+=1)<u)return a(t,i,s,n)}else if("preload"==o.rel&&"style"==o.as)return o.rel="stylesheet";i(t,l,e.defaultPrevented)},!1!==h(t,o)&&l.head.appendChild(o)}function l(e,t,i){var s,n,r=(e=e.push?e:[e]).length,o=r,l=[];for(s=function(e,i,s){if("e"==i&&l.push(e),"b"==i){if(!s)return;l.push(e)}--r||t(l)},n=0;n<o;n++)a(e[n],s,i)}function c(e,i,s){var n,a;if(i&&i.trim&&(n=i),a=(n?s:i)||{},n){if(n in t)throw"LoadJS";t[n]=!0}function c(t,i){l(e,(function(e){o(a,e),t&&o({success:t,error:i},e),r(n,e)}),a)}if(a.returnPromise)return new Promise(c);c()}return c.ready=function(e,t){return n(e,(function(e){o(t,e)})),c},c.done=function(e){r(e,[])},c.reset=function(){t={},i={},s={}},c.isDefined=function(e){return e in t},c}()}));function loadScript(e){return new Promise(((t,i)=>{loadjs_umd(e,{success:t,error:i})}))}function parseId$1(e){if(is.empty(e))return null;if(is.number(Number(e)))return e;return e.match(/^.*(vimeo.com\/|video\/)(\d+).*/)?RegExp.$2:e}function parseHash(e){const t=e.match(/^.*(?:vimeo.com\/|video\/)(?:\d+)(?:\?.*&*h=|\/)+(?<hash>[\d,a-f]+)/);return t?t.groups.hash:null}function assurePlaybackState$1(e){e&&!this.embed.hasPlayed&&(this.embed.hasPlayed=!0),this.media.paused===e&&(this.media.paused=!e,triggerEvent.call(this,this.media,e?"play":"pause"))}const vimeo={setup(){const e=this;toggleClass(e.elements.wrapper,e.config.classNames.embed,!0),e.options.speed=e.config.speed.options,setAspectRatio.call(e),is.object(window.Vimeo)?vimeo.ready.call(e):loadScript(e.config.urls.vimeo.sdk).then((()=>{vimeo.ready.call(e)})).catch((t=>{e.debug.warn("Vimeo SDK (player.js) failed to load",t)}))},ready(){const e=this,t=e.config.vimeo,{premium:i,referrerPolicy:s,...n}=t;let r=e.media.getAttribute("src"),o="";is.empty(r)?(r=e.media.getAttribute(e.config.attributes.embed.id),o=e.media.getAttribute(e.config.attributes.embed.hash)):o=parseHash(r);const a=o?{h:o}:{};i&&Object.assign(n,{controls:!1,sidedock:!1});const l=buildUrlParams({loop:e.config.loop.active,autoplay:e.autoplay,muted:e.muted,gesture:"media",playsinline:!this.config.fullscreen.iosNative,...a,...n}),c=parseId$1(r),u=createElement("iframe"),h=format(e.config.urls.vimeo.iframe,c,l);if(u.setAttribute("src",h),u.setAttribute("allowfullscreen",""),u.setAttribute("allow",["autoplay","fullscreen","picture-in-picture","encrypted-media","accelerometer","gyroscope"].join("; ")),is.empty(s)||u.setAttribute("referrerPolicy",s),i||!t.customControls)u.setAttribute("data-poster",e.poster),e.media=replaceElement(u,e.media);else{const t=createElement("div",{class:e.config.classNames.embedContainer,"data-poster":e.poster});t.appendChild(u),e.media=replaceElement(t,e.media)}t.customControls||fetch(format(e.config.urls.vimeo.api,h)).then((t=>{!is.empty(t)&&t.thumbnail_url&&ui.setPoster.call(e,t.thumbnail_url).catch((()=>{}))})),e.embed=new window.Vimeo.Player(u,{autopause:e.config.autopause,muted:e.muted}),e.media.paused=!0,e.media.currentTime=0,e.supported.ui&&e.embed.disableTextTrack(),e.media.play=()=>(assurePlaybackState$1.call(e,!0),e.embed.play()),e.media.pause=()=>(assurePlaybackState$1.call(e,!1),e.embed.pause()),e.media.stop=()=>{e.pause(),e.currentTime=0};let{currentTime:d}=e.media;Object.defineProperty(e.media,"currentTime",{get:()=>d,set(t){const{embed:i,media:s,paused:n,volume:r}=e,o=n&&!i.hasPlayed;s.seeking=!0,triggerEvent.call(e,s,"seeking"),Promise.resolve(o&&i.setVolume(0)).then((()=>i.setCurrentTime(t))).then((()=>o&&i.pause())).then((()=>o&&i.setVolume(r))).catch((()=>{}))}});let m=e.config.speed.selected;Object.defineProperty(e.media,"playbackRate",{get:()=>m,set(t){e.embed.setPlaybackRate(t).then((()=>{m=t,triggerEvent.call(e,e.media,"ratechange")})).catch((()=>{e.options.speed=[1]}))}});let{volume:p}=e.config;Object.defineProperty(e.media,"volume",{get:()=>p,set(t){e.embed.setVolume(t).then((()=>{p=t,triggerEvent.call(e,e.media,"volumechange")}))}});let{muted:g}=e.config;Object.defineProperty(e.media,"muted",{get:()=>g,set(t){const i=!!is.boolean(t)&&t;e.embed.setVolume(i?0:e.config.volume).then((()=>{g=i,triggerEvent.call(e,e.media,"volumechange")}))}});let f,{loop:y}=e.config;Object.defineProperty(e.media,"loop",{get:()=>y,set(t){const i=is.boolean(t)?t:e.config.loop.active;e.embed.setLoop(i).then((()=>{y=i}))}}),e.embed.getVideoUrl().then((t=>{f=t,controls.setDownloadUrl.call(e)})).catch((e=>{this.debug.warn(e)})),Object.defineProperty(e.media,"currentSrc",{get:()=>f}),Object.defineProperty(e.media,"ended",{get:()=>e.currentTime===e.duration}),Promise.all([e.embed.getVideoWidth(),e.embed.getVideoHeight()]).then((t=>{const[i,s]=t;e.embed.ratio=roundAspectRatio(i,s),setAspectRatio.call(this)})),e.embed.setAutopause(e.config.autopause).then((t=>{e.config.autopause=t})),e.embed.getVideoTitle().then((t=>{e.config.title=t,ui.setTitle.call(this)})),e.embed.getCurrentTime().then((t=>{d=t,triggerEvent.call(e,e.media,"timeupdate")})),e.embed.getDuration().then((t=>{e.media.duration=t,triggerEvent.call(e,e.media,"durationchange")})),e.embed.getTextTracks().then((t=>{e.media.textTracks=t,captions.setup.call(e)})),e.embed.on("cuechange",(({cues:t=[]})=>{const i=t.map((e=>stripHTML(e.text)));captions.updateCues.call(e,i)})),e.embed.on("loaded",(()=>{if(e.embed.getPaused().then((t=>{assurePlaybackState$1.call(e,!t),t||triggerEvent.call(e,e.media,"playing")})),is.element(e.embed.element)&&e.supported.ui){e.embed.element.setAttribute("tabindex",-1)}})),e.embed.on("bufferstart",(()=>{triggerEvent.call(e,e.media,"waiting")})),e.embed.on("bufferend",(()=>{triggerEvent.call(e,e.media,"playing")})),e.embed.on("play",(()=>{assurePlaybackState$1.call(e,!0),triggerEvent.call(e,e.media,"playing")})),e.embed.on("pause",(()=>{assurePlaybackState$1.call(e,!1)})),e.embed.on("timeupdate",(t=>{e.media.seeking=!1,d=t.seconds,triggerEvent.call(e,e.media,"timeupdate")})),e.embed.on("progress",(t=>{e.media.buffered=t.percent,triggerEvent.call(e,e.media,"progress"),1===parseInt(t.percent,10)&&triggerEvent.call(e,e.media,"canplaythrough"),e.embed.getDuration().then((t=>{t!==e.media.duration&&(e.media.duration=t,triggerEvent.call(e,e.media,"durationchange"))}))})),e.embed.on("seeked",(()=>{e.media.seeking=!1,triggerEvent.call(e,e.media,"seeked")})),e.embed.on("ended",(()=>{e.media.paused=!0,triggerEvent.call(e,e.media,"ended")})),e.embed.on("error",(t=>{e.media.error=t,triggerEvent.call(e,e.media,"error")})),t.customControls&&setTimeout((()=>ui.build.call(e)),0)}};function parseId(e){if(is.empty(e))return null;return e.match(/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/)?RegExp.$2:e}function assurePlaybackState(e){e&&!this.embed.hasPlayed&&(this.embed.hasPlayed=!0),this.media.paused===e&&(this.media.paused=!e,triggerEvent.call(this,this.media,e?"play":"pause"))}function getHost(e){return e.noCookie?"https://www.youtube-nocookie.com":"http:"===window.location.protocol?"http://www.youtube.com":void 0}const youtube={setup(){if(toggleClass(this.elements.wrapper,this.config.classNames.embed,!0),is.object(window.YT)&&is.function(window.YT.Player))youtube.ready.call(this);else{const e=window.onYouTubeIframeAPIReady;window.onYouTubeIframeAPIReady=()=>{is.function(e)&&e(),youtube.ready.call(this)},loadScript(this.config.urls.youtube.sdk).catch((e=>{this.debug.warn("YouTube API failed to load",e)}))}},getTitle(e){fetch(format(this.config.urls.youtube.api,e)).then((e=>{if(is.object(e)){const{title:t,height:i,width:s}=e;this.config.title=t,ui.setTitle.call(this),this.embed.ratio=roundAspectRatio(s,i)}setAspectRatio.call(this)})).catch((()=>{setAspectRatio.call(this)}))},ready(){const e=this,t=e.config.youtube,i=e.media&&e.media.getAttribute("id");if(!is.empty(i)&&i.startsWith("youtube-"))return;let s=e.media.getAttribute("src");is.empty(s)&&(s=e.media.getAttribute(this.config.attributes.embed.id));const n=parseId(s),r=createElement("div",{id:generateId(e.provider),"data-poster":t.customControls?e.poster:void 0});if(e.media=replaceElement(r,e.media),t.customControls){const t=e=>`https://i.ytimg.com/vi/${n}/${e}default.jpg`;loadImage(t("maxres"),121).catch((()=>loadImage(t("sd"),121))).catch((()=>loadImage(t("hq")))).then((t=>ui.setPoster.call(e,t.src))).then((t=>{t.includes("maxres")||(e.elements.poster.style.backgroundSize="cover")})).catch((()=>{}))}e.embed=new window.YT.Player(e.media,{videoId:n,host:getHost(t),playerVars:extend({},{autoplay:e.config.autoplay?1:0,hl:e.config.hl,controls:e.supported.ui&&t.customControls?0:1,disablekb:1,playsinline:e.config.fullscreen.iosNative?0:1,cc_load_policy:e.captions.active?1:0,cc_lang_pref:e.config.captions.language,widget_referrer:window?window.location.href:null},t),events:{onError(t){if(!e.media.error){const i=t.data,s={2:"The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.",5:"The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.",100:"The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.",101:"The owner of the requested video does not allow it to be played in embedded players.",150:"The owner of the requested video does not allow it to be played in embedded players."}[i]||"An unknown error occured";e.media.error={code:i,message:s},triggerEvent.call(e,e.media,"error")}},onPlaybackRateChange(t){const i=t.target;e.media.playbackRate=i.getPlaybackRate(),triggerEvent.call(e,e.media,"ratechange")},onReady(i){if(is.function(e.media.play))return;const s=i.target;youtube.getTitle.call(e,n),e.media.play=()=>{assurePlaybackState.call(e,!0),s.playVideo()},e.media.pause=()=>{assurePlaybackState.call(e,!1),s.pauseVideo()},e.media.stop=()=>{s.stopVideo()},e.media.duration=s.getDuration(),e.media.paused=!0,e.media.currentTime=0,Object.defineProperty(e.media,"currentTime",{get:()=>Number(s.getCurrentTime()),set(t){e.paused&&!e.embed.hasPlayed&&e.embed.mute(),e.media.seeking=!0,triggerEvent.call(e,e.media,"seeking"),s.seekTo(t)}}),Object.defineProperty(e.media,"playbackRate",{get:()=>s.getPlaybackRate(),set(e){s.setPlaybackRate(e)}});let{volume:r}=e.config;Object.defineProperty(e.media,"volume",{get:()=>r,set(t){r=t,s.setVolume(100*r),triggerEvent.call(e,e.media,"volumechange")}});let{muted:o}=e.config;Object.defineProperty(e.media,"muted",{get:()=>o,set(t){const i=is.boolean(t)?t:o;o=i,s[i?"mute":"unMute"](),s.setVolume(100*r),triggerEvent.call(e,e.media,"volumechange")}}),Object.defineProperty(e.media,"currentSrc",{get:()=>s.getVideoUrl()}),Object.defineProperty(e.media,"ended",{get:()=>e.currentTime===e.duration});const a=s.getAvailablePlaybackRates();e.options.speed=a.filter((t=>e.config.speed.options.includes(t))),e.supported.ui&&t.customControls&&e.media.setAttribute("tabindex",-1),triggerEvent.call(e,e.media,"timeupdate"),triggerEvent.call(e,e.media,"durationchange"),clearInterval(e.timers.buffering),e.timers.buffering=setInterval((()=>{e.media.buffered=s.getVideoLoadedFraction(),(null===e.media.lastBuffered||e.media.lastBuffered<e.media.buffered)&&triggerEvent.call(e,e.media,"progress"),e.media.lastBuffered=e.media.buffered,1===e.media.buffered&&(clearInterval(e.timers.buffering),triggerEvent.call(e,e.media,"canplaythrough"))}),200),t.customControls&&setTimeout((()=>ui.build.call(e)),50)},onStateChange(i){const s=i.target;clearInterval(e.timers.playing);switch(e.media.seeking&&[1,2].includes(i.data)&&(e.media.seeking=!1,triggerEvent.call(e,e.media,"seeked")),i.data){case-1:triggerEvent.call(e,e.media,"timeupdate"),e.media.buffered=s.getVideoLoadedFraction(),triggerEvent.call(e,e.media,"progress");break;case 0:assurePlaybackState.call(e,!1),e.media.loop?(s.stopVideo(),s.playVideo()):triggerEvent.call(e,e.media,"ended");break;case 1:t.customControls&&!e.config.autoplay&&e.media.paused&&!e.embed.hasPlayed?e.media.pause():(assurePlaybackState.call(e,!0),triggerEvent.call(e,e.media,"playing"),e.timers.playing=setInterval((()=>{triggerEvent.call(e,e.media,"timeupdate")}),50),e.media.duration!==s.getDuration()&&(e.media.duration=s.getDuration(),triggerEvent.call(e,e.media,"durationchange")));break;case 2:e.muted||e.embed.unMute(),assurePlaybackState.call(e,!1);break;case 3:triggerEvent.call(e,e.media,"waiting")}triggerEvent.call(e,e.elements.container,"statechange",!1,{code:i.data})}}})}},media={setup(){this.media?(toggleClass(this.elements.container,this.config.classNames.type.replace("{0}",this.type),!0),toggleClass(this.elements.container,this.config.classNames.provider.replace("{0}",this.provider),!0),this.isEmbed&&toggleClass(this.elements.container,this.config.classNames.type.replace("{0}","video"),!0),this.isVideo&&(this.elements.wrapper=createElement("div",{class:this.config.classNames.video}),wrap(this.media,this.elements.wrapper),this.elements.poster=createElement("div",{class:this.config.classNames.poster}),this.elements.wrapper.appendChild(this.elements.poster)),this.isHTML5?html5.setup.call(this):this.isYouTube?youtube.setup.call(this):this.isVimeo&&vimeo.setup.call(this)):this.debug.warn("No media element found!")}},destroy=e=>{e.manager&&e.manager.destroy(),e.elements.displayContainer&&e.elements.displayContainer.destroy(),e.elements.container.remove()};class Ads{constructor(e){_defineProperty$1(this,"load",(()=>{this.enabled&&(is.object(window.google)&&is.object(window.google.ima)?this.ready():loadScript(this.player.config.urls.googleIMA.sdk).then((()=>{this.ready()})).catch((()=>{this.trigger("error",new Error("Google IMA SDK failed to load"))})))})),_defineProperty$1(this,"ready",(()=>{var e;this.enabled||((e=this).manager&&e.manager.destroy(),e.elements.displayContainer&&e.elements.displayContainer.destroy(),e.elements.container.remove()),this.startSafetyTimer(12e3,"ready()"),this.managerPromise.then((()=>{this.clearSafetyTimer("onAdsManagerLoaded()")})),this.listeners(),this.setupIMA()})),_defineProperty$1(this,"setupIMA",(()=>{this.elements.container=createElement("div",{class:this.player.config.classNames.ads}),this.player.elements.container.appendChild(this.elements.container),google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED),google.ima.settings.setLocale(this.player.config.ads.language),google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline),this.elements.displayContainer=new google.ima.AdDisplayContainer(this.elements.container,this.player.media),this.loader=new google.ima.AdsLoader(this.elements.displayContainer),this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,(e=>this.onAdsManagerLoaded(e)),!1),this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,(e=>this.onAdError(e)),!1),this.requestAds()})),_defineProperty$1(this,"requestAds",(()=>{const{container:e}=this.player.elements;try{const t=new google.ima.AdsRequest;t.adTagUrl=this.tagUrl,t.linearAdSlotWidth=e.offsetWidth,t.linearAdSlotHeight=e.offsetHeight,t.nonLinearAdSlotWidth=e.offsetWidth,t.nonLinearAdSlotHeight=e.offsetHeight,t.forceNonLinearFullSlot=!1,t.setAdWillPlayMuted(!this.player.muted),this.loader.requestAds(t)}catch(e){this.onAdError(e)}})),_defineProperty$1(this,"pollCountdown",((e=!1)=>{if(!e)return clearInterval(this.countdownTimer),void this.elements.container.removeAttribute("data-badge-text");this.countdownTimer=setInterval((()=>{const e=formatTime(Math.max(this.manager.getRemainingTime(),0)),t=`${i18n.get("advertisement",this.player.config)} - ${e}`;this.elements.container.setAttribute("data-badge-text",t)}),100)})),_defineProperty$1(this,"onAdsManagerLoaded",(e=>{if(!this.enabled)return;const t=new google.ima.AdsRenderingSettings;t.restoreCustomPlaybackStateOnAdBreakComplete=!0,t.enablePreloading=!0,this.manager=e.getAdsManager(this.player,t),this.cuePoints=this.manager.getCuePoints(),this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR,(e=>this.onAdError(e))),Object.keys(google.ima.AdEvent.Type).forEach((e=>{this.manager.addEventListener(google.ima.AdEvent.Type[e],(e=>this.onAdEvent(e)))})),this.trigger("loaded")})),_defineProperty$1(this,"addCuePoints",(()=>{is.empty(this.cuePoints)||this.cuePoints.forEach((e=>{if(0!==e&&-1!==e&&e<this.player.duration){const t=this.player.elements.progress;if(is.element(t)){const i=100/this.player.duration*e,s=createElement("span",{class:this.player.config.classNames.cues});s.style.left=`${i.toString()}%`,t.appendChild(s)}}}))})),_defineProperty$1(this,"onAdEvent",(e=>{const{container:t}=this.player.elements,i=e.getAd(),s=e.getAdData();switch((e=>{triggerEvent.call(this.player,this.player.media,`ads${e.replace(/_/g,"").toLowerCase()}`)})(e.type),e.type){case google.ima.AdEvent.Type.LOADED:this.trigger("loaded"),this.pollCountdown(!0),i.isLinear()||(i.width=t.offsetWidth,i.height=t.offsetHeight);break;case google.ima.AdEvent.Type.STARTED:this.manager.setVolume(this.player.volume);break;case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:this.player.ended?this.loadAds():this.loader.contentComplete();break;case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:this.pauseContent();break;case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:this.pollCountdown(),this.resumeContent();break;case google.ima.AdEvent.Type.LOG:s.adError&&this.player.debug.warn(`Non-fatal ad error: ${s.adError.getMessage()}`)}})),_defineProperty$1(this,"onAdError",(e=>{this.cancel(),this.player.debug.warn("Ads error",e)})),_defineProperty$1(this,"listeners",(()=>{const{container:e}=this.player.elements;let t;this.player.on("canplay",(()=>{this.addCuePoints()})),this.player.on("ended",(()=>{this.loader.contentComplete()})),this.player.on("timeupdate",(()=>{t=this.player.currentTime})),this.player.on("seeked",(()=>{const e=this.player.currentTime;is.empty(this.cuePoints)||this.cuePoints.forEach(((i,s)=>{t<i&&i<e&&(this.manager.discardAdBreak(),this.cuePoints.splice(s,1))}))})),window.addEventListener("resize",(()=>{this.manager&&this.manager.resize(e.offsetWidth,e.offsetHeight,google.ima.ViewMode.NORMAL)}))})),_defineProperty$1(this,"play",(()=>{const{container:e}=this.player.elements;this.managerPromise||this.resumeContent(),this.managerPromise.then((()=>{this.manager.setVolume(this.player.volume),this.elements.displayContainer.initialize();try{this.initialized||(this.manager.init(e.offsetWidth,e.offsetHeight,google.ima.ViewMode.NORMAL),this.manager.start()),this.initialized=!0}catch(e){this.onAdError(e)}})).catch((()=>{}))})),_defineProperty$1(this,"resumeContent",(()=>{this.elements.container.style.zIndex="",this.playing=!1,silencePromise(this.player.media.play())})),_defineProperty$1(this,"pauseContent",(()=>{this.elements.container.style.zIndex=3,this.playing=!0,this.player.media.pause()})),_defineProperty$1(this,"cancel",(()=>{this.initialized&&this.resumeContent(),this.trigger("error"),this.loadAds()})),_defineProperty$1(this,"loadAds",(()=>{this.managerPromise.then((()=>{this.manager&&this.manager.destroy(),this.managerPromise=new Promise((e=>{this.on("loaded",e),this.player.debug.log(this.manager)})),this.initialized=!1,this.requestAds()})).catch((()=>{}))})),_defineProperty$1(this,"trigger",((e,...t)=>{const i=this.events[e];is.array(i)&&i.forEach((e=>{is.function(e)&&e.apply(this,t)}))})),_defineProperty$1(this,"on",((e,t)=>(is.array(this.events[e])||(this.events[e]=[]),this.events[e].push(t),this))),_defineProperty$1(this,"startSafetyTimer",((e,t)=>{this.player.debug.log(`Safety timer invoked from: ${t}`),this.safetyTimer=setTimeout((()=>{this.cancel(),this.clearSafetyTimer("startSafetyTimer()")}),e)})),_defineProperty$1(this,"clearSafetyTimer",(e=>{is.nullOrUndefined(this.safetyTimer)||(this.player.debug.log(`Safety timer cleared from: ${e}`),clearTimeout(this.safetyTimer),this.safetyTimer=null)})),this.player=e,this.config=e.config.ads,this.playing=!1,this.initialized=!1,this.elements={container:null,displayContainer:null},this.manager=null,this.loader=null,this.cuePoints=null,this.events={},this.safetyTimer=null,this.countdownTimer=null,this.managerPromise=new Promise(((e,t)=>{this.on("loaded",e),this.on("error",t)})),this.load()}get enabled(){const{config:e}=this;return this.player.isHTML5&&this.player.isVideo&&e.enabled&&(!is.empty(e.publisherId)||is.url(e.tagUrl))}get tagUrl(){const{config:e}=this;if(is.url(e.tagUrl))return e.tagUrl;return`https://go.aniview.com/api/adserver6/vast/?${buildUrlParams({AV_PUBLISHERID:"58c25bb0073ef448b1087ad6",AV_CHANNELID:"5a0458dc28a06145e4519d21",AV_URL:window.location.hostname,cb:Date.now(),AV_WIDTH:640,AV_HEIGHT:480,AV_CDIM2:e.publisherId})}`}}const parseVtt=e=>{const t=[];return e.split(/\r\n\r\n|\n\n|\r\r/).forEach((e=>{const i={};e.split(/\r\n|\n|\r/).forEach((e=>{if(is.number(i.startTime)){if(!is.empty(e.trim())&&is.empty(i.text)){const t=e.trim().split("#xywh=");[i.text]=t,t[1]&&([i.x,i.y,i.w,i.h]=t[1].split(","))}}else{const t=e.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})/);t&&(i.startTime=60*Number(t[1]||0)*60+60*Number(t[2])+Number(t[3])+Number(`0.${t[4]}`),i.endTime=60*Number(t[6]||0)*60+60*Number(t[7])+Number(t[8])+Number(`0.${t[9]}`))}})),i.text&&t.push(i)})),t},fitRatio=(e,t)=>{const i={};return e>t.width/t.height?(i.width=t.width,i.height=1/e*t.width):(i.height=t.height,i.width=e*t.height),i};class PreviewThumbnails{constructor(e){_defineProperty$1(this,"load",(()=>{this.player.elements.display.seekTooltip&&(this.player.elements.display.seekTooltip.hidden=this.enabled),this.enabled&&this.getThumbnails().then((()=>{this.enabled&&(this.render(),this.determineContainerAutoSizing(),this.loaded=!0)}))})),_defineProperty$1(this,"getThumbnails",(()=>new Promise((e=>{const{src:t}=this.player.config.previewThumbnails;if(is.empty(t))throw new Error("Missing previewThumbnails.src config attribute");const i=()=>{this.thumbnails.sort(((e,t)=>e.height-t.height)),this.player.debug.log("Preview thumbnails",this.thumbnails),e()};if(is.function(t))t((e=>{this.thumbnails=e,i()}));else{const e=(is.string(t)?[t]:t).map((e=>this.getThumbnail(e)));Promise.all(e).then(i)}})))),_defineProperty$1(this,"getThumbnail",(e=>new Promise((t=>{fetch(e).then((i=>{const s={frames:parseVtt(i),height:null,urlPrefix:""};s.frames[0].text.startsWith("/")||s.frames[0].text.startsWith("http://")||s.frames[0].text.startsWith("https://")||(s.urlPrefix=e.substring(0,e.lastIndexOf("/")+1));const n=new Image;n.onload=()=>{s.height=n.naturalHeight,s.width=n.naturalWidth,this.thumbnails.push(s),t()},n.src=s.urlPrefix+s.frames[0].text}))})))),_defineProperty$1(this,"startMove",(e=>{if(this.loaded&&is.event(e)&&["touchmove","mousemove"].includes(e.type)&&this.player.media.duration){if("touchmove"===e.type)this.seekTime=this.player.media.duration*(this.player.elements.inputs.seek.value/100);else{const t=this.player.elements.progress.getBoundingClientRect(),i=100/t.width*(e.pageX-t.left);this.seekTime=this.player.media.duration*(i/100),this.seekTime<0&&(this.seekTime=0),this.seekTime>this.player.media.duration-1&&(this.seekTime=this.player.media.duration-1),this.mousePosX=e.pageX,this.elements.thumb.time.innerText=formatTime(this.seekTime)}this.showImageAtCurrentTime()}})),_defineProperty$1(this,"endMove",(()=>{this.toggleThumbContainer(!1,!0)})),_defineProperty$1(this,"startScrubbing",(e=>{(is.nullOrUndefined(e.button)||!1===e.button||0===e.button)&&(this.mouseDown=!0,this.player.media.duration&&(this.toggleScrubbingContainer(!0),this.toggleThumbContainer(!1,!0),this.showImageAtCurrentTime()))})),_defineProperty$1(this,"endScrubbing",(()=>{this.mouseDown=!1,Math.ceil(this.lastTime)===Math.ceil(this.player.media.currentTime)?this.toggleScrubbingContainer(!1):once.call(this.player,this.player.media,"timeupdate",(()=>{this.mouseDown||this.toggleScrubbingContainer(!1)}))})),_defineProperty$1(this,"listeners",(()=>{this.player.on("play",(()=>{this.toggleThumbContainer(!1,!0)})),this.player.on("seeked",(()=>{this.toggleThumbContainer(!1)})),this.player.on("timeupdate",(()=>{this.lastTime=this.player.media.currentTime}))})),_defineProperty$1(this,"render",(()=>{this.elements.thumb.container=createElement("div",{class:this.player.config.classNames.previewThumbnails.thumbContainer}),this.elements.thumb.imageContainer=createElement("div",{class:this.player.config.classNames.previewThumbnails.imageContainer}),this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer);const e=createElement("div",{class:this.player.config.classNames.previewThumbnails.timeContainer});this.elements.thumb.time=createElement("span",{},"00:00"),e.appendChild(this.elements.thumb.time),this.elements.thumb.container.appendChild(e),is.element(this.player.elements.progress)&&this.player.elements.progress.appendChild(this.elements.thumb.container),this.elements.scrubbing.container=createElement("div",{class:this.player.config.classNames.previewThumbnails.scrubbingContainer}),this.player.elements.wrapper.appendChild(this.elements.scrubbing.container)})),_defineProperty$1(this,"destroy",(()=>{this.elements.thumb.container&&this.elements.thumb.container.remove(),this.elements.scrubbing.container&&this.elements.scrubbing.container.remove()})),_defineProperty$1(this,"showImageAtCurrentTime",(()=>{this.mouseDown?this.setScrubbingContainerSize():this.setThumbContainerSizeAndPos();const e=this.thumbnails[0].frames.findIndex((e=>this.seekTime>=e.startTime&&this.seekTime<=e.endTime)),t=e>=0;let i=0;this.mouseDown||this.toggleThumbContainer(t),t&&(this.thumbnails.forEach(((t,s)=>{this.loadedImages.includes(t.frames[e].text)&&(i=s)})),e!==this.showingThumb&&(this.showingThumb=e,this.loadImage(i)))})),_defineProperty$1(this,"loadImage",((e=0)=>{const t=this.showingThumb,i=this.thumbnails[e],{urlPrefix:s}=i,n=i.frames[t],r=i.frames[t].text,o=s+r;if(this.currentImageElement&&this.currentImageElement.dataset.filename===r)this.showImage(this.currentImageElement,n,e,t,r,!1),this.currentImageElement.dataset.index=t,this.removeOldImages(this.currentImageElement);else{this.loadingImage&&this.usingSprites&&(this.loadingImage.onload=null);const i=new Image;i.src=o,i.dataset.index=t,i.dataset.filename=r,this.showingThumbFilename=r,this.player.debug.log(`Loading image: ${o}`),i.onload=()=>this.showImage(i,n,e,t,r,!0),this.loadingImage=i,this.removeOldImages(i)}})),_defineProperty$1(this,"showImage",((e,t,i,s,n,r=!0)=>{this.player.debug.log(`Showing thumb: ${n}. num: ${s}. qual: ${i}. newimg: ${r}`),this.setImageSizeAndOffset(e,t),r&&(this.currentImageContainer.appendChild(e),this.currentImageElement=e,this.loadedImages.includes(n)||this.loadedImages.push(n)),this.preloadNearby(s,!0).then(this.preloadNearby(s,!1)).then(this.getHigherQuality(i,e,t,n))})),_defineProperty$1(this,"removeOldImages",(e=>{Array.from(this.currentImageContainer.children).forEach((t=>{if("img"!==t.tagName.toLowerCase())return;const i=this.usingSprites?500:1e3;if(t.dataset.index!==e.dataset.index&&!t.dataset.deleting){t.dataset.deleting=!0;const{currentImageContainer:e}=this;setTimeout((()=>{e.removeChild(t),this.player.debug.log(`Removing thumb: ${t.dataset.filename}`)}),i)}}))})),_defineProperty$1(this,"preloadNearby",((e,t=!0)=>new Promise((i=>{setTimeout((()=>{const s=this.thumbnails[0].frames[e].text;if(this.showingThumbFilename===s){let n;n=t?this.thumbnails[0].frames.slice(e):this.thumbnails[0].frames.slice(0,e).reverse();let r=!1;n.forEach((e=>{const t=e.text;if(t!==s&&!this.loadedImages.includes(t)){r=!0,this.player.debug.log(`Preloading thumb filename: ${t}`);const{urlPrefix:e}=this.thumbnails[0],s=e+t,n=new Image;n.src=s,n.onload=()=>{this.player.debug.log(`Preloaded thumb filename: ${t}`),this.loadedImages.includes(t)||this.loadedImages.push(t),i()}}})),r||i()}}),300)})))),_defineProperty$1(this,"getHigherQuality",((e,t,i,s)=>{if(e<this.thumbnails.length-1){let n=t.naturalHeight;this.usingSprites&&(n=i.h),n<this.thumbContainerHeight&&setTimeout((()=>{this.showingThumbFilename===s&&(this.player.debug.log(`Showing higher quality thumb for: ${s}`),this.loadImage(e+1))}),300)}})),_defineProperty$1(this,"toggleThumbContainer",((e=!1,t=!1)=>{const i=this.player.config.classNames.previewThumbnails.thumbContainerShown;this.elements.thumb.container.classList.toggle(i,e),!e&&t&&(this.showingThumb=null,this.showingThumbFilename=null)})),_defineProperty$1(this,"toggleScrubbingContainer",((e=!1)=>{const t=this.player.config.classNames.previewThumbnails.scrubbingContainerShown;this.elements.scrubbing.container.classList.toggle(t,e),e||(this.showingThumb=null,this.showingThumbFilename=null)})),_defineProperty$1(this,"determineContainerAutoSizing",(()=>{(this.elements.thumb.imageContainer.clientHeight>20||this.elements.thumb.imageContainer.clientWidth>20)&&(this.sizeSpecifiedInCSS=!0)})),_defineProperty$1(this,"setThumbContainerSizeAndPos",(()=>{if(this.sizeSpecifiedInCSS){if(this.elements.thumb.imageContainer.clientHeight>20&&this.elements.thumb.imageContainer.clientWidth<20){const e=Math.floor(this.elements.thumb.imageContainer.clientHeight*this.thumbAspectRatio);this.elements.thumb.imageContainer.style.width=`${e}px`}else if(this.elements.thumb.imageContainer.clientHeight<20&&this.elements.thumb.imageContainer.clientWidth>20){const e=Math.floor(this.elements.thumb.imageContainer.clientWidth/this.thumbAspectRatio);this.elements.thumb.imageContainer.style.height=`${e}px`}}else{const e=Math.floor(this.thumbContainerHeight*this.thumbAspectRatio);this.elements.thumb.imageContainer.style.height=`${this.thumbContainerHeight}px`,this.elements.thumb.imageContainer.style.width=`${e}px`}this.setThumbContainerPos()})),_defineProperty$1(this,"setThumbContainerPos",(()=>{const e=this.player.elements.progress.getBoundingClientRect(),t=this.player.elements.container.getBoundingClientRect(),{container:i}=this.elements.thumb,s=t.left-e.left+10,n=t.right-e.left-i.clientWidth-10;let r=this.mousePosX-e.left-i.clientWidth/2;r<s&&(r=s),r>n&&(r=n),i.style.left=`${r}px`})),_defineProperty$1(this,"setScrubbingContainerSize",(()=>{const{width:e,height:t}=fitRatio(this.thumbAspectRatio,{width:this.player.media.clientWidth,height:this.player.media.clientHeight});this.elements.scrubbing.container.style.width=`${e}px`,this.elements.scrubbing.container.style.height=`${t}px`})),_defineProperty$1(this,"setImageSizeAndOffset",((e,t)=>{if(!this.usingSprites)return;const i=this.thumbContainerHeight/t.h;e.style.height=e.naturalHeight*i+"px",e.style.width=e.naturalWidth*i+"px",e.style.left=`-${t.x*i}px`,e.style.top=`-${t.y*i}px`})),this.player=e,this.thumbnails=[],this.loaded=!1,this.lastMouseMoveTime=Date.now(),this.mouseDown=!1,this.loadedImages=[],this.elements={thumb:{},scrubbing:{}},this.load()}get enabled(){return this.player.isHTML5&&this.player.isVideo&&this.player.config.previewThumbnails.enabled}get currentImageContainer(){return this.mouseDown?this.elements.scrubbing.container:this.elements.thumb.imageContainer}get usingSprites(){return Object.keys(this.thumbnails[0].frames[0]).includes("w")}get thumbAspectRatio(){return this.usingSprites?this.thumbnails[0].frames[0].w/this.thumbnails[0].frames[0].h:this.thumbnails[0].width/this.thumbnails[0].height}get thumbContainerHeight(){if(this.mouseDown){const{height:e}=fitRatio(this.thumbAspectRatio,{width:this.player.media.clientWidth,height:this.player.media.clientHeight});return e}return this.sizeSpecifiedInCSS?this.elements.thumb.imageContainer.clientHeight:Math.floor(this.player.media.clientWidth/this.thumbAspectRatio/4)}get currentImageElement(){return this.mouseDown?this.currentScrubbingImageElement:this.currentThumbnailImageElement}set currentImageElement(e){this.mouseDown?this.currentScrubbingImageElement=e:this.currentThumbnailImageElement=e}}const source={insertElements(e,t){is.string(t)?insertElement(e,this.media,{src:t}):is.array(t)&&t.forEach((t=>{insertElement(e,this.media,t)}))},change(e){getDeep(e,"sources.length")?(html5.cancelRequests.call(this),this.destroy.call(this,(()=>{this.options.quality=[],removeElement(this.media),this.media=null,is.element(this.elements.container)&&this.elements.container.removeAttribute("class");const{sources:t,type:i}=e,[{provider:s=providers.html5,src:n}]=t,r="html5"===s?i:"div",o="html5"===s?{}:{src:n};Object.assign(this,{provider:s,type:i,supported:support.check(i,s,this.config.playsinline),media:createElement(r,o)}),this.elements.container.appendChild(this.media),is.boolean(e.autoplay)&&(this.config.autoplay=e.autoplay),this.isHTML5&&(this.config.crossorigin&&this.media.setAttribute("crossorigin",""),this.config.autoplay&&this.media.setAttribute("autoplay",""),is.empty(e.poster)||(this.poster=e.poster),this.config.loop.active&&this.media.setAttribute("loop",""),this.config.muted&&this.media.setAttribute("muted",""),this.config.playsinline&&this.media.setAttribute("playsinline","")),ui.addStyleHook.call(this),this.isHTML5&&source.insertElements.call(this,"source",t),this.config.title=e.title,media.setup.call(this),this.isHTML5&&Object.keys(e).includes("tracks")&&source.insertElements.call(this,"track",e.tracks),(this.isHTML5||this.isEmbed&&!this.supported.ui)&&ui.build.call(this),this.isHTML5&&this.media.load(),is.empty(e.previewThumbnails)||(Object.assign(this.config.previewThumbnails,e.previewThumbnails),this.previewThumbnails&&this.previewThumbnails.loaded&&(this.previewThumbnails.destroy(),this.previewThumbnails=null),this.config.previewThumbnails.enabled&&(this.previewThumbnails=new PreviewThumbnails(this))),this.fullscreen.update()}),!0)):this.debug.warn("Invalid source format")}};function clamp(e=0,t=0,i=255){return Math.min(Math.max(e,t),i)}class Plyr{constructor(e,t){if(_defineProperty$1(this,"play",(()=>is.function(this.media.play)?(this.ads&&this.ads.enabled&&this.ads.managerPromise.then((()=>this.ads.play())).catch((()=>silencePromise(this.media.play()))),this.media.play()):null)),_defineProperty$1(this,"pause",(()=>this.playing&&is.function(this.media.pause)?this.media.pause():null)),_defineProperty$1(this,"togglePlay",(e=>(is.boolean(e)?e:!this.playing)?this.play():this.pause())),_defineProperty$1(this,"stop",(()=>{this.isHTML5?(this.pause(),this.restart()):is.function(this.media.stop)&&this.media.stop()})),_defineProperty$1(this,"restart",(()=>{this.currentTime=0})),_defineProperty$1(this,"rewind",(e=>{this.currentTime-=is.number(e)?e:this.config.seekTime})),_defineProperty$1(this,"forward",(e=>{this.currentTime+=is.number(e)?e:this.config.seekTime})),_defineProperty$1(this,"increaseVolume",(e=>{const t=this.media.muted?0:this.volume;this.volume=t+(is.number(e)?e:0)})),_defineProperty$1(this,"decreaseVolume",(e=>{this.increaseVolume(-e)})),_defineProperty$1(this,"airplay",(()=>{support.airplay&&this.media.webkitShowPlaybackTargetPicker()})),_defineProperty$1(this,"toggleControls",(e=>{if(this.supported.ui&&!this.isAudio){const t=hasClass(this.elements.container,this.config.classNames.hideControls),i=void 0===e?void 0:!e,s=toggleClass(this.elements.container,this.config.classNames.hideControls,i);if(s&&is.array(this.config.controls)&&this.config.controls.includes("settings")&&!is.empty(this.config.settings)&&controls.toggleMenu.call(this,!1),s!==t){const e=s?"controlshidden":"controlsshown";triggerEvent.call(this,this.media,e)}return!s}return!1})),_defineProperty$1(this,"on",((e,t)=>{on.call(this,this.elements.container,e,t)})),_defineProperty$1(this,"once",((e,t)=>{once.call(this,this.elements.container,e,t)})),_defineProperty$1(this,"off",((e,t)=>{off(this.elements.container,e,t)})),_defineProperty$1(this,"destroy",((e,t=!1)=>{if(!this.ready)return;const i=()=>{document.body.style.overflow="",this.embed=null,t?(Object.keys(this.elements).length&&(removeElement(this.elements.buttons.play),removeElement(this.elements.captions),removeElement(this.elements.controls),removeElement(this.elements.wrapper),this.elements.buttons.play=null,this.elements.captions=null,this.elements.controls=null,this.elements.wrapper=null),is.function(e)&&e()):(unbindListeners.call(this),html5.cancelRequests.call(this),replaceElement(this.elements.original,this.elements.container),triggerEvent.call(this,this.elements.original,"destroyed",!0),is.function(e)&&e.call(this.elements.original),this.ready=!1,setTimeout((()=>{this.elements=null,this.media=null}),200))};this.stop(),clearTimeout(this.timers.loading),clearTimeout(this.timers.controls),clearTimeout(this.timers.resized),this.isHTML5?(ui.toggleNativeControls.call(this,!0),i()):this.isYouTube?(clearInterval(this.timers.buffering),clearInterval(this.timers.playing),null!==this.embed&&is.function(this.embed.destroy)&&this.embed.destroy(),i()):this.isVimeo&&(null!==this.embed&&this.embed.unload().then(i),setTimeout(i,200))})),_defineProperty$1(this,"supports",(e=>support.mime.call(this,e))),this.timers={},this.ready=!1,this.loading=!1,this.failed=!1,this.touch=support.touch,this.media=e,is.string(this.media)&&(this.media=document.querySelectorAll(this.media)),(window.jQuery&&this.media instanceof jQuery||is.nodeList(this.media)||is.array(this.media))&&(this.media=this.media[0]),this.config=extend({},defaults,Plyr.defaults,t||{},(()=>{try{return JSON.parse(this.media.getAttribute("data-plyr-config"))}catch(e){return{}}})()),this.elements={container:null,fullscreen:null,captions:null,buttons:{},display:{},progress:{},inputs:{},settings:{popup:null,menu:null,panels:{},buttons:{}}},this.captions={active:null,currentTrack:-1,meta:new WeakMap},this.fullscreen={active:!1},this.options={speed:[],quality:[]},this.debug=new Console(this.config.debug),this.debug.log("Config",this.config),this.debug.log("Support",support),is.nullOrUndefined(this.media)||!is.element(this.media))return void this.debug.error("Setup failed: no suitable element passed");if(this.media.plyr)return void this.debug.warn("Target already setup");if(!this.config.enabled)return void this.debug.error("Setup failed: disabled by config");if(!support.check().api)return void this.debug.error("Setup failed: no support");const i=this.media.cloneNode(!0);i.autoplay=!1,this.elements.original=i;const s=this.media.tagName.toLowerCase();let n=null,r=null;switch(s){case"div":if(n=this.media.querySelector("iframe"),is.element(n)){if(r=parseUrl(n.getAttribute("src")),this.provider=getProviderByUrl(r.toString()),this.elements.container=this.media,this.media=n,this.elements.container.className="",r.search.length){const e=["1","true"];e.includes(r.searchParams.get("autoplay"))&&(this.config.autoplay=!0),e.includes(r.searchParams.get("loop"))&&(this.config.loop.active=!0),this.isYouTube?(this.config.playsinline=e.includes(r.searchParams.get("playsinline")),this.config.youtube.hl=r.searchParams.get("hl")):this.config.playsinline=!0}}else this.provider=this.media.getAttribute(this.config.attributes.embed.provider),this.media.removeAttribute(this.config.attributes.embed.provider);if(is.empty(this.provider)||!Object.values(providers).includes(this.provider))return void this.debug.error("Setup failed: Invalid provider");this.type=types.video;break;case"video":case"audio":this.type=s,this.provider=providers.html5,this.media.hasAttribute("crossorigin")&&(this.config.crossorigin=!0),this.media.hasAttribute("autoplay")&&(this.config.autoplay=!0),(this.media.hasAttribute("playsinline")||this.media.hasAttribute("webkit-playsinline"))&&(this.config.playsinline=!0),this.media.hasAttribute("muted")&&(this.config.muted=!0),this.media.hasAttribute("loop")&&(this.config.loop.active=!0);break;default:return void this.debug.error("Setup failed: unsupported type")}this.supported=support.check(this.type,this.provider,this.config.playsinline),this.supported.api?(this.eventListeners=[],this.listeners=new Listeners(this),this.storage=new Storage(this),this.media.plyr=this,is.element(this.elements.container)||(this.elements.container=createElement("div",{tabindex:0}),wrap(this.media,this.elements.container)),ui.migrateStyles.call(this),ui.addStyleHook.call(this),media.setup.call(this),this.config.debug&&on.call(this,this.elements.container,this.config.events.join(" "),(e=>{this.debug.log(`event: ${e.type}`)})),this.fullscreen=new Fullscreen(this),(this.isHTML5||this.isEmbed&&!this.supported.ui)&&ui.build.call(this),this.listeners.container(),this.listeners.global(),this.config.ads.enabled&&(this.ads=new Ads(this)),this.isHTML5&&this.config.autoplay&&this.once("canplay",(()=>silencePromise(this.play()))),this.lastSeekTime=0,this.config.previewThumbnails.enabled&&(this.previewThumbnails=new PreviewThumbnails(this))):this.debug.error("Setup failed: no support")}get isHTML5(){return this.provider===providers.html5}get isEmbed(){return this.isYouTube||this.isVimeo}get isYouTube(){return this.provider===providers.youtube}get isVimeo(){return this.provider===providers.vimeo}get isVideo(){return this.type===types.video}get isAudio(){return this.type===types.audio}get playing(){return Boolean(this.ready&&!this.paused&&!this.ended)}get paused(){return Boolean(this.media.paused)}get stopped(){return Boolean(this.paused&&0===this.currentTime)}get ended(){return Boolean(this.media.ended)}set currentTime(e){if(!this.duration)return;const t=is.number(e)&&e>0;this.media.currentTime=t?Math.min(e,this.duration):0,this.debug.log(`Seeking to ${this.currentTime} seconds`)}get currentTime(){return Number(this.media.currentTime)}get buffered(){const{buffered:e}=this.media;return is.number(e)?e:e&&e.length&&this.duration>0?e.end(0)/this.duration:0}get seeking(){return Boolean(this.media.seeking)}get duration(){const e=parseFloat(this.config.duration),t=(this.media||{}).duration,i=is.number(t)&&t!==1/0?t:0;return e||i}set volume(e){let t=e;is.string(t)&&(t=Number(t)),is.number(t)||(t=this.storage.get("volume")),is.number(t)||({volume:t}=this.config),t>1&&(t=1),t<0&&(t=0),this.config.volume=t,this.media.volume=t,!is.empty(e)&&this.muted&&t>0&&(this.muted=!1)}get volume(){return Number(this.media.volume)}set muted(e){let t=e;is.boolean(t)||(t=this.storage.get("muted")),is.boolean(t)||(t=this.config.muted),this.config.muted=t,this.media.muted=t}get muted(){return Boolean(this.media.muted)}get hasAudio(){return!this.isHTML5||(!!this.isAudio||(Boolean(this.media.mozHasAudio)||Boolean(this.media.webkitAudioDecodedByteCount)||Boolean(this.media.audioTracks&&this.media.audioTracks.length)))}set speed(e){let t=null;is.number(e)&&(t=e),is.number(t)||(t=this.storage.get("speed")),is.number(t)||(t=this.config.speed.selected);const{minimumSpeed:i,maximumSpeed:s}=this;t=clamp(t,i,s),this.config.speed.selected=t,setTimeout((()=>{this.media&&(this.media.playbackRate=t)}),0)}get speed(){return Number(this.media.playbackRate)}get minimumSpeed(){return this.isYouTube?Math.min(...this.options.speed):this.isVimeo?.5:.0625}get maximumSpeed(){return this.isYouTube?Math.max(...this.options.speed):this.isVimeo?2:16}set quality(e){const t=this.config.quality,i=this.options.quality;if(!i.length)return;let s=[!is.empty(e)&&Number(e),this.storage.get("quality"),t.selected,t.default].find(is.number),n=!0;if(!i.includes(s)){const e=closest(i,s);this.debug.warn(`Unsupported quality option: ${s}, using ${e} instead`),s=e,n=!1}t.selected=s,this.media.quality=s,n&&this.storage.set({quality:s})}get quality(){return this.media.quality}set loop(e){const t=is.boolean(e)?e:this.config.loop.active;this.config.loop.active=t,this.media.loop=t}get loop(){return Boolean(this.media.loop)}set source(e){source.change.call(this,e)}get source(){return this.media.currentSrc}get download(){const{download:e}=this.config.urls;return is.url(e)?e:this.source}set download(e){is.url(e)&&(this.config.urls.download=e,controls.setDownloadUrl.call(this))}set poster(e){this.isVideo?ui.setPoster.call(this,e,!1).catch((()=>{})):this.debug.warn("Poster can only be set for video")}get poster(){return this.isVideo?this.media.getAttribute("poster")||this.media.getAttribute("data-poster"):null}get ratio(){if(!this.isVideo)return null;const e=reduceAspectRatio(getAspectRatio.call(this));return is.array(e)?e.join(":"):e}set ratio(e){this.isVideo?is.string(e)&&validateAspectRatio(e)?(this.config.ratio=reduceAspectRatio(e),setAspectRatio.call(this)):this.debug.error(`Invalid aspect ratio specified (${e})`):this.debug.warn("Aspect ratio can only be set for video")}set autoplay(e){const t=is.boolean(e)?e:this.config.autoplay;this.config.autoplay=t}get autoplay(){return Boolean(this.config.autoplay)}toggleCaptions(e){captions.toggle.call(this,e,!1)}set currentTrack(e){captions.set.call(this,e,!1),captions.setup()}get currentTrack(){const{toggled:e,currentTrack:t}=this.captions;return e?t:-1}set language(e){captions.setLanguage.call(this,e,!1)}get language(){return(captions.getCurrentTrack.call(this)||{}).language}set pip(e){if(!support.pip)return;const t=is.boolean(e)?e:!this.pip;is.function(this.media.webkitSetPresentationMode)&&this.media.webkitSetPresentationMode(t?pip.active:pip.inactive),is.function(this.media.requestPictureInPicture)&&(!this.pip&&t?this.media.requestPictureInPicture():this.pip&&!t&&document.exitPictureInPicture())}get pip(){return support.pip?is.empty(this.media.webkitPresentationMode)?this.media===document.pictureInPictureElement:this.media.webkitPresentationMode===pip.active:null}setPreviewThumbnails(e){this.previewThumbnails&&this.previewThumbnails.loaded&&(this.previewThumbnails.destroy(),this.previewThumbnails=null),Object.assign(this.config.previewThumbnails,e),this.config.previewThumbnails.enabled&&(this.previewThumbnails=new PreviewThumbnails(this))}static supported(e,t,i){return support.check(e,t,i)}static loadSprite(e,t){return loadSprite(e,t)}static setup(e,t={}){let i=null;return is.string(e)?i=Array.from(document.querySelectorAll(e)):is.nodeList(e)?i=Array.from(e):is.array(e)&&(i=e.filter(is.element)),is.empty(i)?null:i.map((e=>new Plyr(e,t)))}}Plyr.defaults=cloneDeep(defaults);export{Plyr as default};
\ No newline at end of file diff --git a/extlib/plyr/plyr.polyfilled.min.mjs.map b/extlib/plyr/plyr.polyfilled.min.mjs.map new file mode 100644 index 00000000..03211111 --- /dev/null +++ b/extlib/plyr/plyr.polyfilled.min.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["node_modules/custom-event-polyfill/polyfill.js","plyr.polyfilled.mjs","node_modules/rangetouch/dist/rangetouch.mjs","node_modules/url-polyfill/url-polyfill.js","src/js/utils/is.js","src/js/utils/animation.js","src/js/utils/browser.js","src/js/utils/objects.js","src/js/utils/elements.js","src/js/support.js","src/js/utils/events.js","src/js/utils/promise.js","src/js/utils/arrays.js","src/js/utils/style.js","src/js/html5.js","src/js/utils/strings.js","src/js/utils/i18n.js","src/js/storage.js","src/js/utils/fetch.js","src/js/utils/load-sprite.js","src/js/utils/time.js","src/js/controls.js","src/js/utils/urls.js","src/js/captions.js","src/js/config/defaults.js","src/js/config/states.js","src/js/config/types.js","src/js/console.js","src/js/fullscreen.js","src/js/utils/load-image.js","src/js/ui.js","src/js/listeners.js","node_modules/loadjs/dist/loadjs.umd.js","src/js/utils/load-script.js","src/js/plugins/vimeo.js","src/js/plugins/youtube.js","src/js/media.js","src/js/plugins/ads.js","src/js/plugins/preview-thumbnails.js","src/js/source.js","src/js/utils/numbers.js","src/js/plyr.js"],"names":["window","ce","CustomEvent","cancelable","preventDefault","defaultPrevented","Error","e","event","params","evt","origPrevent","bubbles","document","createEvent","initCustomEvent","detail","call","this","Object","defineProperty","get","prototype","Event","commonjsGlobal","globalThis","global","self","createCommonjsModule","fn","module","exports","_defineProperty$1","obj","key","value","enumerable","configurable","writable","_classCallCheck","t","TypeError","_defineProperties","n","length","r","_createClass","_defineProperty","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","push","apply","_objectSpread2","arguments","forEach","getOwnPropertyDescriptors","defineProperties","iteratorSupported","Symbol","iterator","error","checkIfIteratorIsSupported","createIterator","items","next","shift","done","serializeParam","encodeURIComponent","replace","deserializeParam","decodeURIComponent","String","URLSearchParams","toString","set","entries","checkIfURLSearchParamsSupported","searchString","typeofSearchString","_fromString","_this","name","append","i","entry","hasOwnProperty","proto","_entries","delete","getAll","slice","has","callback","thisArg","values","searchArray","join","polyfillURLSearchParams","sort","a","b","attribute","attributes","split","u","URL","pathname","href","searchParams","checkIfURLIsSupported","_URL","url","base","baseElement","doc","location","toLowerCase","implementation","createHTMLDocument","createElement","head","appendChild","indexOf","err","anchorElement","body","inputElement","type","protocol","test","checkValidity","search","enableSearchUpdate","enableSearchParamsUpdate","methodName","method","attributeName","_anchorElement","linkURLWithAnchorAttribute","_updateSearchParams","origin","expectedPort","addPortToOrigin","port","hostname","password","username","createObjectURL","blob","revokeObjectURL","polyfillURL","getOrigin","setInterval","defaults","addCSS","thumbWidth","watch","matches","Array","from","querySelectorAll","includes","trigger","dispatchEvent","getConstructor","constructor","instanceOf","isNullOrUndefined","isObject","isNumber","Number","isNaN","isString","isBoolean","Boolean","isFunction","Function","isArray","isNodeList","NodeList","isElement","Element","isEvent","isEmpty","is","nullOrUndefined","object","number","string","boolean","function","array","nodeList","element","empty","getDecimalPlaces","concat","match","Math","max","round","parseFloat","toFixed","RangeTouch","querySelector","rangeTouch","config","init","enabled","style","userSelect","webKitUserSelect","touchAction","listeners","target","changedTouches","o","getAttribute","s","c","getBoundingClientRect","width","clientX","left","disabled","MutationObserver","addedNodes","observe","childList","subtree","map","documentElement","input","isWeakMap","WeakMap","isTextNode","Text","isKeyboardEvent","KeyboardEvent","isCue","TextTrackCue","VTTCue","isTrack","TextTrack","kind","isPromise","Promise","then","nodeType","ownerDocument","isUrl","startsWith","_","weakMap","textNode","keyboardEvent","cue","track","promise","transitionEndEvent","events","WebkitTransition","MozTransition","OTransition","transition","find","undefined","repaint","delay","setTimeout","hidden","offsetHeight","browser","isIE","documentMode","isEdge","navigator","userAgent","isWebkit","isIPhone","platform","isIos","maxTouchPoints","cloneDeep","JSON","parse","stringify","getDeep","path","reduce","extend","sources","source","assign","wrap","elements","wrapper","targets","reverse","index","child","cloneNode","parent","parentNode","sibling","nextSibling","insertBefore","setAttributes","setAttribute","text","innerText","insertAfter","insertElement","removeElement","removeChild","emptyElement","childNodes","lastChild","replaceElement","newChild","oldChild","replaceChild","getAttributesFromSelector","sel","existingAttributes","existing","selector","trim","className","parts","charAt","class","id","toggleHidden","hide","toggleClass","force","classList","contains","hasClass","webkitMatchesSelector","mozMatchesSelector","msMatchesSelector","closest","el","parentElement","getElements","container","getElement","setFocus","tabFocus","focus","preventScroll","classNames","defaultCodecs","support","audio","video","check","provider","playsinline","canPlayInline","api","ui","rangeInput","pip","webkitSetPresentationMode","pictureInPictureEnabled","disablePictureInPicture","airplay","WebKitPlaybackTargetAvailabilityEvent","mime","mediaType","isHTML5","media","canPlayType","textTracks","range","touch","transitions","reducedMotion","matchMedia","supportsPassiveListeners","supported","options","addEventListener","removeEventListener","toggleListener","toggle","passive","capture","eventListeners","on","off","once","onceCallback","args","triggerEvent","plyr","unbindListeners","item","ready","resolve","silencePromise","dedupe","prev","curr","abs","supportsCSS","declaration","CSS","supports","standardRatios","out","x","y","validateAspectRatio","every","reduceAspectRatio","ratio","height","getDivider","w","h","divider","getAspectRatio","embed","videoWidth","videoHeight","setAspectRatio","isVideo","padding","aspectRatio","paddingBottom","isVimeo","vimeo","premium","offsetWidth","parseInt","getComputedStyle","offset","fullscreen","active","transform","add","videoFixedRatio","roundAspectRatio","tolerance","closestRatio","getViewportSize","clientWidth","innerWidth","clientHeight","innerHeight","html5","getSources","getQualityOptions","quality","forced","setup","player","speed","onChange","currentTime","paused","preload","readyState","playbackRate","src","play","load","cancelRequests","blankVideo","debug","log","generateId","prefix","floor","random","format","getPercentage","current","replaceAll","RegExp","toTitleCase","toUpperCase","substr","toPascalCase","toCamelCase","stripHTML","fragment","createDocumentFragment","innerHTML","firstChild","getHTML","resources","youtube","i18n","seekTime","title","k","v","Storage","store","localStorage","getItem","json","storage","setItem","removeItem","fetch","responseType","reject","request","XMLHttpRequest","responseText","response","status","open","send","loadSprite","hasId","isCached","exists","getElementById","update","data","insertAdjacentElement","useStorage","cached","content","result","catch","getHours","trunc","getMinutes","getSeconds","formatTime","time","displayHours","inverted","hours","mins","secs","controls","getIconUrl","iconUrl","host","top","cors","svg4everybody","findElements","selectors","buttons","pause","restart","rewind","fastForward","mute","settings","captions","progress","inputs","seek","volume","display","buffer","duration","seekTooltip","tooltip","warn","toggleNativeControls","createIcon","namespace","iconPath","iconPrefix","icon","createElementNS","focusable","use","setAttributeNS","createLabel","attr","createBadge","badge","menu","createButton","buttonType","props","label","labelPressed","iconPressed","some","control","button","createRange","min","step","autocomplete","role","updateRangeFill","createProgress","suffixKey","played","suffix","createTime","attrs","bindMenuItemShortcuts","menuItem","which","stopPropagation","isRadioButton","showMenuPanel","nextElementSibling","firstElementChild","previousElementSibling","lastElementChild","focusFirstMenuItem","createMenuItem","list","checked","flex","children","node","bind","currentTrack","updateTimeDisplay","updateVolume","setRange","muted","pressed","updateProgress","setProgress","val","getElementsByTagName","nodeValue","buffered","percent","setProperty","updateSeekTooltip","tooltips","visible","show","clientRect","pageX","timeUpdate","invert","invertTime","seeking","durationUpdate","hasDuration","displayDuration","toggleMenuButton","setting","updateSetting","pane","panels","default","getLabel","setQualityMenu","checkMenu","getBadge","sorting","setCaptionsMenu","tracks","getTracks","toggled","language","unshift","setSpeedMenu","minimumSpeed","maximumSpeed","popup","p","firstItem","toggleMenu","composedPath","isMenuItem","getMenuSize","tab","clone","position","opacity","removeAttribute","scrollWidth","scrollHeight","size","restore","propertyName","setDownloadUrl","download","create","defaultAttributes","progressContainer","inner","home","backButton","urls","isEmbed","inject","seektime","addProperty","controlPressed","labels","parseUrl","safe","parser","buildUrlParams","isYouTube","languages","userLanguage","trackEvents","meta","currentTrackNode","languageExists","mode","updateCues","setLanguage","activeClass","findTrack","enableTextTrack","sortIsDefault","sorted","getCurrentTrack","cues","activeCues","getCueAsHTML","cueText","caption","autoplay","autopause","toggleInvert","clickToPlay","hideControls","resetOnEnd","disableContextMenu","loop","selected","keyboard","focused","fallback","iosNative","seekLabel","unmute","enableCaptions","disableCaptions","enterFullscreen","exitFullscreen","frameTitle","menuBack","normal","start","end","all","reset","advertisement","qualityBadge","sdk","iframe","googleIMA","editable","embedContainer","poster","posterEnabled","ads","playing","stopped","loading","hover","isTouch","uiSupported","noTransition","previewThumbnails","thumbContainer","thumbContainerShown","imageContainer","timeContainer","scrubbingContainer","scrubbingContainerShown","hash","publisherId","tagUrl","byline","portrait","transparent","customControls","referrerPolicy","rel","showinfo","iv_load_policy","modestbranding","noCookie","inactive","providers","types","getProviderByUrl","noop","Console","console","Fullscreen","scrollPosition","scrollX","scrollY","scrollTo","overflow","viewport","property","hasProperty","cleanupViewport","part","keyCode","activeElement","first","last","shiftKey","forceFallback","native","requestFullscreen","webkitEnterFullscreen","toggleFallback","navigationUI","webkitExitFullscreen","action","cancelFullScreen","exit","enter","proxy","trapFocus","fullscreenEnabled","webkitFullscreenEnabled","mozFullScreenEnabled","msFullscreenEnabled","usingNative","pre","getRootNode","fullscreenElement","shadowRoot","loadImage","minWidth","image","Image","handler","onload","onerror","naturalWidth","addStyleHook","build","checkPlaying","setTitle","setPoster","togglePoster","enable","backgroundImage","backgroundSize","toggleControls","checkLoading","clearTimeout","timers","controlsElement","recentTouchSeek","lastSeekTime","Date","now","migrateStyles","getPropertyValue","removeProperty","Listeners","focusTimer","lastKeyDown","timeStamp","wasKeyDown","removeCurrent","handleKey","firstTouch","setTabFocus","setGutter","useNativeAspectRatio","maxWidth","margin","viewportWidth","viewportHeight","resized","isAudio","ended","togglePlay","proxyEvents","defaultHandler","customHandlerKey","customHandler","returned","hasCustomHandler","inputEvent","forward","toggleCaptions","code","rect","currentTarget","hasAttribute","seekTo","loaded","startMove","endMove","startScrubbing","endScrubbing","webkitDirectionInvertedFromDevice","deltaX","deltaY","direction","sign","increaseVolume","lastKey","repeat","altKey","ctrlKey","metaKey","decreaseVolume","loadjs_umd","devnull","bundleIdCache","bundleResultCache","bundleCallbackQueue","subscribe","bundleIds","callbackFn","bundleId","depsNotFound","numWaiting","pathsNotFound","publish","q","splice","executeCallbacks","success","loadFile","numTries","isLegacyIECss","async","maxTries","numRetries","beforeCallbackFn","before","pathStripped","relList","as","onbeforeload","ev","sheet","cssText","loadFiles","paths","loadjs","arg1","arg2","loadFn","returnPromise","deps","isDefined","factory","loadScript","parseId","$2","parseHash","found","groups","assurePlaybackState","hasPlayed","Vimeo","frameParams","hashParam","sidedock","gesture","thumbnail_url","Player","disableTextTrack","stop","restorePause","setVolume","setCurrentTime","setPlaybackRate","currentSrc","setLoop","getVideoUrl","getVideoWidth","getVideoHeight","dimensions","setAutopause","state","getVideoTitle","getCurrentTime","getDuration","getTextTracks","strippedCues","getPaused","seconds","getHost","YT","onYouTubeIframeAPIReady","getTitle","videoId","currentId","posterSrc","playerVars","hl","disablekb","cc_load_policy","cc_lang_pref","widget_referrer","onError","message","onPlaybackRateChange","instance","getPlaybackRate","onReady","playVideo","pauseVideo","stopVideo","speeds","getAvailablePlaybackRates","clearInterval","buffering","getVideoLoadedFraction","lastBuffered","onStateChange","unMute","destroy","manager","displayContainer","remove","Ads","google","ima","startSafetyTimer","managerPromise","clearSafetyTimer","setupIMA","setVpaidMode","ImaSdkSettings","VpaidMode","ENABLED","setLocale","setDisableCustomPlaybackForIOS10Plus","AdDisplayContainer","loader","AdsLoader","AdsManagerLoadedEvent","Type","ADS_MANAGER_LOADED","onAdsManagerLoaded","AdErrorEvent","AD_ERROR","onAdError","requestAds","AdsRequest","adTagUrl","linearAdSlotWidth","linearAdSlotHeight","nonLinearAdSlotWidth","nonLinearAdSlotHeight","forceNonLinearFullSlot","setAdWillPlayMuted","countdownTimer","getRemainingTime","AdsRenderingSettings","restoreCustomPlaybackStateOnAdBreakComplete","enablePreloading","getAdsManager","cuePoints","getCuePoints","AdEvent","onAdEvent","cuePoint","seekElement","cuePercentage","ad","getAd","adData","getAdData","LOADED","pollCountdown","isLinear","STARTED","ALL_ADS_COMPLETED","loadAds","contentComplete","CONTENT_PAUSE_REQUESTED","pauseContent","CONTENT_RESUME_REQUESTED","resumeContent","LOG","adError","getMessage","cancel","addCuePoints","seekedTime","discardAdBreak","resize","ViewMode","NORMAL","initialize","initialized","zIndex","handlers","safetyTimer","AV_PUBLISHERID","AV_CHANNELID","AV_URL","cb","AV_WIDTH","AV_HEIGHT","AV_CDIM2","parseVtt","vttDataString","processedList","frame","line","startTime","lineSplit","matchTimes","endTime","fitRatio","outer","PreviewThumbnails","getThumbnails","render","determineContainerAutoSizing","sortAndResolve","thumbnails","promises","getThumbnail","thumbnail","frames","urlPrefix","substring","lastIndexOf","tempImage","naturalHeight","percentage","mousePosX","thumb","showImageAtCurrentTime","toggleThumbContainer","mouseDown","toggleScrubbingContainer","ceil","lastTime","scrubbing","setScrubbingContainerSize","setThumbContainerSizeAndPos","thumbNum","findIndex","hasThumb","qualityIndex","loadedImages","showingThumb","thumbFilename","thumbUrl","currentImageElement","dataset","filename","showImage","removeOldImages","loadingImage","usingSprites","previewImage","showingThumbFilename","newImage","setImageSizeAndOffset","currentImageContainer","preloadNearby","getHigherQuality","currentImage","tagName","removeDelay","deleting","oldThumbFilename","thumbnailsClone","foundOne","newThumbFilename","thumbURL","currentQualityIndex","previewImageHeight","thumbContainerHeight","clearShowing","sizeSpecifiedInCSS","thumbAspectRatio","thumbHeight","setThumbContainerPos","seekbarRect","plyrRect","minVal","maxVal","right","previewPos","multiplier","lastMouseMoveTime","currentScrubbingImageElement","currentThumbnailImageElement","insertElements","change","crossorigin","clamp","Plyr","webkitShowPlaybackTargetPicker","isHidden","hiding","eventName","soft","original","unload","failed","jQuery","truthy","tabindex","inputIsValid","fauxDuration","realDuration","Infinity","hasAudio","mozHasAudio","webkitAudioDecodedByteCount","audioTracks","updateStorage","requestPictureInPicture","exitPictureInPicture","webkitPresentationMode","pictureInPictureElement","setPreviewThumbnails","thumbnailSource","static","inline"],"mappings":"CAMA,WACE,GAAsB,oBAAXA,OAIX,IACE,IAAIC,EAAK,IAAID,OAAOE,YAAY,OAAQ,CAAEC,YAAY,IAEtD,GADAF,EAAGG,kBACyB,IAAxBH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2a,UAI7DhmB,GAAGM,SAAShL,KAAKwW,MAAMg1B,4BACpBxrC,KAAK+V,KAAOuB,EACftX,KAAKwW,MAAMg1B,0BACFxrC,KAAK+V,MAAQuB,GACtB3X,SAAS8rC,wBAQX11B,UACF,OAAKV,QAAQU,IAKRrL,GAAGU,MAAMpL,KAAKwW,MAAMk1B,wBAKlB1rC,KAAKwW,QAAU7W,SAASgsC,wBAJtB3rC,KAAKwW,MAAMk1B,yBAA2B31B,IAAI6E,OAL1C,KAeXgxB,qBAAqBC,GACf7rC,KAAKsvB,mBAAqBtvB,KAAKsvB,kBAAkB+H,SACnDr3B,KAAKsvB,kBAAkB4P,UACvBl/B,KAAKsvB,kBAAoB,MAG3BrvB,OAAOsR,OAAOvR,KAAKgM,OAAOsjB,kBAAmBuc,GAGzC7rC,KAAKgM,OAAOsjB,kBAAkBpjB,UAChClM,KAAKsvB,kBAAoB,IAAI6V,kBAAkBnlC,OAqMnC8rC,iBAAC7kC,EAAMwO,EAAUs2B,GAC/B,OAAO12B,QAAQG,MAAMvO,EAAMwO,EAAUs2B,GAQtBD,kBAAC7lC,EAAK6N,GACrB,OAAO4L,WAAWzZ,EAAK6N,GAQbg4B,aAACt4B,EAAU0D,EAAU,IAC/B,IAAIvF,EAAU,KAUd,OARIjH,GAAGI,OAAO0I,GACZ7B,EAAU3I,MAAMC,KAAKtJ,SAASuJ,iBAAiBsK,IACtC9I,GAAGQ,SAASsI,GACrB7B,EAAU3I,MAAMC,KAAKuK,GACZ9I,GAAGO,MAAMuI,KAClB7B,EAAU6B,EAASvR,OAAOyI,GAAGS,UAG3BT,GAAGU,MAAMuG,GACJ,KAGFA,EAAQnE,KAAKlM,GAAM,IAAI6oC,KAAK7oC,EAAG4V,MAI1CizB,KAAKxhC,SAAWkI,UAAUlI,iBxCqvPjBwhC","file":"plyr.polyfilled.min.mjs","sourcesContent":["// Polyfill for creating CustomEvents on IE9/10/11\n\n// code pulled from:\n// https://github.com/d4tocchini/customevent-polyfill\n// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill\n\n(function() {\n if (typeof window === 'undefined') {\n return;\n }\n\n try {\n var ce = new window.CustomEvent('test', { cancelable: true });\n ce.preventDefault();\n if (ce.defaultPrevented !== true) {\n // IE has problems with .preventDefault() on custom events\n // http://stackoverflow.com/questions/23349191\n throw new Error('Could not prevent default');\n }\n } catch (e) {\n var CustomEvent = function(event, params) {\n var evt, origPrevent;\n params = params || {};\n params.bubbles = !!params.bubbles;\n params.cancelable = !!params.cancelable;\n\n evt = document.createEvent('CustomEvent');\n evt.initCustomEvent(\n event,\n params.bubbles,\n params.cancelable,\n params.detail\n );\n origPrevent = evt.preventDefault;\n evt.preventDefault = function() {\n origPrevent.call(this);\n try {\n Object.defineProperty(this, 'defaultPrevented', {\n get: function() {\n return true;\n }\n });\n } catch (e) {\n this.defaultPrevented = true;\n }\n };\n return evt;\n };\n\n CustomEvent.prototype = window.Event.prototype;\n window.CustomEvent = CustomEvent; // expose definition to window\n }\n})();\n","// Polyfill for creating CustomEvents on IE9/10/11\n// code pulled from:\n// https://github.com/d4tocchini/customevent-polyfill\n// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill\n(function () {\n if (typeof window === 'undefined') {\n return;\n }\n\n try {\n var ce = new window.CustomEvent('test', {\n cancelable: true\n });\n ce.preventDefault();\n\n if (ce.defaultPrevented !== true) {\n // IE has problems with .preventDefault() on custom events\n // http://stackoverflow.com/questions/23349191\n throw new Error('Could not prevent default');\n }\n } catch (e) {\n var CustomEvent = function (event, params) {\n var evt, origPrevent;\n params = params || {};\n params.bubbles = !!params.bubbles;\n params.cancelable = !!params.cancelable;\n evt = document.createEvent('CustomEvent');\n evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);\n origPrevent = evt.preventDefault;\n\n evt.preventDefault = function () {\n origPrevent.call(this);\n\n try {\n Object.defineProperty(this, 'defaultPrevented', {\n get: function () {\n return true;\n }\n });\n } catch (e) {\n this.defaultPrevented = true;\n }\n };\n\n return evt;\n };\n\n CustomEvent.prototype = window.Event.prototype;\n window.CustomEvent = CustomEvent; // expose definition to window\n }\n})();\n\nvar commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nfunction createCommonjsModule(fn, module) {\n\treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n}\n\n(function (global) {\n /**\r\n * Polyfill URLSearchParams\r\n *\r\n * Inspired from : https://github.com/WebReflection/url-search-params/blob/master/src/url-search-params.js\r\n */\n var checkIfIteratorIsSupported = function () {\n try {\n return !!Symbol.iterator;\n } catch (error) {\n return false;\n }\n };\n\n var iteratorSupported = checkIfIteratorIsSupported();\n\n var createIterator = function (items) {\n var iterator = {\n next: function () {\n var value = items.shift();\n return {\n done: value === void 0,\n value: value\n };\n }\n };\n\n if (iteratorSupported) {\n iterator[Symbol.iterator] = function () {\n return iterator;\n };\n }\n\n return iterator;\n };\n /**\r\n * Search param name and values should be encoded according to https://url.spec.whatwg.org/#urlencoded-serializing\r\n * encodeURIComponent() produces the same result except encoding spaces as `%20` instead of `+`.\r\n */\n\n\n var serializeParam = function (value) {\n return encodeURIComponent(value).replace(/%20/g, '+');\n };\n\n var deserializeParam = function (value) {\n return decodeURIComponent(String(value).replace(/\\+/g, ' '));\n };\n\n var polyfillURLSearchParams = function () {\n var URLSearchParams = function (searchString) {\n Object.defineProperty(this, '_entries', {\n writable: true,\n value: {}\n });\n var typeofSearchString = typeof searchString;\n\n if (typeofSearchString === 'undefined') ; else if (typeofSearchString === 'string') {\n if (searchString !== '') {\n this._fromString(searchString);\n }\n } else if (searchString instanceof URLSearchParams) {\n var _this = this;\n\n searchString.forEach(function (value, name) {\n _this.append(name, value);\n });\n } else if (searchString !== null && typeofSearchString === 'object') {\n if (Object.prototype.toString.call(searchString) === '[object Array]') {\n for (var i = 0; i < searchString.length; i++) {\n var entry = searchString[i];\n\n if (Object.prototype.toString.call(entry) === '[object Array]' || entry.length !== 2) {\n this.append(entry[0], entry[1]);\n } else {\n throw new TypeError('Expected [string, any] as entry at index ' + i + ' of URLSearchParams\\'s input');\n }\n }\n } else {\n for (var key in searchString) {\n if (searchString.hasOwnProperty(key)) {\n this.append(key, searchString[key]);\n }\n }\n }\n } else {\n throw new TypeError('Unsupported input\\'s type for URLSearchParams');\n }\n };\n\n var proto = URLSearchParams.prototype;\n\n proto.append = function (name, value) {\n if (name in this._entries) {\n this._entries[name].push(String(value));\n } else {\n this._entries[name] = [String(value)];\n }\n };\n\n proto.delete = function (name) {\n delete this._entries[name];\n };\n\n proto.get = function (name) {\n return name in this._entries ? this._entries[name][0] : null;\n };\n\n proto.getAll = function (name) {\n return name in this._entries ? this._entries[name].slice(0) : [];\n };\n\n proto.has = function (name) {\n return name in this._entries;\n };\n\n proto.set = function (name, value) {\n this._entries[name] = [String(value)];\n };\n\n proto.forEach = function (callback, thisArg) {\n var entries;\n\n for (var name in this._entries) {\n if (this._entries.hasOwnProperty(name)) {\n entries = this._entries[name];\n\n for (var i = 0; i < entries.length; i++) {\n callback.call(thisArg, entries[i], name, this);\n }\n }\n }\n };\n\n proto.keys = function () {\n var items = [];\n this.forEach(function (value, name) {\n items.push(name);\n });\n return createIterator(items);\n };\n\n proto.values = function () {\n var items = [];\n this.forEach(function (value) {\n items.push(value);\n });\n return createIterator(items);\n };\n\n proto.entries = function () {\n var items = [];\n this.forEach(function (value, name) {\n items.push([name, value]);\n });\n return createIterator(items);\n };\n\n if (iteratorSupported) {\n proto[Symbol.iterator] = proto.entries;\n }\n\n proto.toString = function () {\n var searchArray = [];\n this.forEach(function (value, name) {\n searchArray.push(serializeParam(name) + '=' + serializeParam(value));\n });\n return searchArray.join('&');\n };\n\n global.URLSearchParams = URLSearchParams;\n };\n\n var checkIfURLSearchParamsSupported = function () {\n try {\n var URLSearchParams = global.URLSearchParams;\n return new URLSearchParams('?a=1').toString() === 'a=1' && typeof URLSearchParams.prototype.set === 'function' && typeof URLSearchParams.prototype.entries === 'function';\n } catch (e) {\n return false;\n }\n };\n\n if (!checkIfURLSearchParamsSupported()) {\n polyfillURLSearchParams();\n }\n\n var proto = global.URLSearchParams.prototype;\n\n if (typeof proto.sort !== 'function') {\n proto.sort = function () {\n var _this = this;\n\n var items = [];\n this.forEach(function (value, name) {\n items.push([name, value]);\n\n if (!_this._entries) {\n _this.delete(name);\n }\n });\n items.sort(function (a, b) {\n if (a[0] < b[0]) {\n return -1;\n } else if (a[0] > b[0]) {\n return +1;\n } else {\n return 0;\n }\n });\n\n if (_this._entries) {\n // force reset because IE keeps keys index\n _this._entries = {};\n }\n\n for (var i = 0; i < items.length; i++) {\n this.append(items[i][0], items[i][1]);\n }\n };\n }\n\n if (typeof proto._fromString !== 'function') {\n Object.defineProperty(proto, '_fromString', {\n enumerable: false,\n configurable: false,\n writable: false,\n value: function (searchString) {\n if (this._entries) {\n this._entries = {};\n } else {\n var keys = [];\n this.forEach(function (value, name) {\n keys.push(name);\n });\n\n for (var i = 0; i < keys.length; i++) {\n this.delete(keys[i]);\n }\n }\n\n searchString = searchString.replace(/^\\?/, '');\n var attributes = searchString.split('&');\n var attribute;\n\n for (var i = 0; i < attributes.length; i++) {\n attribute = attributes[i].split('=');\n this.append(deserializeParam(attribute[0]), attribute.length > 1 ? deserializeParam(attribute[1]) : '');\n }\n }\n });\n } // HTMLAnchorElement\n\n})(typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal);\n\n(function (global) {\n /**\r\n * Polyfill URL\r\n *\r\n * Inspired from : https://github.com/arv/DOM-URL-Polyfill/blob/master/src/url.js\r\n */\n var checkIfURLIsSupported = function () {\n try {\n var u = new global.URL('b', 'http://a');\n u.pathname = 'c d';\n return u.href === 'http://a/c%20d' && u.searchParams;\n } catch (e) {\n return false;\n }\n };\n\n var polyfillURL = function () {\n var _URL = global.URL;\n\n var URL = function (url, base) {\n if (typeof url !== 'string') url = String(url);\n if (base && typeof base !== 'string') base = String(base); // Only create another document if the base is different from current location.\n\n var doc = document,\n baseElement;\n\n if (base && (global.location === void 0 || base !== global.location.href)) {\n base = base.toLowerCase();\n doc = document.implementation.createHTMLDocument('');\n baseElement = doc.createElement('base');\n baseElement.href = base;\n doc.head.appendChild(baseElement);\n\n try {\n if (baseElement.href.indexOf(base) !== 0) throw new Error(baseElement.href);\n } catch (err) {\n throw new Error('URL unable to set base ' + base + ' due to ' + err);\n }\n }\n\n var anchorElement = doc.createElement('a');\n anchorElement.href = url;\n\n if (baseElement) {\n doc.body.appendChild(anchorElement);\n anchorElement.href = anchorElement.href; // force href to refresh\n }\n\n var inputElement = doc.createElement('input');\n inputElement.type = 'url';\n inputElement.value = url;\n\n if (anchorElement.protocol === ':' || !/:/.test(anchorElement.href) || !inputElement.checkValidity() && !base) {\n throw new TypeError('Invalid URL');\n }\n\n Object.defineProperty(this, '_anchorElement', {\n value: anchorElement\n }); // create a linked searchParams which reflect its changes on URL\n\n var searchParams = new global.URLSearchParams(this.search);\n var enableSearchUpdate = true;\n var enableSearchParamsUpdate = true;\n\n var _this = this;\n\n ['append', 'delete', 'set'].forEach(function (methodName) {\n var method = searchParams[methodName];\n\n searchParams[methodName] = function () {\n method.apply(searchParams, arguments);\n\n if (enableSearchUpdate) {\n enableSearchParamsUpdate = false;\n _this.search = searchParams.toString();\n enableSearchParamsUpdate = true;\n }\n };\n });\n Object.defineProperty(this, 'searchParams', {\n value: searchParams,\n enumerable: true\n });\n var search = void 0;\n Object.defineProperty(this, '_updateSearchParams', {\n enumerable: false,\n configurable: false,\n writable: false,\n value: function () {\n if (this.search !== search) {\n search = this.search;\n\n if (enableSearchParamsUpdate) {\n enableSearchUpdate = false;\n\n this.searchParams._fromString(this.search);\n\n enableSearchUpdate = true;\n }\n }\n }\n });\n };\n\n var proto = URL.prototype;\n\n var linkURLWithAnchorAttribute = function (attributeName) {\n Object.defineProperty(proto, attributeName, {\n get: function () {\n return this._anchorElement[attributeName];\n },\n set: function (value) {\n this._anchorElement[attributeName] = value;\n },\n enumerable: true\n });\n };\n\n ['hash', 'host', 'hostname', 'port', 'protocol'].forEach(function (attributeName) {\n linkURLWithAnchorAttribute(attributeName);\n });\n Object.defineProperty(proto, 'search', {\n get: function () {\n return this._anchorElement['search'];\n },\n set: function (value) {\n this._anchorElement['search'] = value;\n\n this._updateSearchParams();\n },\n enumerable: true\n });\n Object.defineProperties(proto, {\n 'toString': {\n get: function () {\n var _this = this;\n\n return function () {\n return _this.href;\n };\n }\n },\n 'href': {\n get: function () {\n return this._anchorElement.href.replace(/\\?$/, '');\n },\n set: function (value) {\n this._anchorElement.href = value;\n\n this._updateSearchParams();\n },\n enumerable: true\n },\n 'pathname': {\n get: function () {\n return this._anchorElement.pathname.replace(/(^\\/?)/, '/');\n },\n set: function (value) {\n this._anchorElement.pathname = value;\n },\n enumerable: true\n },\n 'origin': {\n get: function () {\n // get expected port from protocol\n var expectedPort = {\n 'http:': 80,\n 'https:': 443,\n 'ftp:': 21\n }[this._anchorElement.protocol]; // add port to origin if, expected port is different than actual port\n // and it is not empty f.e http://foo:8080\n // 8080 != 80 && 8080 != ''\n\n var addPortToOrigin = this._anchorElement.port != expectedPort && this._anchorElement.port !== '';\n return this._anchorElement.protocol + '//' + this._anchorElement.hostname + (addPortToOrigin ? ':' + this._anchorElement.port : '');\n },\n enumerable: true\n },\n 'password': {\n // TODO\n get: function () {\n return '';\n },\n set: function (value) {},\n enumerable: true\n },\n 'username': {\n // TODO\n get: function () {\n return '';\n },\n set: function (value) {},\n enumerable: true\n }\n });\n\n URL.createObjectURL = function (blob) {\n return _URL.createObjectURL.apply(_URL, arguments);\n };\n\n URL.revokeObjectURL = function (url) {\n return _URL.revokeObjectURL.apply(_URL, arguments);\n };\n\n global.URL = URL;\n };\n\n if (!checkIfURLIsSupported()) {\n polyfillURL();\n }\n\n if (global.location !== void 0 && !('origin' in global.location)) {\n var getOrigin = function () {\n return global.location.protocol + '//' + global.location.hostname + (global.location.port ? ':' + global.location.port : '');\n };\n\n try {\n Object.defineProperty(global.location, 'origin', {\n get: getOrigin,\n enumerable: true\n });\n } catch (e) {\n setInterval(function () {\n global.location.origin = getOrigin();\n }, 100);\n }\n }\n})(typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal);\n\nfunction _defineProperty$1(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction _classCallCheck(e, t) {\n if (!(e instanceof t)) throw new TypeError(\"Cannot call a class as a function\");\n}\n\nfunction _defineProperties(e, t) {\n for (var n = 0; n < t.length; n++) {\n var r = t[n];\n r.enumerable = r.enumerable || !1, r.configurable = !0, \"value\" in r && (r.writable = !0), Object.defineProperty(e, r.key, r);\n }\n}\n\nfunction _createClass(e, t, n) {\n return t && _defineProperties(e.prototype, t), n && _defineProperties(e, n), e;\n}\n\nfunction _defineProperty(e, t, n) {\n return t in e ? Object.defineProperty(e, t, {\n value: n,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[t] = n, e;\n}\n\nfunction ownKeys(e, t) {\n var n = Object.keys(e);\n\n if (Object.getOwnPropertySymbols) {\n var r = Object.getOwnPropertySymbols(e);\n t && (r = r.filter(function (t) {\n return Object.getOwnPropertyDescriptor(e, t).enumerable;\n })), n.push.apply(n, r);\n }\n\n return n;\n}\n\nfunction _objectSpread2(e) {\n for (var t = 1; t < arguments.length; t++) {\n var n = null != arguments[t] ? arguments[t] : {};\n t % 2 ? ownKeys(Object(n), !0).forEach(function (t) {\n _defineProperty(e, t, n[t]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : ownKeys(Object(n)).forEach(function (t) {\n Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));\n });\n }\n\n return e;\n}\n\nvar defaults$1 = {\n addCSS: !0,\n thumbWidth: 15,\n watch: !0\n};\n\nfunction matches$1(e, t) {\n return function () {\n return Array.from(document.querySelectorAll(t)).includes(this);\n }.call(e, t);\n}\n\nfunction trigger(e, t) {\n if (e && t) {\n var n = new Event(t, {\n bubbles: !0\n });\n e.dispatchEvent(n);\n }\n}\n\nvar getConstructor$1 = function (e) {\n return null != e ? e.constructor : null;\n},\n instanceOf$1 = function (e, t) {\n return !!(e && t && e instanceof t);\n},\n isNullOrUndefined$1 = function (e) {\n return null == e;\n},\n isObject$1 = function (e) {\n return getConstructor$1(e) === Object;\n},\n isNumber$1 = function (e) {\n return getConstructor$1(e) === Number && !Number.isNaN(e);\n},\n isString$1 = function (e) {\n return getConstructor$1(e) === String;\n},\n isBoolean$1 = function (e) {\n return getConstructor$1(e) === Boolean;\n},\n isFunction$1 = function (e) {\n return getConstructor$1(e) === Function;\n},\n isArray$1 = function (e) {\n return Array.isArray(e);\n},\n isNodeList$1 = function (e) {\n return instanceOf$1(e, NodeList);\n},\n isElement$1 = function (e) {\n return instanceOf$1(e, Element);\n},\n isEvent$1 = function (e) {\n return instanceOf$1(e, Event);\n},\n isEmpty$1 = function (e) {\n return isNullOrUndefined$1(e) || (isString$1(e) || isArray$1(e) || isNodeList$1(e)) && !e.length || isObject$1(e) && !Object.keys(e).length;\n},\n is$1 = {\n nullOrUndefined: isNullOrUndefined$1,\n object: isObject$1,\n number: isNumber$1,\n string: isString$1,\n boolean: isBoolean$1,\n function: isFunction$1,\n array: isArray$1,\n nodeList: isNodeList$1,\n element: isElement$1,\n event: isEvent$1,\n empty: isEmpty$1\n};\n\nfunction getDecimalPlaces(e) {\n var t = \"\".concat(e).match(/(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/);\n return t ? Math.max(0, (t[1] ? t[1].length : 0) - (t[2] ? +t[2] : 0)) : 0;\n}\n\nfunction round(e, t) {\n if (1 > t) {\n var n = getDecimalPlaces(t);\n return parseFloat(e.toFixed(n));\n }\n\n return Math.round(e / t) * t;\n}\n\nvar RangeTouch = function () {\n function e(t, n) {\n _classCallCheck(this, e), is$1.element(t) ? this.element = t : is$1.string(t) && (this.element = document.querySelector(t)), is$1.element(this.element) && is$1.empty(this.element.rangeTouch) && (this.config = _objectSpread2({}, defaults$1, {}, n), this.init());\n }\n\n return _createClass(e, [{\n key: \"init\",\n value: function () {\n e.enabled && (this.config.addCSS && (this.element.style.userSelect = \"none\", this.element.style.webKitUserSelect = \"none\", this.element.style.touchAction = \"manipulation\"), this.listeners(!0), this.element.rangeTouch = this);\n }\n }, {\n key: \"destroy\",\n value: function () {\n e.enabled && (this.config.addCSS && (this.element.style.userSelect = \"\", this.element.style.webKitUserSelect = \"\", this.element.style.touchAction = \"\"), this.listeners(!1), this.element.rangeTouch = null);\n }\n }, {\n key: \"listeners\",\n value: function (e) {\n var t = this,\n n = e ? \"addEventListener\" : \"removeEventListener\";\n [\"touchstart\", \"touchmove\", \"touchend\"].forEach(function (e) {\n t.element[n](e, function (e) {\n return t.set(e);\n }, !1);\n });\n }\n }, {\n key: \"get\",\n value: function (t) {\n if (!e.enabled || !is$1.event(t)) return null;\n var n,\n r = t.target,\n i = t.changedTouches[0],\n o = parseFloat(r.getAttribute(\"min\")) || 0,\n s = parseFloat(r.getAttribute(\"max\")) || 100,\n u = parseFloat(r.getAttribute(\"step\")) || 1,\n c = r.getBoundingClientRect(),\n a = 100 / c.width * (this.config.thumbWidth / 2) / 100;\n return 0 > (n = 100 / c.width * (i.clientX - c.left)) ? n = 0 : 100 < n && (n = 100), 50 > n ? n -= (100 - 2 * n) * a : 50 < n && (n += 2 * (n - 50) * a), o + round(n / 100 * (s - o), u);\n }\n }, {\n key: \"set\",\n value: function (t) {\n e.enabled && is$1.event(t) && !t.target.disabled && (t.preventDefault(), t.target.value = this.get(t), trigger(t.target, \"touchend\" === t.type ? \"change\" : \"input\"));\n }\n }], [{\n key: \"setup\",\n value: function (t) {\n var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {},\n r = null;\n if (is$1.empty(t) || is$1.string(t) ? r = Array.from(document.querySelectorAll(is$1.string(t) ? t : 'input[type=\"range\"]')) : is$1.element(t) ? r = [t] : is$1.nodeList(t) ? r = Array.from(t) : is$1.array(t) && (r = t.filter(is$1.element)), is$1.empty(r)) return null;\n\n var i = _objectSpread2({}, defaults$1, {}, n);\n\n if (is$1.string(t) && i.watch) {\n var o = new MutationObserver(function (n) {\n Array.from(n).forEach(function (n) {\n Array.from(n.addedNodes).forEach(function (n) {\n is$1.element(n) && matches$1(n, t) && new e(n, i);\n });\n });\n });\n o.observe(document.body, {\n childList: !0,\n subtree: !0\n });\n }\n\n return r.map(function (t) {\n return new e(t, n);\n });\n }\n }, {\n key: \"enabled\",\n get: function () {\n return \"ontouchstart\" in document.documentElement;\n }\n }]), e;\n}();\n\n// ==========================================================================\n// Type checking utils\n// ==========================================================================\nconst getConstructor = input => input !== null && typeof input !== 'undefined' ? input.constructor : null;\n\nconst instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor);\n\nconst isNullOrUndefined = input => input === null || typeof input === 'undefined';\n\nconst isObject = input => getConstructor(input) === Object;\n\nconst isNumber = input => getConstructor(input) === Number && !Number.isNaN(input);\n\nconst isString = input => getConstructor(input) === String;\n\nconst isBoolean = input => getConstructor(input) === Boolean;\n\nconst isFunction = input => getConstructor(input) === Function;\n\nconst isArray = input => Array.isArray(input);\n\nconst isWeakMap = input => instanceOf(input, WeakMap);\n\nconst isNodeList = input => instanceOf(input, NodeList);\n\nconst isTextNode = input => getConstructor(input) === Text;\n\nconst isEvent = input => instanceOf(input, Event);\n\nconst isKeyboardEvent = input => instanceOf(input, KeyboardEvent);\n\nconst isCue = input => instanceOf(input, window.TextTrackCue) || instanceOf(input, window.VTTCue);\n\nconst isTrack = input => instanceOf(input, TextTrack) || !isNullOrUndefined(input) && isString(input.kind);\n\nconst isPromise = input => instanceOf(input, Promise) && isFunction(input.then);\n\nconst isElement = input => input !== null && typeof input === 'object' && input.nodeType === 1 && typeof input.style === 'object' && typeof input.ownerDocument === 'object';\n\nconst isEmpty = input => isNullOrUndefined(input) || (isString(input) || isArray(input) || isNodeList(input)) && !input.length || isObject(input) && !Object.keys(input).length;\n\nconst isUrl = input => {\n // Accept a URL object\n if (instanceOf(input, window.URL)) {\n return true;\n } // Must be string from here\n\n\n if (!isString(input)) {\n return false;\n } // Add the protocol if required\n\n\n let string = input;\n\n if (!input.startsWith('http://') || !input.startsWith('https://')) {\n string = `http://${input}`;\n }\n\n try {\n return !isEmpty(new URL(string).hostname);\n } catch (_) {\n return false;\n }\n};\n\nvar is = {\n nullOrUndefined: isNullOrUndefined,\n object: isObject,\n number: isNumber,\n string: isString,\n boolean: isBoolean,\n function: isFunction,\n array: isArray,\n weakMap: isWeakMap,\n nodeList: isNodeList,\n element: isElement,\n textNode: isTextNode,\n event: isEvent,\n keyboardEvent: isKeyboardEvent,\n cue: isCue,\n track: isTrack,\n promise: isPromise,\n url: isUrl,\n empty: isEmpty\n};\n\n// ==========================================================================\nconst transitionEndEvent = (() => {\n const element = document.createElement('span');\n const events = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend'\n };\n const type = Object.keys(events).find(event => element.style[event] !== undefined);\n return is.string(type) ? events[type] : false;\n})(); // Force repaint of element\n\nfunction repaint(element, delay) {\n setTimeout(() => {\n try {\n // eslint-disable-next-line no-param-reassign\n element.hidden = true; // eslint-disable-next-line no-unused-expressions\n\n element.offsetHeight; // eslint-disable-next-line no-param-reassign\n\n element.hidden = false;\n } catch (_) {// Do nothing\n }\n }, delay);\n}\n\n// ==========================================================================\n// Browser sniffing\n// Unfortunately, due to mixed support, UA sniffing is required\n// ==========================================================================\nconst browser = {\n isIE: Boolean(window.document.documentMode),\n isEdge: window.navigator.userAgent.includes('Edge'),\n isWebkit: 'WebkitAppearance' in document.documentElement.style && !/Edge/.test(navigator.userAgent),\n isIPhone: /(iPhone|iPod)/gi.test(navigator.platform),\n isIos: navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 || /(iPad|iPhone|iPod)/gi.test(navigator.platform)\n};\n\n// ==========================================================================\n\nfunction cloneDeep(object) {\n return JSON.parse(JSON.stringify(object));\n} // Get a nested value in an object\n\nfunction getDeep(object, path) {\n return path.split('.').reduce((obj, key) => obj && obj[key], object);\n} // Deep extend destination object with N more objects\n\nfunction extend(target = {}, ...sources) {\n if (!sources.length) {\n return target;\n }\n\n const source = sources.shift();\n\n if (!is.object(source)) {\n return target;\n }\n\n Object.keys(source).forEach(key => {\n if (is.object(source[key])) {\n if (!Object.keys(target).includes(key)) {\n Object.assign(target, {\n [key]: {}\n });\n }\n\n extend(target[key], source[key]);\n } else {\n Object.assign(target, {\n [key]: source[key]\n });\n }\n });\n return extend(target, ...sources);\n}\n\n// ==========================================================================\n\nfunction wrap(elements, wrapper) {\n // Convert `elements` to an array, if necessary.\n const targets = elements.length ? elements : [elements]; // Loops backwards to prevent having to clone the wrapper on the\n // first element (see `child` below).\n\n Array.from(targets).reverse().forEach((element, index) => {\n const child = index > 0 ? wrapper.cloneNode(true) : wrapper; // Cache the current parent and sibling.\n\n const parent = element.parentNode;\n const sibling = element.nextSibling; // Wrap the element (is automatically removed from its current\n // parent).\n\n child.appendChild(element); // If the element had a sibling, insert the wrapper before\n // the sibling to maintain the HTML structure; otherwise, just\n // append it to the parent.\n\n if (sibling) {\n parent.insertBefore(child, sibling);\n } else {\n parent.appendChild(child);\n }\n });\n} // Set attributes\n\nfunction setAttributes(element, attributes) {\n if (!is.element(element) || is.empty(attributes)) {\n return;\n } // Assume null and undefined attributes should be left out,\n // Setting them would otherwise convert them to \"null\" and \"undefined\"\n\n\n Object.entries(attributes).filter(([, value]) => !is.nullOrUndefined(value)).forEach(([key, value]) => element.setAttribute(key, value));\n} // Create a DocumentFragment\n\nfunction createElement(type, attributes, text) {\n // Create a new <element>\n const element = document.createElement(type); // Set all passed attributes\n\n if (is.object(attributes)) {\n setAttributes(element, attributes);\n } // Add text node\n\n\n if (is.string(text)) {\n element.innerText = text;\n } // Return built element\n\n\n return element;\n} // Inaert an element after another\n\nfunction insertAfter(element, target) {\n if (!is.element(element) || !is.element(target)) {\n return;\n }\n\n target.parentNode.insertBefore(element, target.nextSibling);\n} // Insert a DocumentFragment\n\nfunction insertElement(type, parent, attributes, text) {\n if (!is.element(parent)) {\n return;\n }\n\n parent.appendChild(createElement(type, attributes, text));\n} // Remove element(s)\n\nfunction removeElement(element) {\n if (is.nodeList(element) || is.array(element)) {\n Array.from(element).forEach(removeElement);\n return;\n }\n\n if (!is.element(element) || !is.element(element.parentNode)) {\n return;\n }\n\n element.parentNode.removeChild(element);\n} // Remove all child elements\n\nfunction emptyElement(element) {\n if (!is.element(element)) {\n return;\n }\n\n let {\n length\n } = element.childNodes;\n\n while (length > 0) {\n element.removeChild(element.lastChild);\n length -= 1;\n }\n} // Replace element\n\nfunction replaceElement(newChild, oldChild) {\n if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) {\n return null;\n }\n\n oldChild.parentNode.replaceChild(newChild, oldChild);\n return newChild;\n} // Get an attribute object from a string selector\n\nfunction getAttributesFromSelector(sel, existingAttributes) {\n // For example:\n // '.test' to { class: 'test' }\n // '#test' to { id: 'test' }\n // '[data-test=\"test\"]' to { 'data-test': 'test' }\n if (!is.string(sel) || is.empty(sel)) {\n return {};\n }\n\n const attributes = {};\n const existing = extend({}, existingAttributes);\n sel.split(',').forEach(s => {\n // Remove whitespace\n const selector = s.trim();\n const className = selector.replace('.', '');\n const stripped = selector.replace(/[[\\]]/g, ''); // Get the parts and value\n\n const parts = stripped.split('=');\n const [key] = parts;\n const value = parts.length > 1 ? parts[1].replace(/[\"']/g, '') : ''; // Get the first character\n\n const start = selector.charAt(0);\n\n switch (start) {\n case '.':\n // Add to existing classname\n if (is.string(existing.class)) {\n attributes.class = `${existing.class} ${className}`;\n } else {\n attributes.class = className;\n }\n\n break;\n\n case '#':\n // ID selector\n attributes.id = selector.replace('#', '');\n break;\n\n case '[':\n // Attribute selector\n attributes[key] = value;\n break;\n }\n });\n return extend(existing, attributes);\n} // Toggle hidden\n\nfunction toggleHidden(element, hidden) {\n if (!is.element(element)) {\n return;\n }\n\n let hide = hidden;\n\n if (!is.boolean(hide)) {\n hide = !element.hidden;\n } // eslint-disable-next-line no-param-reassign\n\n\n element.hidden = hide;\n} // Mirror Element.classList.toggle, with IE compatibility for \"force\" argument\n\nfunction toggleClass(element, className, force) {\n if (is.nodeList(element)) {\n return Array.from(element).map(e => toggleClass(e, className, force));\n }\n\n if (is.element(element)) {\n let method = 'toggle';\n\n if (typeof force !== 'undefined') {\n method = force ? 'add' : 'remove';\n }\n\n element.classList[method](className);\n return element.classList.contains(className);\n }\n\n return false;\n} // Has class name\n\nfunction hasClass(element, className) {\n return is.element(element) && element.classList.contains(className);\n} // Element matches selector\n\nfunction matches(element, selector) {\n const {\n prototype\n } = Element;\n\n function match() {\n return Array.from(document.querySelectorAll(selector)).includes(this);\n }\n\n const method = prototype.matches || prototype.webkitMatchesSelector || prototype.mozMatchesSelector || prototype.msMatchesSelector || match;\n return method.call(element, selector);\n} // Closest ancestor element matching selector (also tests element itself)\n\nfunction closest$1(element, selector) {\n const {\n prototype\n } = Element; // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill\n\n function closestElement() {\n let el = this;\n\n do {\n if (matches.matches(el, selector)) return el;\n el = el.parentElement || el.parentNode;\n } while (el !== null && el.nodeType === 1);\n\n return null;\n }\n\n const method = prototype.closest || closestElement;\n return method.call(element, selector);\n} // Find all elements\n\nfunction getElements(selector) {\n return this.elements.container.querySelectorAll(selector);\n} // Find a single element\n\nfunction getElement(selector) {\n return this.elements.container.querySelector(selector);\n} // Set focus and tab focus class\n\nfunction setFocus(element = null, tabFocus = false) {\n if (!is.element(element)) {\n return;\n } // Set regular focus\n\n\n element.focus({\n preventScroll: true\n }); // If we want to mimic keyboard focus via tab\n\n if (tabFocus) {\n toggleClass(element, this.config.classNames.tabFocus);\n }\n}\n\n// ==========================================================================\n\nconst defaultCodecs = {\n 'audio/ogg': 'vorbis',\n 'audio/wav': '1',\n 'video/webm': 'vp8, vorbis',\n 'video/mp4': 'avc1.42E01E, mp4a.40.2',\n 'video/ogg': 'theora'\n}; // Check for feature support\n\nconst support = {\n // Basic support\n audio: 'canPlayType' in document.createElement('audio'),\n video: 'canPlayType' in document.createElement('video'),\n\n // Check for support\n // Basic functionality vs full UI\n check(type, provider, playsinline) {\n const canPlayInline = browser.isIPhone && playsinline && support.playsinline;\n const api = support[type] || provider !== 'html5';\n const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline);\n return {\n api,\n ui\n };\n },\n\n // Picture-in-picture support\n // Safari & Chrome only currently\n pip: (() => {\n if (browser.isIPhone) {\n return false;\n } // Safari\n // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls\n\n\n if (is.function(createElement('video').webkitSetPresentationMode)) {\n return true;\n } // Chrome\n // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture\n\n\n if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) {\n return true;\n }\n\n return false;\n })(),\n // Airplay support\n // Safari only currently\n airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent),\n // Inline playback support\n // https://webkit.org/blog/6784/new-video-policies-for-ios/\n playsinline: 'playsInline' in document.createElement('video'),\n\n // Check for mime type support against a player instance\n // Credits: http://diveintohtml5.info/everything.html\n // Related: http://www.leanbackplayer.com/test/h5mt.html\n mime(input) {\n if (is.empty(input)) {\n return false;\n }\n\n const [mediaType] = input.split('/');\n let type = input; // Verify we're using HTML5 and there's no media type mismatch\n\n if (!this.isHTML5 || mediaType !== this.type) {\n return false;\n } // Add codec if required\n\n\n if (Object.keys(defaultCodecs).includes(type)) {\n type += `; codecs=\"${defaultCodecs[input]}\"`;\n }\n\n try {\n return Boolean(type && this.media.canPlayType(type).replace(/no/, ''));\n } catch (_) {\n return false;\n }\n },\n\n // Check for textTracks support\n textTracks: 'textTracks' in document.createElement('video'),\n // <input type=\"range\"> Sliders\n rangeInput: (() => {\n const range = document.createElement('input');\n range.type = 'range';\n return range.type === 'range';\n })(),\n // Touch\n // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event\n touch: 'ontouchstart' in document.documentElement,\n // Detect transitions support\n transitions: transitionEndEvent !== false,\n // Reduced motion iOS & MacOS setting\n // https://webkit.org/blog/7551/responsive-design-for-motion/\n reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches\n};\n\n// ==========================================================================\n// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md\n// https://www.youtube.com/watch?v=NPM6172J22g\n\nconst supportsPassiveListeners = (() => {\n // Test via a getter in the options object to see if the passive property is accessed\n let supported = false;\n\n try {\n const options = Object.defineProperty({}, 'passive', {\n get() {\n supported = true;\n return null;\n }\n\n });\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n } catch (_) {// Do nothing\n }\n\n return supported;\n})(); // Toggle event listener\n\n\nfunction toggleListener(element, event, callback, toggle = false, passive = true, capture = false) {\n // Bail if no element, event, or callback\n if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) {\n return;\n } // Allow multiple events\n\n\n const events = event.split(' '); // Build options\n // Default to just the capture boolean for browsers with no passive listener support\n\n let options = capture; // If passive events listeners are supported\n\n if (supportsPassiveListeners) {\n options = {\n // Whether the listener can be passive (i.e. default never prevented)\n passive,\n // Whether the listener is a capturing listener or not\n capture\n };\n } // If a single node is passed, bind the event listener\n\n\n events.forEach(type => {\n if (this && this.eventListeners && toggle) {\n // Cache event listener\n this.eventListeners.push({\n element,\n type,\n callback,\n options\n });\n }\n\n element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options);\n });\n} // Bind event handler\n\nfunction on(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, true, passive, capture);\n} // Unbind event handler\n\nfunction off(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, false, passive, capture);\n} // Bind once-only event handler\n\nfunction once(element, events = '', callback, passive = true, capture = false) {\n const onceCallback = (...args) => {\n off(element, events, onceCallback, passive, capture);\n callback.apply(this, args);\n };\n\n toggleListener.call(this, element, events, onceCallback, true, passive, capture);\n} // Trigger event\n\nfunction triggerEvent(element, type = '', bubbles = false, detail = {}) {\n // Bail if no element\n if (!is.element(element) || is.empty(type)) {\n return;\n } // Create and dispatch the event\n\n\n const event = new CustomEvent(type, {\n bubbles,\n detail: { ...detail,\n plyr: this\n }\n }); // Dispatch the event\n\n element.dispatchEvent(event);\n} // Unbind all cached event listeners\n\nfunction unbindListeners() {\n if (this && this.eventListeners) {\n this.eventListeners.forEach(item => {\n const {\n element,\n type,\n callback,\n options\n } = item;\n element.removeEventListener(type, callback, options);\n });\n this.eventListeners = [];\n }\n} // Run method when / if player is ready\n\nfunction ready() {\n return new Promise(resolve => this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve)).then(() => {});\n}\n\n/**\n * Silence a Promise-like object.\n * This is useful for avoiding non-harmful, but potentially confusing \"uncaught\n * play promise\" rejection error messages.\n * @param {Object} value An object that may or may not be `Promise`-like.\n */\n\nfunction silencePromise(value) {\n if (is.promise(value)) {\n value.then(null, () => {});\n }\n}\n\n// ==========================================================================\n\nfunction dedupe(array) {\n if (!is.array(array)) {\n return array;\n }\n\n return array.filter((item, index) => array.indexOf(item) === index);\n} // Get the closest value in an array\n\nfunction closest(array, value) {\n if (!is.array(array) || !array.length) {\n return null;\n }\n\n return array.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev);\n}\n\n// ==========================================================================\n\nfunction supportsCSS(declaration) {\n if (!window || !window.CSS) {\n return false;\n }\n\n return window.CSS.supports(declaration);\n} // Standard/common aspect ratios\n\nconst standardRatios = [[1, 1], [4, 3], [3, 4], [5, 4], [4, 5], [3, 2], [2, 3], [16, 10], [10, 16], [16, 9], [9, 16], [21, 9], [9, 21], [32, 9], [9, 32]].reduce((out, [x, y]) => ({ ...out,\n [x / y]: [x, y]\n}), {}); // Validate an aspect ratio\n\nfunction validateAspectRatio(input) {\n if (!is.array(input) && (!is.string(input) || !input.includes(':'))) {\n return false;\n }\n\n const ratio = is.array(input) ? input : input.split(':');\n return ratio.map(Number).every(is.number);\n} // Reduce an aspect ratio to it's lowest form\n\nfunction reduceAspectRatio(ratio) {\n if (!is.array(ratio) || !ratio.every(is.number)) {\n return null;\n }\n\n const [width, height] = ratio;\n\n const getDivider = (w, h) => h === 0 ? w : getDivider(h, w % h);\n\n const divider = getDivider(width, height);\n return [width / divider, height / divider];\n} // Calculate an aspect ratio\n\nfunction getAspectRatio(input) {\n const parse = ratio => validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null; // Try provided ratio\n\n\n let ratio = parse(input); // Get from config\n\n if (ratio === null) {\n ratio = parse(this.config.ratio);\n } // Get from embed\n\n\n if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) {\n ({\n ratio\n } = this.embed);\n } // Get from HTML5 video\n\n\n if (ratio === null && this.isHTML5) {\n const {\n videoWidth,\n videoHeight\n } = this.media;\n ratio = [videoWidth, videoHeight];\n }\n\n return reduceAspectRatio(ratio);\n} // Set aspect ratio for responsive container\n\nfunction setAspectRatio(input) {\n if (!this.isVideo) {\n return {};\n }\n\n const {\n wrapper\n } = this.elements;\n const ratio = getAspectRatio.call(this, input);\n\n if (!is.array(ratio)) {\n return {};\n }\n\n const [x, y] = reduceAspectRatio(ratio);\n const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`);\n const padding = 100 / x * y;\n\n if (useNative) {\n wrapper.style.aspectRatio = `${x}/${y}`;\n } else {\n wrapper.style.paddingBottom = `${padding}%`;\n } // For Vimeo we have an extra <div> to hide the standard controls and UI\n\n\n if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) {\n const height = 100 / this.media.offsetWidth * parseInt(window.getComputedStyle(this.media).paddingBottom, 10);\n const offset = (height - padding) / (height / 50);\n\n if (this.fullscreen.active) {\n wrapper.style.paddingBottom = null;\n } else {\n this.media.style.transform = `translateY(-${offset}%)`;\n }\n } else if (this.isHTML5) {\n wrapper.classList.add(this.config.classNames.videoFixedRatio);\n }\n\n return {\n padding,\n ratio\n };\n} // Round an aspect ratio to closest standard ratio\n\nfunction roundAspectRatio(x, y, tolerance = 0.05) {\n const ratio = x / y;\n const closestRatio = closest(Object.keys(standardRatios), ratio); // Check match is within tolerance\n\n if (Math.abs(closestRatio - ratio) <= tolerance) {\n return standardRatios[closestRatio];\n } // No match\n\n\n return [x, y];\n} // Get the size of the viewport\n// https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions\n\nfunction getViewportSize() {\n const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);\n const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);\n return [width, height];\n}\n\n// ==========================================================================\nconst html5 = {\n getSources() {\n if (!this.isHTML5) {\n return [];\n }\n\n const sources = Array.from(this.media.querySelectorAll('source')); // Filter out unsupported sources (if type is specified)\n\n return sources.filter(source => {\n const type = source.getAttribute('type');\n\n if (is.empty(type)) {\n return true;\n }\n\n return support.mime.call(this, type);\n });\n },\n\n // Get quality levels\n getQualityOptions() {\n // Whether we're forcing all options (e.g. for streaming)\n if (this.config.quality.forced) {\n return this.config.quality.options;\n } // Get sizes from <source> elements\n\n\n return html5.getSources.call(this).map(source => Number(source.getAttribute('data-res'))).filter(Boolean);\n },\n\n setup() {\n if (!this.isHTML5) {\n return;\n }\n\n const player = this; // Set speed options from config\n\n player.options.speed = player.config.speed.options; // Set aspect ratio if fixed\n\n if (!is.empty(this.config.ratio)) {\n setAspectRatio.call(player);\n } // Quality\n\n\n Object.defineProperty(player.media, 'quality', {\n get() {\n // Get sources\n const sources = html5.getSources.call(player);\n const source = sources.find(s => s.getAttribute('src') === player.source); // Return size, if match is found\n\n return source && Number(source.getAttribute('data-res'));\n },\n\n set(input) {\n if (player.quality === input) {\n return;\n } // If we're using an external handler...\n\n\n if (player.config.quality.forced && is.function(player.config.quality.onChange)) {\n player.config.quality.onChange(input);\n } else {\n // Get sources\n const sources = html5.getSources.call(player); // Get first match for requested size\n\n const source = sources.find(s => Number(s.getAttribute('data-res')) === input); // No matching source found\n\n if (!source) {\n return;\n } // Get current state\n\n\n const {\n currentTime,\n paused,\n preload,\n readyState,\n playbackRate\n } = player.media; // Set new source\n\n player.media.src = source.getAttribute('src'); // Prevent loading if preload=\"none\" and the current source isn't loaded (#1044)\n\n if (preload !== 'none' || readyState) {\n // Restore time\n player.once('loadedmetadata', () => {\n player.speed = playbackRate;\n player.currentTime = currentTime; // Resume playing\n\n if (!paused) {\n silencePromise(player.play());\n }\n }); // Load new source\n\n player.media.load();\n }\n } // Trigger change event\n\n\n triggerEvent.call(player, player.media, 'qualitychange', false, {\n quality: input\n });\n }\n\n });\n },\n\n // Cancel current network requests\n // See https://github.com/sampotts/plyr/issues/174\n cancelRequests() {\n if (!this.isHTML5) {\n return;\n } // Remove child sources\n\n\n removeElement(html5.getSources.call(this)); // Set blank video src attribute\n // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error\n // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection\n\n this.media.setAttribute('src', this.config.blankVideo); // Load the new empty source\n // This will cancel existing requests\n // See https://github.com/sampotts/plyr/issues/174\n\n this.media.load(); // Debugging\n\n this.debug.log('Cancelled network requests');\n }\n\n};\n\n// ==========================================================================\n\nfunction generateId(prefix) {\n return `${prefix}-${Math.floor(Math.random() * 10000)}`;\n} // Format string\n\nfunction format(input, ...args) {\n if (is.empty(input)) {\n return input;\n }\n\n return input.toString().replace(/{(\\d+)}/g, (match, i) => args[i].toString());\n} // Get percentage\n\nfunction getPercentage(current, max) {\n if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) {\n return 0;\n }\n\n return (current / max * 100).toFixed(2);\n} // Replace all occurances of a string in a string\n\nconst replaceAll = (input = '', find = '', replace = '') => input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\\]/\\\\])/g, '\\\\$1'), 'g'), replace.toString()); // Convert to title case\n\nconst toTitleCase = (input = '') => input.toString().replace(/\\w\\S*/g, text => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()); // Convert string to pascalCase\n\nfunction toPascalCase(input = '') {\n let string = input.toString(); // Convert kebab case\n\n string = replaceAll(string, '-', ' '); // Convert snake case\n\n string = replaceAll(string, '_', ' '); // Convert to title case\n\n string = toTitleCase(string); // Convert to pascal case\n\n return replaceAll(string, ' ', '');\n} // Convert string to pascalCase\n\nfunction toCamelCase(input = '') {\n let string = input.toString(); // Convert to pascal case\n\n string = toPascalCase(string); // Convert first character to lowercase\n\n return string.charAt(0).toLowerCase() + string.slice(1);\n} // Remove HTML from a string\n\nfunction stripHTML(source) {\n const fragment = document.createDocumentFragment();\n const element = document.createElement('div');\n fragment.appendChild(element);\n element.innerHTML = source;\n return fragment.firstChild.innerText;\n} // Like outerHTML, but also works for DocumentFragment\n\nfunction getHTML(element) {\n const wrapper = document.createElement('div');\n wrapper.appendChild(element);\n return wrapper.innerHTML;\n}\n\n// ==========================================================================\n\nconst resources = {\n pip: 'PIP',\n airplay: 'AirPlay',\n html5: 'HTML5',\n vimeo: 'Vimeo',\n youtube: 'YouTube'\n};\nconst i18n = {\n get(key = '', config = {}) {\n if (is.empty(key) || is.empty(config)) {\n return '';\n }\n\n let string = getDeep(config.i18n, key);\n\n if (is.empty(string)) {\n if (Object.keys(resources).includes(key)) {\n return resources[key];\n }\n\n return '';\n }\n\n const replace = {\n '{seektime}': config.seekTime,\n '{title}': config.title\n };\n Object.entries(replace).forEach(([k, v]) => {\n string = replaceAll(string, k, v);\n });\n return string;\n }\n\n};\n\nclass Storage {\n constructor(player) {\n _defineProperty$1(this, \"get\", key => {\n if (!Storage.supported || !this.enabled) {\n return null;\n }\n\n const store = window.localStorage.getItem(this.key);\n\n if (is.empty(store)) {\n return null;\n }\n\n const json = JSON.parse(store);\n return is.string(key) && key.length ? json[key] : json;\n });\n\n _defineProperty$1(this, \"set\", object => {\n // Bail if we don't have localStorage support or it's disabled\n if (!Storage.supported || !this.enabled) {\n return;\n } // Can only store objectst\n\n\n if (!is.object(object)) {\n return;\n } // Get current storage\n\n\n let storage = this.get(); // Default to empty object\n\n if (is.empty(storage)) {\n storage = {};\n } // Update the working copy of the values\n\n\n extend(storage, object); // Update storage\n\n try {\n window.localStorage.setItem(this.key, JSON.stringify(storage));\n } catch (_) {// Do nothing\n }\n });\n\n this.enabled = player.config.storage.enabled;\n this.key = player.config.storage.key;\n } // Check for actual support (see if we can use it)\n\n\n static get supported() {\n try {\n if (!('localStorage' in window)) {\n return false;\n }\n\n const test = '___test'; // Try to use it (it might be disabled, e.g. user is in private mode)\n // see: https://github.com/sampotts/plyr/issues/131\n\n window.localStorage.setItem(test, test);\n window.localStorage.removeItem(test);\n return true;\n } catch (_) {\n return false;\n }\n }\n\n}\n\n// ==========================================================================\n// Fetch wrapper\n// Using XHR to avoid issues with older browsers\n// ==========================================================================\nfunction fetch(url, responseType = 'text') {\n return new Promise((resolve, reject) => {\n try {\n const request = new XMLHttpRequest(); // Check for CORS support\n\n if (!('withCredentials' in request)) {\n return;\n }\n\n request.addEventListener('load', () => {\n if (responseType === 'text') {\n try {\n resolve(JSON.parse(request.responseText));\n } catch (_) {\n resolve(request.responseText);\n }\n } else {\n resolve(request.response);\n }\n });\n request.addEventListener('error', () => {\n throw new Error(request.status);\n });\n request.open('GET', url, true); // Set the required response type\n\n request.responseType = responseType;\n request.send();\n } catch (error) {\n reject(error);\n }\n });\n}\n\n// ==========================================================================\n\nfunction loadSprite(url, id) {\n if (!is.string(url)) {\n return;\n }\n\n const prefix = 'cache';\n const hasId = is.string(id);\n let isCached = false;\n\n const exists = () => document.getElementById(id) !== null;\n\n const update = (container, data) => {\n // eslint-disable-next-line no-param-reassign\n container.innerHTML = data; // Check again incase of race condition\n\n if (hasId && exists()) {\n return;\n } // Inject the SVG to the body\n\n\n document.body.insertAdjacentElement('afterbegin', container);\n }; // Only load once if ID set\n\n\n if (!hasId || !exists()) {\n const useStorage = Storage.supported; // Create container\n\n const container = document.createElement('div');\n container.setAttribute('hidden', '');\n\n if (hasId) {\n container.setAttribute('id', id);\n } // Check in cache\n\n\n if (useStorage) {\n const cached = window.localStorage.getItem(`${prefix}-${id}`);\n isCached = cached !== null;\n\n if (isCached) {\n const data = JSON.parse(cached);\n update(container, data.content);\n }\n } // Get the sprite\n\n\n fetch(url).then(result => {\n if (is.empty(result)) {\n return;\n }\n\n if (useStorage) {\n try {\n window.localStorage.setItem(`${prefix}-${id}`, JSON.stringify({\n content: result\n }));\n } catch (_) {// Do nothing\n }\n }\n\n update(container, result);\n }).catch(() => {});\n }\n}\n\n// ==========================================================================\n\nconst getHours = value => Math.trunc(value / 60 / 60 % 60, 10);\nconst getMinutes = value => Math.trunc(value / 60 % 60, 10);\nconst getSeconds = value => Math.trunc(value % 60, 10); // Format time to UI friendly string\n\nfunction formatTime(time = 0, displayHours = false, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return formatTime(undefined, displayHours, inverted);\n } // Format time component to add leading zero\n\n\n const format = value => `0${value}`.slice(-2); // Breakdown to hours, mins, secs\n\n\n let hours = getHours(time);\n const mins = getMinutes(time);\n const secs = getSeconds(time); // Do we need to display hours?\n\n if (displayHours || hours > 0) {\n hours = `${hours}:`;\n } else {\n hours = '';\n } // Render\n\n\n return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`;\n}\n\n// ==========================================================================\n\nconst controls = {\n // Get icon URL\n getIconUrl() {\n const url = new URL(this.config.iconUrl, window.location);\n const host = window.location.host ? window.location.host : window.top.location.host;\n const cors = url.host !== host || browser.isIE && !window.svg4everybody;\n return {\n url: this.config.iconUrl,\n cors\n };\n },\n\n // Find the UI controls\n findElements() {\n try {\n this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper); // Buttons\n\n this.elements.buttons = {\n play: getElements.call(this, this.config.selectors.buttons.play),\n pause: getElement.call(this, this.config.selectors.buttons.pause),\n restart: getElement.call(this, this.config.selectors.buttons.restart),\n rewind: getElement.call(this, this.config.selectors.buttons.rewind),\n fastForward: getElement.call(this, this.config.selectors.buttons.fastForward),\n mute: getElement.call(this, this.config.selectors.buttons.mute),\n pip: getElement.call(this, this.config.selectors.buttons.pip),\n airplay: getElement.call(this, this.config.selectors.buttons.airplay),\n settings: getElement.call(this, this.config.selectors.buttons.settings),\n captions: getElement.call(this, this.config.selectors.buttons.captions),\n fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen)\n }; // Progress\n\n this.elements.progress = getElement.call(this, this.config.selectors.progress); // Inputs\n\n this.elements.inputs = {\n seek: getElement.call(this, this.config.selectors.inputs.seek),\n volume: getElement.call(this, this.config.selectors.inputs.volume)\n }; // Display\n\n this.elements.display = {\n buffer: getElement.call(this, this.config.selectors.display.buffer),\n currentTime: getElement.call(this, this.config.selectors.display.currentTime),\n duration: getElement.call(this, this.config.selectors.display.duration)\n }; // Seek tooltip\n\n if (is.element(this.elements.progress)) {\n this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`);\n }\n\n return true;\n } catch (error) {\n // Log it\n this.debug.warn('It looks like there is a problem with your custom controls HTML', error); // Restore native video controls\n\n this.toggleNativeControls(true);\n return false;\n }\n },\n\n // Create <svg> icon\n createIcon(type, attributes) {\n const namespace = 'http://www.w3.org/2000/svg';\n const iconUrl = controls.getIconUrl.call(this);\n const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`; // Create <svg>\n\n const icon = document.createElementNS(namespace, 'svg');\n setAttributes(icon, extend(attributes, {\n 'aria-hidden': 'true',\n focusable: 'false'\n })); // Create the <use> to reference sprite\n\n const use = document.createElementNS(namespace, 'use');\n const path = `${iconPath}-${type}`; // Set `href` attributes\n // https://github.com/sampotts/plyr/issues/460\n // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href\n\n if ('href' in use) {\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path);\n } // Always set the older attribute even though it's \"deprecated\" (it'll be around for ages)\n\n\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path); // Add <use> to <svg>\n\n icon.appendChild(use);\n return icon;\n },\n\n // Create hidden text label\n createLabel(key, attr = {}) {\n const text = i18n.get(key, this.config);\n const attributes = { ...attr,\n class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ')\n };\n return createElement('span', attributes, text);\n },\n\n // Create a badge\n createBadge(text) {\n if (is.empty(text)) {\n return null;\n }\n\n const badge = createElement('span', {\n class: this.config.classNames.menu.value\n });\n badge.appendChild(createElement('span', {\n class: this.config.classNames.menu.badge\n }, text));\n return badge;\n },\n\n // Create a <button>\n createButton(buttonType, attr) {\n const attributes = extend({}, attr);\n let type = toCamelCase(buttonType);\n const props = {\n element: 'button',\n toggle: false,\n label: null,\n icon: null,\n labelPressed: null,\n iconPressed: null\n };\n ['element', 'icon', 'label'].forEach(key => {\n if (Object.keys(attributes).includes(key)) {\n props[key] = attributes[key];\n delete attributes[key];\n }\n }); // Default to 'button' type to prevent form submission\n\n if (props.element === 'button' && !Object.keys(attributes).includes('type')) {\n attributes.type = 'button';\n } // Set class name\n\n\n if (Object.keys(attributes).includes('class')) {\n if (!attributes.class.split(' ').some(c => c === this.config.classNames.control)) {\n extend(attributes, {\n class: `${attributes.class} ${this.config.classNames.control}`\n });\n }\n } else {\n attributes.class = this.config.classNames.control;\n } // Large play button\n\n\n switch (buttonType) {\n case 'play':\n props.toggle = true;\n props.label = 'play';\n props.labelPressed = 'pause';\n props.icon = 'play';\n props.iconPressed = 'pause';\n break;\n\n case 'mute':\n props.toggle = true;\n props.label = 'mute';\n props.labelPressed = 'unmute';\n props.icon = 'volume';\n props.iconPressed = 'muted';\n break;\n\n case 'captions':\n props.toggle = true;\n props.label = 'enableCaptions';\n props.labelPressed = 'disableCaptions';\n props.icon = 'captions-off';\n props.iconPressed = 'captions-on';\n break;\n\n case 'fullscreen':\n props.toggle = true;\n props.label = 'enterFullscreen';\n props.labelPressed = 'exitFullscreen';\n props.icon = 'enter-fullscreen';\n props.iconPressed = 'exit-fullscreen';\n break;\n\n case 'play-large':\n attributes.class += ` ${this.config.classNames.control}--overlaid`;\n type = 'play';\n props.label = 'play';\n props.icon = 'play';\n break;\n\n default:\n if (is.empty(props.label)) {\n props.label = type;\n }\n\n if (is.empty(props.icon)) {\n props.icon = buttonType;\n }\n\n }\n\n const button = createElement(props.element); // Setup toggle icon and labels\n\n if (props.toggle) {\n // Icon\n button.appendChild(controls.createIcon.call(this, props.iconPressed, {\n class: 'icon--pressed'\n }));\n button.appendChild(controls.createIcon.call(this, props.icon, {\n class: 'icon--not-pressed'\n })); // Label/Tooltip\n\n button.appendChild(controls.createLabel.call(this, props.labelPressed, {\n class: 'label--pressed'\n }));\n button.appendChild(controls.createLabel.call(this, props.label, {\n class: 'label--not-pressed'\n }));\n } else {\n button.appendChild(controls.createIcon.call(this, props.icon));\n button.appendChild(controls.createLabel.call(this, props.label));\n } // Merge and set attributes\n\n\n extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes));\n setAttributes(button, attributes); // We have multiple play buttons\n\n if (type === 'play') {\n if (!is.array(this.elements.buttons[type])) {\n this.elements.buttons[type] = [];\n }\n\n this.elements.buttons[type].push(button);\n } else {\n this.elements.buttons[type] = button;\n }\n\n return button;\n },\n\n // Create an <input type='range'>\n createRange(type, attributes) {\n // Seek input\n const input = createElement('input', extend(getAttributesFromSelector(this.config.selectors.inputs[type]), {\n type: 'range',\n min: 0,\n max: 100,\n step: 0.01,\n value: 0,\n autocomplete: 'off',\n // A11y fixes for https://github.com/sampotts/plyr/issues/905\n role: 'slider',\n 'aria-label': i18n.get(type, this.config),\n 'aria-valuemin': 0,\n 'aria-valuemax': 100,\n 'aria-valuenow': 0\n }, attributes));\n this.elements.inputs[type] = input; // Set the fill for webkit now\n\n controls.updateRangeFill.call(this, input); // Improve support on touch devices\n\n RangeTouch.setup(input);\n return input;\n },\n\n // Create a <progress>\n createProgress(type, attributes) {\n const progress = createElement('progress', extend(getAttributesFromSelector(this.config.selectors.display[type]), {\n min: 0,\n max: 100,\n value: 0,\n role: 'progressbar',\n 'aria-hidden': true\n }, attributes)); // Create the label inside\n\n if (type !== 'volume') {\n progress.appendChild(createElement('span', null, '0'));\n const suffixKey = {\n played: 'played',\n buffer: 'buffered'\n }[type];\n const suffix = suffixKey ? i18n.get(suffixKey, this.config) : '';\n progress.innerText = `% ${suffix.toLowerCase()}`;\n }\n\n this.elements.display[type] = progress;\n return progress;\n },\n\n // Create time display\n createTime(type, attrs) {\n const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs);\n const container = createElement('div', extend(attributes, {\n class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(),\n 'aria-label': i18n.get(type, this.config)\n }), '00:00'); // Reference for updates\n\n this.elements.display[type] = container;\n return container;\n },\n\n // Bind keyboard shortcuts for a menu item\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n bindMenuItemShortcuts(menuItem, type) {\n // Navigate through menus via arrow keys and space\n on.call(this, menuItem, 'keydown keyup', event => {\n // We only care about space and ⬆️ ⬇️️ ➡️\n if (![32, 38, 39, 40].includes(event.which)) {\n return;\n } // Prevent play / seek\n\n\n event.preventDefault();\n event.stopPropagation(); // We're just here to prevent the keydown bubbling\n\n if (event.type === 'keydown') {\n return;\n }\n\n const isRadioButton = matches(menuItem, '[role=\"menuitemradio\"]'); // Show the respective menu\n\n if (!isRadioButton && [32, 39].includes(event.which)) {\n controls.showMenuPanel.call(this, type, true);\n } else {\n let target;\n\n if (event.which !== 32) {\n if (event.which === 40 || isRadioButton && event.which === 39) {\n target = menuItem.nextElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.firstElementChild;\n }\n } else {\n target = menuItem.previousElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.lastElementChild;\n }\n }\n\n setFocus.call(this, target, true);\n }\n }\n }, false); // Enter will fire a `click` event but we still need to manage focus\n // So we bind to keyup which fires after and set focus here\n\n on.call(this, menuItem, 'keyup', event => {\n if (event.which !== 13) {\n return;\n }\n\n controls.focusFirstMenuItem.call(this, null, true);\n });\n },\n\n // Create a settings menu item\n createMenuItem({\n value,\n list,\n type,\n title,\n badge = null,\n checked = false\n }) {\n const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]);\n const menuItem = createElement('button', extend(attributes, {\n type: 'button',\n role: 'menuitemradio',\n class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(),\n 'aria-checked': checked,\n value\n }));\n const flex = createElement('span'); // We have to set as HTML incase of special characters\n\n flex.innerHTML = title;\n\n if (is.element(badge)) {\n flex.appendChild(badge);\n }\n\n menuItem.appendChild(flex); // Replicate radio button behaviour\n\n Object.defineProperty(menuItem, 'checked', {\n enumerable: true,\n\n get() {\n return menuItem.getAttribute('aria-checked') === 'true';\n },\n\n set(check) {\n // Ensure exclusivity\n if (check) {\n Array.from(menuItem.parentNode.children).filter(node => matches(node, '[role=\"menuitemradio\"]')).forEach(node => node.setAttribute('aria-checked', 'false'));\n }\n\n menuItem.setAttribute('aria-checked', check ? 'true' : 'false');\n }\n\n });\n this.listeners.bind(menuItem, 'click keyup', event => {\n if (is.keyboardEvent(event) && event.which !== 32) {\n return;\n }\n\n event.preventDefault();\n event.stopPropagation();\n menuItem.checked = true;\n\n switch (type) {\n case 'language':\n this.currentTrack = Number(value);\n break;\n\n case 'quality':\n this.quality = value;\n break;\n\n case 'speed':\n this.speed = parseFloat(value);\n break;\n }\n\n controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event));\n }, type, false);\n controls.bindMenuItemShortcuts.call(this, menuItem, type);\n list.appendChild(menuItem);\n },\n\n // Format a time for display\n formatTime(time = 0, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return time;\n } // Always display hours if duration is over an hour\n\n\n const forceHours = getHours(this.duration) > 0;\n return formatTime(time, forceHours, inverted);\n },\n\n // Update the displayed time\n updateTimeDisplay(target = null, time = 0, inverted = false) {\n // Bail if there's no element to display or the value isn't a number\n if (!is.element(target) || !is.number(time)) {\n return;\n } // eslint-disable-next-line no-param-reassign\n\n\n target.innerText = controls.formatTime(time, inverted);\n },\n\n // Update volume UI and storage\n updateVolume() {\n if (!this.supported.ui) {\n return;\n } // Update range\n\n\n if (is.element(this.elements.inputs.volume)) {\n controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);\n } // Update mute state\n\n\n if (is.element(this.elements.buttons.mute)) {\n this.elements.buttons.mute.pressed = this.muted || this.volume === 0;\n }\n },\n\n // Update seek value and lower fill\n setRange(target, value = 0) {\n if (!is.element(target)) {\n return;\n } // eslint-disable-next-line\n\n\n target.value = value; // Webkit range fill\n\n controls.updateRangeFill.call(this, target);\n },\n\n // Update <progress> elements\n updateProgress(event) {\n if (!this.supported.ui || !is.event(event)) {\n return;\n }\n\n let value = 0;\n\n const setProgress = (target, input) => {\n const val = is.number(input) ? input : 0;\n const progress = is.element(target) ? target : this.elements.display.buffer; // Update value and label\n\n if (is.element(progress)) {\n progress.value = val; // Update text label inside\n\n const label = progress.getElementsByTagName('span')[0];\n\n if (is.element(label)) {\n label.childNodes[0].nodeValue = val;\n }\n }\n };\n\n if (event) {\n switch (event.type) {\n // Video playing\n case 'timeupdate':\n case 'seeking':\n case 'seeked':\n value = getPercentage(this.currentTime, this.duration); // Set seek range value only if it's a 'natural' time event\n\n if (event.type === 'timeupdate') {\n controls.setRange.call(this, this.elements.inputs.seek, value);\n }\n\n break;\n // Check buffer status\n\n case 'playing':\n case 'progress':\n setProgress(this.elements.display.buffer, this.buffered * 100);\n break;\n }\n }\n },\n\n // Webkit polyfill for lower fill range\n updateRangeFill(target) {\n // Get range from event if event passed\n const range = is.event(target) ? target.target : target; // Needs to be a valid <input type='range'>\n\n if (!is.element(range) || range.getAttribute('type') !== 'range') {\n return;\n } // Set aria values for https://github.com/sampotts/plyr/issues/905\n\n\n if (matches(range, this.config.selectors.inputs.seek)) {\n range.setAttribute('aria-valuenow', this.currentTime);\n const currentTime = controls.formatTime(this.currentTime);\n const duration = controls.formatTime(this.duration);\n const format = i18n.get('seekLabel', this.config);\n range.setAttribute('aria-valuetext', format.replace('{currentTime}', currentTime).replace('{duration}', duration));\n } else if (matches(range, this.config.selectors.inputs.volume)) {\n const percent = range.value * 100;\n range.setAttribute('aria-valuenow', percent);\n range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`);\n } else {\n range.setAttribute('aria-valuenow', range.value);\n } // WebKit only\n\n\n if (!browser.isWebkit) {\n return;\n } // Set CSS custom property\n\n\n range.style.setProperty('--value', `${range.value / range.max * 100}%`);\n },\n\n // Update hover tooltip for seeking\n updateSeekTooltip(event) {\n // Bail if setting not true\n if (!this.config.tooltips.seek || !is.element(this.elements.inputs.seek) || !is.element(this.elements.display.seekTooltip) || this.duration === 0) {\n return;\n }\n\n const visible = `${this.config.classNames.tooltip}--visible`;\n\n const toggle = show => toggleClass(this.elements.display.seekTooltip, visible, show); // Hide on touch\n\n\n if (this.touch) {\n toggle(false);\n return;\n } // Determine percentage, if already visible\n\n\n let percent = 0;\n const clientRect = this.elements.progress.getBoundingClientRect();\n\n if (is.event(event)) {\n percent = 100 / clientRect.width * (event.pageX - clientRect.left);\n } else if (hasClass(this.elements.display.seekTooltip, visible)) {\n percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);\n } else {\n return;\n } // Set bounds\n\n\n if (percent < 0) {\n percent = 0;\n } else if (percent > 100) {\n percent = 100;\n } // Display the time a click would seek to\n\n\n controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent); // Set position\n\n this.elements.display.seekTooltip.style.left = `${percent}%`; // Show/hide the tooltip\n // If the event is a moues in/out and percentage is inside bounds\n\n if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) {\n toggle(event.type === 'mouseenter');\n }\n },\n\n // Handle time change event\n timeUpdate(event) {\n // Only invert if only one time element is displayed and used for both duration and currentTime\n const invert = !is.element(this.elements.display.duration) && this.config.invertTime; // Duration\n\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, invert ? this.duration - this.currentTime : this.currentTime, invert); // Ignore updates while seeking\n\n if (event && event.type === 'timeupdate' && this.media.seeking) {\n return;\n } // Playing progress\n\n\n controls.updateProgress.call(this, event);\n },\n\n // Show the duration on metadataloaded or durationchange events\n durationUpdate() {\n // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false\n if (!this.supported.ui || !this.config.invertTime && this.currentTime) {\n return;\n } // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar.\n // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415\n // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062\n // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338\n\n\n if (this.duration >= 2 ** 32) {\n toggleHidden(this.elements.display.currentTime, true);\n toggleHidden(this.elements.progress, true);\n return;\n } // Update ARIA values\n\n\n if (is.element(this.elements.inputs.seek)) {\n this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration);\n } // If there's a spot to display duration\n\n\n const hasDuration = is.element(this.elements.display.duration); // If there's only one time display, display duration there\n\n if (!hasDuration && this.config.displayDuration && this.paused) {\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);\n } // If there's a duration element, update content\n\n\n if (hasDuration) {\n controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);\n } // Update the tooltip (if visible)\n\n\n controls.updateSeekTooltip.call(this);\n },\n\n // Hide/show a tab\n toggleMenuButton(setting, toggle) {\n toggleHidden(this.elements.settings.buttons[setting], !toggle);\n },\n\n // Update the selected setting\n updateSetting(setting, container, input) {\n const pane = this.elements.settings.panels[setting];\n let value = null;\n let list = container;\n\n if (setting === 'captions') {\n value = this.currentTrack;\n } else {\n value = !is.empty(input) ? input : this[setting]; // Get default\n\n if (is.empty(value)) {\n value = this.config[setting].default;\n } // Unsupported value\n\n\n if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) {\n this.debug.warn(`Unsupported value of '${value}' for ${setting}`);\n return;\n } // Disabled value\n\n\n if (!this.config[setting].options.includes(value)) {\n this.debug.warn(`Disabled value of '${value}' for ${setting}`);\n return;\n }\n } // Get the list if we need to\n\n\n if (!is.element(list)) {\n list = pane && pane.querySelector('[role=\"menu\"]');\n } // If there's no list it means it's not been rendered...\n\n\n if (!is.element(list)) {\n return;\n } // Update the label\n\n\n const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`);\n label.innerHTML = controls.getLabel.call(this, setting, value); // Find the radio option and check it\n\n const target = list && list.querySelector(`[value=\"${value}\"]`);\n\n if (is.element(target)) {\n target.checked = true;\n }\n },\n\n // Translate a value into a nice label\n getLabel(setting, value) {\n switch (setting) {\n case 'speed':\n return value === 1 ? i18n.get('normal', this.config) : `${value}×`;\n\n case 'quality':\n if (is.number(value)) {\n const label = i18n.get(`qualityLabel.${value}`, this.config);\n\n if (!label.length) {\n return `${value}p`;\n }\n\n return label;\n }\n\n return toTitleCase(value);\n\n case 'captions':\n return captions.getLabel.call(this);\n\n default:\n return null;\n }\n },\n\n // Set the quality menu\n setQualityMenu(options) {\n // Menu required\n if (!is.element(this.elements.settings.panels.quality)) {\n return;\n }\n\n const type = 'quality';\n const list = this.elements.settings.panels.quality.querySelector('[role=\"menu\"]'); // Set options if passed and filter based on uniqueness and config\n\n if (is.array(options)) {\n this.options.quality = dedupe(options).filter(quality => this.config.quality.options.includes(quality));\n } // Toggle the pane and tab\n\n\n const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1;\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If we're hiding, nothing more to do\n\n if (!toggle) {\n return;\n } // Get the badge HTML for HD, 4K etc\n\n\n const getBadge = quality => {\n const label = i18n.get(`qualityBadge.${quality}`, this.config);\n\n if (!label.length) {\n return null;\n }\n\n return controls.createBadge.call(this, label);\n }; // Sort options by the config and then render options\n\n\n this.options.quality.sort((a, b) => {\n const sorting = this.config.quality.options;\n return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1;\n }).forEach(quality => {\n controls.createMenuItem.call(this, {\n value: quality,\n list,\n type,\n title: controls.getLabel.call(this, 'quality', quality),\n badge: getBadge(quality)\n });\n });\n controls.updateSetting.call(this, type, list);\n },\n\n // Set the looping options\n\n /* setLoopMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.loop)) {\n return;\n }\n const options = ['start', 'end', 'all', 'reset'];\n const list = this.elements.settings.panels.loop.querySelector('[role=\"menu\"]');\n // Show the pane and tab\n toggleHidden(this.elements.settings.buttons.loop, false);\n toggleHidden(this.elements.settings.panels.loop, false);\n // Toggle the pane and tab\n const toggle = !is.empty(this.loop.options);\n controls.toggleMenuButton.call(this, 'loop', toggle);\n // Empty the menu\n emptyElement(list);\n options.forEach(option => {\n const item = createElement('li');\n const button = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.loop), {\n type: 'button',\n class: this.config.classNames.control,\n 'data-plyr-loop-action': option,\n }),\n i18n.get(option, this.config)\n );\n if (['start', 'end'].includes(option)) {\n const badge = controls.createBadge.call(this, '00:00');\n button.appendChild(badge);\n }\n item.appendChild(button);\n list.appendChild(item);\n });\n }, */\n // Get current selected caption language\n // TODO: rework this to user the getter in the API?\n // Set a list of available captions languages\n setCaptionsMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.captions)) {\n return;\n } // TODO: Captions or language? Currently it's mixed\n\n\n const type = 'captions';\n const list = this.elements.settings.panels.captions.querySelector('[role=\"menu\"]');\n const tracks = captions.getTracks.call(this);\n const toggle = Boolean(tracks.length); // Toggle the pane and tab\n\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If there's no captions, bail\n\n if (!toggle) {\n return;\n } // Generate options data\n\n\n const options = tracks.map((track, value) => ({\n value,\n checked: this.captions.toggled && this.currentTrack === value,\n title: captions.getLabel.call(this, track),\n badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()),\n list,\n type: 'language'\n })); // Add the \"Disabled\" option to turn off captions\n\n options.unshift({\n value: -1,\n checked: !this.captions.toggled,\n title: i18n.get('disabled', this.config),\n list,\n type: 'language'\n }); // Generate options\n\n options.forEach(controls.createMenuItem.bind(this));\n controls.updateSetting.call(this, type, list);\n },\n\n // Set a list of available captions languages\n setSpeedMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.speed)) {\n return;\n }\n\n const type = 'speed';\n const list = this.elements.settings.panels.speed.querySelector('[role=\"menu\"]'); // Filter out invalid speeds\n\n this.options.speed = this.options.speed.filter(o => o >= this.minimumSpeed && o <= this.maximumSpeed); // Toggle the pane and tab\n\n const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1;\n controls.toggleMenuButton.call(this, type, toggle); // Empty the menu\n\n emptyElement(list); // Check if we need to toggle the parent\n\n controls.checkMenu.call(this); // If we're hiding, nothing more to do\n\n if (!toggle) {\n return;\n } // Create items\n\n\n this.options.speed.forEach(speed => {\n controls.createMenuItem.call(this, {\n value: speed,\n list,\n type,\n title: controls.getLabel.call(this, 'speed', speed)\n });\n });\n controls.updateSetting.call(this, type, list);\n },\n\n // Check if we need to hide/show the settings menu\n checkMenu() {\n const {\n buttons\n } = this.elements.settings;\n const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden);\n toggleHidden(this.elements.settings.menu, !visible);\n },\n\n // Focus the first menu item in a given (or visible) menu\n focusFirstMenuItem(pane, tabFocus = false) {\n if (this.elements.settings.popup.hidden) {\n return;\n }\n\n let target = pane;\n\n if (!is.element(target)) {\n target = Object.values(this.elements.settings.panels).find(p => !p.hidden);\n }\n\n const firstItem = target.querySelector('[role^=\"menuitem\"]');\n setFocus.call(this, firstItem, tabFocus);\n },\n\n // Show/hide menu\n toggleMenu(input) {\n const {\n popup\n } = this.elements.settings;\n const button = this.elements.buttons.settings; // Menu and button are required\n\n if (!is.element(popup) || !is.element(button)) {\n return;\n } // True toggle by default\n\n\n const {\n hidden\n } = popup;\n let show = hidden;\n\n if (is.boolean(input)) {\n show = input;\n } else if (is.keyboardEvent(input) && input.which === 27) {\n show = false;\n } else if (is.event(input)) {\n // If Plyr is in a shadowDOM, the event target is set to the component, instead of the\n // Element in the shadowDOM. The path, if available, is complete.\n const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target;\n const isMenuItem = popup.contains(target); // If the click was inside the menu or if the click\n // wasn't the button or menu item and we're trying to\n // show the menu (a doc click shouldn't show the menu)\n\n if (isMenuItem || !isMenuItem && input.target !== button && show) {\n return;\n }\n } // Set button attributes\n\n\n button.setAttribute('aria-expanded', show); // Show the actual popup\n\n toggleHidden(popup, !show); // Add class hook\n\n toggleClass(this.elements.container, this.config.classNames.menu.open, show); // Focus the first item if key interaction\n\n if (show && is.keyboardEvent(input)) {\n controls.focusFirstMenuItem.call(this, null, true);\n } else if (!show && !hidden) {\n // If closing, re-focus the button\n setFocus.call(this, button, is.keyboardEvent(input));\n }\n },\n\n // Get the natural size of a menu panel\n getMenuSize(tab) {\n const clone = tab.cloneNode(true);\n clone.style.position = 'absolute';\n clone.style.opacity = 0;\n clone.removeAttribute('hidden'); // Append to parent so we get the \"real\" size\n\n tab.parentNode.appendChild(clone); // Get the sizes before we remove\n\n const width = clone.scrollWidth;\n const height = clone.scrollHeight; // Remove from the DOM\n\n removeElement(clone);\n return {\n width,\n height\n };\n },\n\n // Show a panel in the menu\n showMenuPanel(type = '', tabFocus = false) {\n const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`); // Nothing to show, bail\n\n if (!is.element(target)) {\n return;\n } // Hide all other panels\n\n\n const container = target.parentNode;\n const current = Array.from(container.children).find(node => !node.hidden); // If we can do fancy animations, we'll animate the height/width\n\n if (support.transitions && !support.reducedMotion) {\n // Set the current width as a base\n container.style.width = `${current.scrollWidth}px`;\n container.style.height = `${current.scrollHeight}px`; // Get potential sizes\n\n const size = controls.getMenuSize.call(this, target); // Restore auto height/width\n\n const restore = event => {\n // We're only bothered about height and width on the container\n if (event.target !== container || !['width', 'height'].includes(event.propertyName)) {\n return;\n } // Revert back to auto\n\n\n container.style.width = '';\n container.style.height = ''; // Only listen once\n\n off.call(this, container, transitionEndEvent, restore);\n }; // Listen for the transition finishing and restore auto height/width\n\n\n on.call(this, container, transitionEndEvent, restore); // Set dimensions to target\n\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n } // Set attributes on current tab\n\n\n toggleHidden(current, true); // Set attributes on target\n\n toggleHidden(target, false); // Focus the first item\n\n controls.focusFirstMenuItem.call(this, target, tabFocus);\n },\n\n // Set the download URL\n setDownloadUrl() {\n const button = this.elements.buttons.download; // Bail if no button\n\n if (!is.element(button)) {\n return;\n } // Set attribute\n\n\n button.setAttribute('href', this.download);\n },\n\n // Build the default HTML\n create(data) {\n const {\n bindMenuItemShortcuts,\n createButton,\n createProgress,\n createRange,\n createTime,\n setQualityMenu,\n setSpeedMenu,\n showMenuPanel\n } = controls;\n this.elements.controls = null; // Larger overlaid play button\n\n if (is.array(this.config.controls) && this.config.controls.includes('play-large')) {\n this.elements.container.appendChild(createButton.call(this, 'play-large'));\n } // Create the container\n\n\n const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper));\n this.elements.controls = container; // Default item attributes\n\n const defaultAttributes = {\n class: 'plyr__controls__item'\n }; // Loop through controls in order\n\n dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach(control => {\n // Restart button\n if (control === 'restart') {\n container.appendChild(createButton.call(this, 'restart', defaultAttributes));\n } // Rewind button\n\n\n if (control === 'rewind') {\n container.appendChild(createButton.call(this, 'rewind', defaultAttributes));\n } // Play/Pause button\n\n\n if (control === 'play') {\n container.appendChild(createButton.call(this, 'play', defaultAttributes));\n } // Fast forward button\n\n\n if (control === 'fast-forward') {\n container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes));\n } // Progress\n\n\n if (control === 'progress') {\n const progressContainer = createElement('div', {\n class: `${defaultAttributes.class} plyr__progress__container`\n });\n const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress)); // Seek range slider\n\n progress.appendChild(createRange.call(this, 'seek', {\n id: `plyr-seek-${data.id}`\n })); // Buffer progress\n\n progress.appendChild(createProgress.call(this, 'buffer')); // TODO: Add loop display indicator\n // Seek tooltip\n\n if (this.config.tooltips.seek) {\n const tooltip = createElement('span', {\n class: this.config.classNames.tooltip\n }, '00:00');\n progress.appendChild(tooltip);\n this.elements.display.seekTooltip = tooltip;\n }\n\n this.elements.progress = progress;\n progressContainer.appendChild(this.elements.progress);\n container.appendChild(progressContainer);\n } // Media current time display\n\n\n if (control === 'current-time') {\n container.appendChild(createTime.call(this, 'currentTime', defaultAttributes));\n } // Media duration display\n\n\n if (control === 'duration') {\n container.appendChild(createTime.call(this, 'duration', defaultAttributes));\n } // Volume controls\n\n\n if (control === 'mute' || control === 'volume') {\n let {\n volume\n } = this.elements; // Create the volume container if needed\n\n if (!is.element(volume) || !container.contains(volume)) {\n volume = createElement('div', extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__volume`.trim()\n }));\n this.elements.volume = volume;\n container.appendChild(volume);\n } // Toggle mute button\n\n\n if (control === 'mute') {\n volume.appendChild(createButton.call(this, 'mute'));\n } // Volume range control\n // Ignored on iOS as it's handled globally\n // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html\n\n\n if (control === 'volume' && !browser.isIos) {\n // Set the attributes\n const attributes = {\n max: 1,\n step: 0.05,\n value: this.config.volume\n }; // Create the volume range slider\n\n volume.appendChild(createRange.call(this, 'volume', extend(attributes, {\n id: `plyr-volume-${data.id}`\n })));\n }\n } // Toggle captions button\n\n\n if (control === 'captions') {\n container.appendChild(createButton.call(this, 'captions', defaultAttributes));\n } // Settings button / menu\n\n\n if (control === 'settings' && !is.empty(this.config.settings)) {\n const wrapper = createElement('div', extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__menu`.trim(),\n hidden: ''\n }));\n wrapper.appendChild(createButton.call(this, 'settings', {\n 'aria-haspopup': true,\n 'aria-controls': `plyr-settings-${data.id}`,\n 'aria-expanded': false\n }));\n const popup = createElement('div', {\n class: 'plyr__menu__container',\n id: `plyr-settings-${data.id}`,\n hidden: ''\n });\n const inner = createElement('div');\n const home = createElement('div', {\n id: `plyr-settings-${data.id}-home`\n }); // Create the menu\n\n const menu = createElement('div', {\n role: 'menu'\n });\n home.appendChild(menu);\n inner.appendChild(home);\n this.elements.settings.panels.home = home; // Build the menu items\n\n this.config.settings.forEach(type => {\n // TODO: bundle this with the createMenuItem helper and bindings\n const menuItem = createElement('button', extend(getAttributesFromSelector(this.config.selectors.buttons.settings), {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`,\n role: 'menuitem',\n 'aria-haspopup': true,\n hidden: ''\n })); // Bind menu shortcuts for keyboard users\n\n bindMenuItemShortcuts.call(this, menuItem, type); // Show menu on click\n\n on.call(this, menuItem, 'click', () => {\n showMenuPanel.call(this, type, false);\n });\n const flex = createElement('span', null, i18n.get(type, this.config));\n const value = createElement('span', {\n class: this.config.classNames.menu.value\n }); // Speed contains HTML entities\n\n value.innerHTML = data[type];\n flex.appendChild(value);\n menuItem.appendChild(flex);\n menu.appendChild(menuItem); // Build the panes\n\n const pane = createElement('div', {\n id: `plyr-settings-${data.id}-${type}`,\n hidden: ''\n }); // Back button\n\n const backButton = createElement('button', {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--back`\n }); // Visible label\n\n backButton.appendChild(createElement('span', {\n 'aria-hidden': true\n }, i18n.get(type, this.config))); // Screen reader label\n\n backButton.appendChild(createElement('span', {\n class: this.config.classNames.hidden\n }, i18n.get('menuBack', this.config))); // Go back via keyboard\n\n on.call(this, pane, 'keydown', event => {\n // We only care about <-\n if (event.which !== 37) {\n return;\n } // Prevent seek\n\n\n event.preventDefault();\n event.stopPropagation(); // Show the respective menu\n\n showMenuPanel.call(this, 'home', true);\n }, false); // Go back via button click\n\n on.call(this, backButton, 'click', () => {\n showMenuPanel.call(this, 'home', false);\n }); // Add to pane\n\n pane.appendChild(backButton); // Menu\n\n pane.appendChild(createElement('div', {\n role: 'menu'\n }));\n inner.appendChild(pane);\n this.elements.settings.buttons[type] = menuItem;\n this.elements.settings.panels[type] = pane;\n });\n popup.appendChild(inner);\n wrapper.appendChild(popup);\n container.appendChild(wrapper);\n this.elements.settings.popup = popup;\n this.elements.settings.menu = wrapper;\n } // Picture in picture button\n\n\n if (control === 'pip' && support.pip) {\n container.appendChild(createButton.call(this, 'pip', defaultAttributes));\n } // Airplay button\n\n\n if (control === 'airplay' && support.airplay) {\n container.appendChild(createButton.call(this, 'airplay', defaultAttributes));\n } // Download button\n\n\n if (control === 'download') {\n const attributes = extend({}, defaultAttributes, {\n element: 'a',\n href: this.download,\n target: '_blank'\n }); // Set download attribute for HTML5 only\n\n if (this.isHTML5) {\n attributes.download = '';\n }\n\n const {\n download\n } = this.config.urls;\n\n if (!is.url(download) && this.isEmbed) {\n extend(attributes, {\n icon: `logo-${this.provider}`,\n label: this.provider\n });\n }\n\n container.appendChild(createButton.call(this, 'download', attributes));\n } // Toggle fullscreen button\n\n\n if (control === 'fullscreen') {\n container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes));\n }\n }); // Set available quality levels\n\n if (this.isHTML5) {\n setQualityMenu.call(this, html5.getQualityOptions.call(this));\n }\n\n setSpeedMenu.call(this);\n return container;\n },\n\n // Insert controls\n inject() {\n // Sprite\n if (this.config.loadSprite) {\n const icon = controls.getIconUrl.call(this); // Only load external sprite using AJAX\n\n if (icon.cors) {\n loadSprite(icon.url, 'sprite-plyr');\n }\n } // Create a unique ID\n\n\n this.id = Math.floor(Math.random() * 10000); // Null by default\n\n let container = null;\n this.elements.controls = null; // Set template properties\n\n const props = {\n id: this.id,\n seektime: this.config.seekTime,\n title: this.config.title\n };\n let update = true; // If function, run it and use output\n\n if (is.function(this.config.controls)) {\n this.config.controls = this.config.controls.call(this, props);\n } // Convert falsy controls to empty array (primarily for empty strings)\n\n\n if (!this.config.controls) {\n this.config.controls = [];\n }\n\n if (is.element(this.config.controls) || is.string(this.config.controls)) {\n // HTMLElement or Non-empty string passed as the option\n container = this.config.controls;\n } else {\n // Create controls\n container = controls.create.call(this, {\n id: this.id,\n seektime: this.config.seekTime,\n speed: this.speed,\n quality: this.quality,\n captions: captions.getLabel.call(this) // TODO: Looping\n // loop: 'None',\n\n });\n update = false;\n } // Replace props with their value\n\n\n const replace = input => {\n let result = input;\n Object.entries(props).forEach(([key, value]) => {\n result = replaceAll(result, `{${key}}`, value);\n });\n return result;\n }; // Update markup\n\n\n if (update) {\n if (is.string(this.config.controls)) {\n container = replace(container);\n }\n } // Controls container\n\n\n let target; // Inject to custom location\n\n if (is.string(this.config.selectors.controls.container)) {\n target = document.querySelector(this.config.selectors.controls.container);\n } // Inject into the container by default\n\n\n if (!is.element(target)) {\n target = this.elements.container;\n } // Inject controls HTML (needs to be before captions, hence \"afterbegin\")\n\n\n const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML';\n target[insertMethod]('afterbegin', container); // Find the elements if need be\n\n if (!is.element(this.elements.controls)) {\n controls.findElements.call(this);\n } // Add pressed property to buttons\n\n\n if (!is.empty(this.elements.buttons)) {\n const addProperty = button => {\n const className = this.config.classNames.controlPressed;\n Object.defineProperty(button, 'pressed', {\n enumerable: true,\n\n get() {\n return hasClass(button, className);\n },\n\n set(pressed = false) {\n toggleClass(button, className, pressed);\n }\n\n });\n }; // Toggle classname when pressed property is set\n\n\n Object.values(this.elements.buttons).filter(Boolean).forEach(button => {\n if (is.array(button) || is.nodeList(button)) {\n Array.from(button).filter(Boolean).forEach(addProperty);\n } else {\n addProperty(button);\n }\n });\n } // Edge sometimes doesn't finish the paint so force a repaint\n\n\n if (browser.isEdge) {\n repaint(target);\n } // Setup tooltips\n\n\n if (this.config.tooltips.controls) {\n const {\n classNames,\n selectors\n } = this.config;\n const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`;\n const labels = getElements.call(this, selector);\n Array.from(labels).forEach(label => {\n toggleClass(label, this.config.classNames.hidden, false);\n toggleClass(label, this.config.classNames.tooltip, true);\n });\n }\n }\n\n};\n\n// ==========================================================================\n/**\n * Parse a string to a URL object\n * @param {String} input - the URL to be parsed\n * @param {Boolean} safe - failsafe parsing\n */\n\nfunction parseUrl(input, safe = true) {\n let url = input;\n\n if (safe) {\n const parser = document.createElement('a');\n parser.href = url;\n url = parser.href;\n }\n\n try {\n return new URL(url);\n } catch (_) {\n return null;\n }\n} // Convert object to URLSearchParams\n\nfunction buildUrlParams(input) {\n const params = new URLSearchParams();\n\n if (is.object(input)) {\n Object.entries(input).forEach(([key, value]) => {\n params.set(key, value);\n });\n }\n\n return params;\n}\n\n// ==========================================================================\nconst captions = {\n // Setup captions\n setup() {\n // Requires UI support\n if (!this.supported.ui) {\n return;\n } // Only Vimeo and HTML5 video supported at this point\n\n\n if (!this.isVideo || this.isYouTube || this.isHTML5 && !support.textTracks) {\n // Clear menu and hide\n if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) {\n controls.setCaptionsMenu.call(this);\n }\n\n return;\n } // Inject the container\n\n\n if (!is.element(this.elements.captions)) {\n this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions));\n insertAfter(this.elements.captions, this.elements.wrapper);\n } // Fix IE captions if CORS is used\n // Fetch captions and inject as blobs instead (data URIs not supported!)\n\n\n if (browser.isIE && window.URL) {\n const elements = this.media.querySelectorAll('track');\n Array.from(elements).forEach(track => {\n const src = track.getAttribute('src');\n const url = parseUrl(src);\n\n if (url !== null && url.hostname !== window.location.href.hostname && ['http:', 'https:'].includes(url.protocol)) {\n fetch(src, 'blob').then(blob => {\n track.setAttribute('src', window.URL.createObjectURL(blob));\n }).catch(() => {\n removeElement(track);\n });\n }\n });\n } // Get and set initial data\n // The \"preferred\" options are not realized unless / until the wanted language has a match\n // * languages: Array of user's browser languages.\n // * language: The language preferred by user settings or config\n // * active: The state preferred by user settings or config\n // * toggled: The real captions state\n\n\n const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en'];\n const languages = dedupe(browserLanguages.map(language => language.split('-')[0]));\n let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase(); // Use first browser language when language is 'auto'\n\n if (language === 'auto') {\n [language] = languages;\n }\n\n let active = this.storage.get('captions');\n\n if (!is.boolean(active)) {\n ({\n active\n } = this.config.captions);\n }\n\n Object.assign(this.captions, {\n toggled: false,\n active,\n language,\n languages\n }); // Watch changes to textTracks and update captions menu\n\n if (this.isHTML5) {\n const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack';\n on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this));\n } // Update available languages in list next tick (the event must not be triggered before the listeners)\n\n\n setTimeout(captions.update.bind(this), 0);\n },\n\n // Update available language options in settings based on tracks\n update() {\n const tracks = captions.getTracks.call(this, true); // Get the wanted language\n\n const {\n active,\n language,\n meta,\n currentTrackNode\n } = this.captions;\n const languageExists = Boolean(tracks.find(track => track.language === language)); // Handle tracks (add event listener and \"pseudo\"-default)\n\n if (this.isHTML5 && this.isVideo) {\n tracks.filter(track => !meta.get(track)).forEach(track => {\n this.debug.log('Track added', track); // Attempt to store if the original dom element was \"default\"\n\n meta.set(track, {\n default: track.mode === 'showing'\n }); // Turn off native caption rendering to avoid double captions\n // Note: mode='hidden' forces a track to download. To ensure every track\n // isn't downloaded at once, only 'showing' tracks should be reassigned\n // eslint-disable-next-line no-param-reassign\n\n if (track.mode === 'showing') {\n // eslint-disable-next-line no-param-reassign\n track.mode = 'hidden';\n } // Add event listener for cue changes\n\n\n on.call(this, track, 'cuechange', () => captions.updateCues.call(this));\n });\n } // Update language first time it matches, or if the previous matching track was removed\n\n\n if (languageExists && this.language !== language || !tracks.includes(currentTrackNode)) {\n captions.setLanguage.call(this, language);\n captions.toggle.call(this, active && languageExists);\n } // Enable or disable captions based on track length\n\n\n if (this.elements) {\n toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks));\n } // Update available languages in list\n\n\n if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) {\n controls.setCaptionsMenu.call(this);\n }\n },\n\n // Toggle captions display\n // Used internally for the toggleCaptions method, with the passive option forced to false\n toggle(input, passive = true) {\n // If there's no full support\n if (!this.supported.ui) {\n return;\n }\n\n const {\n toggled\n } = this.captions; // Current state\n\n const activeClass = this.config.classNames.captions.active; // Get the next state\n // If the method is called without parameter, toggle based on current value\n\n const active = is.nullOrUndefined(input) ? !toggled : input; // Update state and trigger event\n\n if (active !== toggled) {\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.active = active;\n this.storage.set({\n captions: active\n });\n } // Force language if the call isn't passive and there is no matching language to toggle to\n\n\n if (!this.language && active && !passive) {\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true); // Override user preferences to avoid switching languages if a matching track is added\n\n this.captions.language = track.language; // Set caption, but don't store in localStorage as user preference\n\n captions.set.call(this, tracks.indexOf(track));\n return;\n } // Toggle button if it's enabled\n\n\n if (this.elements.buttons.captions) {\n this.elements.buttons.captions.pressed = active;\n } // Add class hook\n\n\n toggleClass(this.elements.container, activeClass, active);\n this.captions.toggled = active; // Update settings menu\n\n controls.updateSetting.call(this, 'captions'); // Trigger event (not used internally)\n\n triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled');\n } // Wait for the call stack to clear before setting mode='hidden'\n // on the active track - forcing the browser to download it\n\n\n setTimeout(() => {\n if (active && this.captions.toggled) {\n this.captions.currentTrackNode.mode = 'hidden';\n }\n });\n },\n\n // Set captions by track index\n // Used internally for the currentTrack setter with the passive option forced to false\n set(index, passive = true) {\n const tracks = captions.getTracks.call(this); // Disable captions if setting to -1\n\n if (index === -1) {\n captions.toggle.call(this, false, passive);\n return;\n }\n\n if (!is.number(index)) {\n this.debug.warn('Invalid caption argument', index);\n return;\n }\n\n if (!(index in tracks)) {\n this.debug.warn('Track not found', index);\n return;\n }\n\n if (this.captions.currentTrack !== index) {\n this.captions.currentTrack = index;\n const track = tracks[index];\n const {\n language\n } = track || {}; // Store reference to node for invalidation on remove\n\n this.captions.currentTrackNode = track; // Update settings menu\n\n controls.updateSetting.call(this, 'captions'); // When passive, don't override user preferences\n\n if (!passive) {\n this.captions.language = language;\n this.storage.set({\n language\n });\n } // Handle Vimeo captions\n\n\n if (this.isVimeo) {\n this.embed.enableTextTrack(language);\n } // Trigger event\n\n\n triggerEvent.call(this, this.media, 'languagechange');\n } // Show captions\n\n\n captions.toggle.call(this, true, passive);\n\n if (this.isHTML5 && this.isVideo) {\n // If we change the active track while a cue is already displayed we need to update it\n captions.updateCues.call(this);\n }\n },\n\n // Set captions by language\n // Used internally for the language setter with the passive option forced to false\n setLanguage(input, passive = true) {\n if (!is.string(input)) {\n this.debug.warn('Invalid language argument', input);\n return;\n } // Normalize\n\n\n const language = input.toLowerCase();\n this.captions.language = language; // Set currentTrack\n\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [language]);\n captions.set.call(this, tracks.indexOf(track), passive);\n },\n\n // Get current valid caption tracks\n // If update is false it will also ignore tracks without metadata\n // This is used to \"freeze\" the language options when captions.update is false\n getTracks(update = false) {\n // Handle media or textTracks missing or null\n const tracks = Array.from((this.media || {}).textTracks || []); // For HTML5, use cache instead of current tracks when it exists (if captions.update is false)\n // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata)\n\n return tracks.filter(track => !this.isHTML5 || update || this.captions.meta.has(track)).filter(track => ['captions', 'subtitles'].includes(track.kind));\n },\n\n // Match tracks based on languages and get the first\n findTrack(languages, force = false) {\n const tracks = captions.getTracks.call(this);\n\n const sortIsDefault = track => Number((this.captions.meta.get(track) || {}).default);\n\n const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a));\n let track;\n languages.every(language => {\n track = sorted.find(t => t.language === language);\n return !track; // Break iteration if there is a match\n }); // If no match is found but is required, get first\n\n return track || (force ? sorted[0] : undefined);\n },\n\n // Get the current track\n getCurrentTrack() {\n return captions.getTracks.call(this)[this.currentTrack];\n },\n\n // Get UI label for track\n getLabel(track) {\n let currentTrack = track;\n\n if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) {\n currentTrack = captions.getCurrentTrack.call(this);\n }\n\n if (is.track(currentTrack)) {\n if (!is.empty(currentTrack.label)) {\n return currentTrack.label;\n }\n\n if (!is.empty(currentTrack.language)) {\n return track.language.toUpperCase();\n }\n\n return i18n.get('enabled', this.config);\n }\n\n return i18n.get('disabled', this.config);\n },\n\n // Update captions using current track's active cues\n // Also optional array argument in case there isn't any track (ex: vimeo)\n updateCues(input) {\n // Requires UI\n if (!this.supported.ui) {\n return;\n }\n\n if (!is.element(this.elements.captions)) {\n this.debug.warn('No captions element to render to');\n return;\n } // Only accept array or empty input\n\n\n if (!is.nullOrUndefined(input) && !Array.isArray(input)) {\n this.debug.warn('updateCues: Invalid input', input);\n return;\n }\n\n let cues = input; // Get cues from track\n\n if (!cues) {\n const track = captions.getCurrentTrack.call(this);\n cues = Array.from((track || {}).activeCues || []).map(cue => cue.getCueAsHTML()).map(getHTML);\n } // Set new caption text\n\n\n const content = cues.map(cueText => cueText.trim()).join('\\n');\n const changed = content !== this.elements.captions.innerHTML;\n\n if (changed) {\n // Empty the container and create a new child element\n emptyElement(this.elements.captions);\n const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption));\n caption.innerHTML = content;\n this.elements.captions.appendChild(caption); // Trigger event\n\n triggerEvent.call(this, this.media, 'cuechange');\n }\n }\n\n};\n\n// ==========================================================================\n// Plyr default config\n// ==========================================================================\nconst defaults = {\n // Disable\n enabled: true,\n // Custom media title\n title: '',\n // Logging to console\n debug: false,\n // Auto play (if supported)\n autoplay: false,\n // Only allow one media playing at once (vimeo only)\n autopause: true,\n // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present)\n // TODO: Remove iosNative fullscreen option in favour of this (logic needs work)\n playsinline: true,\n // Default time to skip when rewind/fast forward\n seekTime: 10,\n // Default volume\n volume: 1,\n muted: false,\n // Pass a custom duration\n duration: null,\n // Display the media duration on load in the current time position\n // If you have opted to display both duration and currentTime, this is ignored\n displayDuration: true,\n // Invert the current time to be a countdown\n invertTime: true,\n // Clicking the currentTime inverts it's value to show time left rather than elapsed\n toggleInvert: true,\n // Force an aspect ratio\n // The format must be `'w:h'` (e.g. `'16:9'`)\n ratio: null,\n // Click video container to play/pause\n clickToPlay: true,\n // Auto hide the controls\n hideControls: true,\n // Reset to start when playback ended\n resetOnEnd: false,\n // Disable the standard context menu\n disableContextMenu: true,\n // Sprite (for icons)\n loadSprite: true,\n iconPrefix: 'plyr',\n iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg',\n // Blank video (used to prevent errors on source change)\n blankVideo: 'https://cdn.plyr.io/static/blank.mp4',\n // Quality default\n quality: {\n default: 576,\n // The options to display in the UI, if available for the source media\n options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240],\n forced: false,\n onChange: null\n },\n // Set loops\n loop: {\n active: false // start: null,\n // end: null,\n\n },\n // Speed default and options to display\n speed: {\n selected: 1,\n // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x)\n options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4]\n },\n // Keyboard shortcut settings\n keyboard: {\n focused: true,\n global: false\n },\n // Display tooltips\n tooltips: {\n controls: false,\n seek: true\n },\n // Captions settings\n captions: {\n active: false,\n language: 'auto',\n // Listen to new tracks added after Plyr is initialized.\n // This is needed for streaming captions, but may result in unselectable options\n update: false\n },\n // Fullscreen settings\n fullscreen: {\n enabled: true,\n // Allow fullscreen?\n fallback: true,\n // Fallback using full viewport/window\n iosNative: false // Use the native fullscreen in iOS (disables custom controls)\n // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode\n // Non-ancestors of the player element will be ignored\n // container: null, // defaults to the player element\n\n },\n // Local storage\n storage: {\n enabled: true,\n key: 'plyr'\n },\n // Default controls\n controls: ['play-large', // 'restart',\n // 'rewind',\n 'play', // 'fast-forward',\n 'progress', 'current-time', // 'duration',\n 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', // 'download',\n 'fullscreen'],\n settings: ['captions', 'quality', 'speed'],\n // Localisation\n i18n: {\n restart: 'Restart',\n rewind: 'Rewind {seektime}s',\n play: 'Play',\n pause: 'Pause',\n fastForward: 'Forward {seektime}s',\n seek: 'Seek',\n seekLabel: '{currentTime} of {duration}',\n played: 'Played',\n buffered: 'Buffered',\n currentTime: 'Current time',\n duration: 'Duration',\n volume: 'Volume',\n mute: 'Mute',\n unmute: 'Unmute',\n enableCaptions: 'Enable captions',\n disableCaptions: 'Disable captions',\n download: 'Download',\n enterFullscreen: 'Enter fullscreen',\n exitFullscreen: 'Exit fullscreen',\n frameTitle: 'Player for {title}',\n captions: 'Captions',\n settings: 'Settings',\n pip: 'PIP',\n menuBack: 'Go back to previous menu',\n speed: 'Speed',\n normal: 'Normal',\n quality: 'Quality',\n loop: 'Loop',\n start: 'Start',\n end: 'End',\n all: 'All',\n reset: 'Reset',\n disabled: 'Disabled',\n enabled: 'Enabled',\n advertisement: 'Ad',\n qualityBadge: {\n 2160: '4K',\n 1440: 'HD',\n 1080: 'HD',\n 720: 'HD',\n 576: 'SD',\n 480: 'SD'\n }\n },\n // URLs\n urls: {\n download: null,\n vimeo: {\n sdk: 'https://player.vimeo.com/api/player.js',\n iframe: 'https://player.vimeo.com/video/{0}?{1}',\n api: 'https://vimeo.com/api/oembed.json?url={0}'\n },\n youtube: {\n sdk: 'https://www.youtube.com/iframe_api',\n api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}'\n },\n googleIMA: {\n sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js'\n }\n },\n // Custom control listeners\n listeners: {\n seek: null,\n play: null,\n pause: null,\n restart: null,\n rewind: null,\n fastForward: null,\n mute: null,\n volume: null,\n captions: null,\n download: null,\n fullscreen: null,\n pip: null,\n airplay: null,\n speed: null,\n quality: null,\n loop: null,\n language: null\n },\n // Events to watch and bubble\n events: [// Events to watch on HTML5 media elements and bubble\n // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events\n 'ended', 'progress', 'stalled', 'playing', 'waiting', 'canplay', 'canplaythrough', 'loadstart', 'loadeddata', 'loadedmetadata', 'timeupdate', 'volumechange', 'play', 'pause', 'error', 'seeking', 'seeked', 'emptied', 'ratechange', 'cuechange', // Custom events\n 'download', 'enterfullscreen', 'exitfullscreen', 'captionsenabled', 'captionsdisabled', 'languagechange', 'controlshidden', 'controlsshown', 'ready', // YouTube\n 'statechange', // Quality\n 'qualitychange', // Ads\n 'adsloaded', 'adscontentpause', 'adscontentresume', 'adstarted', 'adsmidpoint', 'adscomplete', 'adsallcomplete', 'adsimpression', 'adsclick'],\n // Selectors\n // Change these to match your template if using custom HTML\n selectors: {\n editable: 'input, textarea, select, [contenteditable]',\n container: '.plyr',\n controls: {\n container: null,\n wrapper: '.plyr__controls'\n },\n labels: '[data-plyr]',\n buttons: {\n play: '[data-plyr=\"play\"]',\n pause: '[data-plyr=\"pause\"]',\n restart: '[data-plyr=\"restart\"]',\n rewind: '[data-plyr=\"rewind\"]',\n fastForward: '[data-plyr=\"fast-forward\"]',\n mute: '[data-plyr=\"mute\"]',\n captions: '[data-plyr=\"captions\"]',\n download: '[data-plyr=\"download\"]',\n fullscreen: '[data-plyr=\"fullscreen\"]',\n pip: '[data-plyr=\"pip\"]',\n airplay: '[data-plyr=\"airplay\"]',\n settings: '[data-plyr=\"settings\"]',\n loop: '[data-plyr=\"loop\"]'\n },\n inputs: {\n seek: '[data-plyr=\"seek\"]',\n volume: '[data-plyr=\"volume\"]',\n speed: '[data-plyr=\"speed\"]',\n language: '[data-plyr=\"language\"]',\n quality: '[data-plyr=\"quality\"]'\n },\n display: {\n currentTime: '.plyr__time--current',\n duration: '.plyr__time--duration',\n buffer: '.plyr__progress__buffer',\n loop: '.plyr__progress__loop',\n // Used later\n volume: '.plyr__volume--display'\n },\n progress: '.plyr__progress',\n captions: '.plyr__captions',\n caption: '.plyr__caption'\n },\n // Class hooks added to the player in different states\n classNames: {\n type: 'plyr--{0}',\n provider: 'plyr--{0}',\n video: 'plyr__video-wrapper',\n embed: 'plyr__video-embed',\n videoFixedRatio: 'plyr__video-wrapper--fixed-ratio',\n embedContainer: 'plyr__video-embed__container',\n poster: 'plyr__poster',\n posterEnabled: 'plyr__poster-enabled',\n ads: 'plyr__ads',\n control: 'plyr__control',\n controlPressed: 'plyr__control--pressed',\n playing: 'plyr--playing',\n paused: 'plyr--paused',\n stopped: 'plyr--stopped',\n loading: 'plyr--loading',\n hover: 'plyr--hover',\n tooltip: 'plyr__tooltip',\n cues: 'plyr__cues',\n hidden: 'plyr__sr-only',\n hideControls: 'plyr--hide-controls',\n isIos: 'plyr--is-ios',\n isTouch: 'plyr--is-touch',\n uiSupported: 'plyr--full-ui',\n noTransition: 'plyr--no-transition',\n display: {\n time: 'plyr__time'\n },\n menu: {\n value: 'plyr__menu__value',\n badge: 'plyr__badge',\n open: 'plyr--menu-open'\n },\n captions: {\n enabled: 'plyr--captions-enabled',\n active: 'plyr--captions-active'\n },\n fullscreen: {\n enabled: 'plyr--fullscreen-enabled',\n fallback: 'plyr--fullscreen-fallback'\n },\n pip: {\n supported: 'plyr--pip-supported',\n active: 'plyr--pip-active'\n },\n airplay: {\n supported: 'plyr--airplay-supported',\n active: 'plyr--airplay-active'\n },\n tabFocus: 'plyr__tab-focus',\n previewThumbnails: {\n // Tooltip thumbs\n thumbContainer: 'plyr__preview-thumb',\n thumbContainerShown: 'plyr__preview-thumb--is-shown',\n imageContainer: 'plyr__preview-thumb__image-container',\n timeContainer: 'plyr__preview-thumb__time-container',\n // Scrubbing\n scrubbingContainer: 'plyr__preview-scrubbing',\n scrubbingContainerShown: 'plyr__preview-scrubbing--is-shown'\n }\n },\n // Embed attributes\n attributes: {\n embed: {\n provider: 'data-plyr-provider',\n id: 'data-plyr-embed-id',\n hash: 'data-plyr-embed-hash'\n }\n },\n // Advertisements plugin\n // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio\n ads: {\n enabled: false,\n publisherId: '',\n tagUrl: ''\n },\n // Preview Thumbnails plugin\n previewThumbnails: {\n enabled: false,\n src: ''\n },\n // Vimeo plugin\n vimeo: {\n byline: false,\n portrait: false,\n title: false,\n speed: true,\n transparent: false,\n // Custom settings from Plyr\n customControls: true,\n referrerPolicy: null,\n // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy\n // Whether the owner of the video has a Pro or Business account\n // (which allows us to properly hide controls without CSS hacks, etc)\n premium: false\n },\n // YouTube plugin\n youtube: {\n rel: 0,\n // No related vids\n showinfo: 0,\n // Hide info\n iv_load_policy: 3,\n // Hide annotations\n modestbranding: 1,\n // Hide logos as much as possible (they still show one in the corner when paused)\n // Custom settings from Plyr\n customControls: true,\n noCookie: false // Whether to use an alternative version of YouTube without cookies\n\n }\n};\n\n// ==========================================================================\n// Plyr states\n// ==========================================================================\nconst pip = {\n active: 'picture-in-picture',\n inactive: 'inline'\n};\n\n// ==========================================================================\n// Plyr supported types and providers\n// ==========================================================================\nconst providers = {\n html5: 'html5',\n youtube: 'youtube',\n vimeo: 'vimeo'\n};\nconst types = {\n audio: 'audio',\n video: 'video'\n};\n/**\n * Get provider by URL\n * @param {String} url\n */\n\nfunction getProviderByUrl(url) {\n // YouTube\n if (/^(https?:\\/\\/)?(www\\.)?(youtube\\.com|youtube-nocookie\\.com|youtu\\.?be)\\/.+$/.test(url)) {\n return providers.youtube;\n } // Vimeo\n\n\n if (/^https?:\\/\\/player.vimeo.com\\/video\\/\\d{0,9}(?=\\b|\\/)/.test(url)) {\n return providers.vimeo;\n }\n\n return null;\n}\n\n// ==========================================================================\n// Console wrapper\n// ==========================================================================\nconst noop = () => {};\n\nclass Console {\n constructor(enabled = false) {\n this.enabled = window.console && enabled;\n\n if (this.enabled) {\n this.log('Debugging enabled');\n }\n }\n\n get log() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.log, console) : noop;\n }\n\n get warn() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop;\n }\n\n get error() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.error, console) : noop;\n }\n\n}\n\nclass Fullscreen {\n constructor(player) {\n _defineProperty$1(this, \"onChange\", () => {\n if (!this.enabled) {\n return;\n } // Update toggle button\n\n\n const button = this.player.elements.buttons.fullscreen;\n\n if (is.element(button)) {\n button.pressed = this.active;\n } // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up\n\n\n const target = this.target === this.player.media ? this.target : this.player.elements.container; // Trigger an event\n\n triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true);\n });\n\n _defineProperty$1(this, \"toggleFallback\", (toggle = false) => {\n // Store or restore scroll position\n if (toggle) {\n this.scrollPosition = {\n x: window.scrollX || 0,\n y: window.scrollY || 0\n };\n } else {\n window.scrollTo(this.scrollPosition.x, this.scrollPosition.y);\n } // Toggle scroll\n\n\n document.body.style.overflow = toggle ? 'hidden' : ''; // Toggle class hook\n\n toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle); // Force full viewport on iPhone X+\n\n if (browser.isIos) {\n let viewport = document.head.querySelector('meta[name=\"viewport\"]');\n const property = 'viewport-fit=cover'; // Inject the viewport meta if required\n\n if (!viewport) {\n viewport = document.createElement('meta');\n viewport.setAttribute('name', 'viewport');\n } // Check if the property already exists\n\n\n const hasProperty = is.string(viewport.content) && viewport.content.includes(property);\n\n if (toggle) {\n this.cleanupViewport = !hasProperty;\n\n if (!hasProperty) {\n viewport.content += `,${property}`;\n }\n } else if (this.cleanupViewport) {\n viewport.content = viewport.content.split(',').filter(part => part.trim() !== property).join(',');\n }\n } // Toggle button and fire events\n\n\n this.onChange();\n });\n\n _defineProperty$1(this, \"trapFocus\", event => {\n // Bail if iOS, not active, not the tab key\n if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) {\n return;\n } // Get the current focused element\n\n\n const focused = document.activeElement;\n const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]');\n const [first] = focusable;\n const last = focusable[focusable.length - 1];\n\n if (focused === last && !event.shiftKey) {\n // Move focus to first element that can be tabbed if Shift isn't used\n first.focus();\n event.preventDefault();\n } else if (focused === first && event.shiftKey) {\n // Move focus to last element that can be tabbed if Shift is used\n last.focus();\n event.preventDefault();\n }\n });\n\n _defineProperty$1(this, \"update\", () => {\n if (this.enabled) {\n let mode;\n\n if (this.forceFallback) {\n mode = 'Fallback (forced)';\n } else if (Fullscreen.native) {\n mode = 'Native';\n } else {\n mode = 'Fallback';\n }\n\n this.player.debug.log(`${mode} fullscreen enabled`);\n } else {\n this.player.debug.log('Fullscreen not supported and fallback disabled');\n } // Add styling hook to show button\n\n\n toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled);\n });\n\n _defineProperty$1(this, \"enter\", () => {\n if (!this.enabled) {\n return;\n } // iOS native fullscreen doesn't need the request step\n\n\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n if (this.player.isVimeo) {\n this.player.embed.requestFullscreen();\n } else {\n this.target.webkitEnterFullscreen();\n }\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(true);\n } else if (!this.prefix) {\n this.target.requestFullscreen({\n navigationUI: 'hide'\n });\n } else if (!is.empty(this.prefix)) {\n this.target[`${this.prefix}Request${this.property}`]();\n }\n });\n\n _defineProperty$1(this, \"exit\", () => {\n if (!this.enabled) {\n return;\n } // iOS native fullscreen\n\n\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n this.target.webkitExitFullscreen();\n silencePromise(this.player.play());\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(false);\n } else if (!this.prefix) {\n (document.cancelFullScreen || document.exitFullscreen).call(document);\n } else if (!is.empty(this.prefix)) {\n const action = this.prefix === 'moz' ? 'Cancel' : 'Exit';\n document[`${this.prefix}${action}${this.property}`]();\n }\n });\n\n _defineProperty$1(this, \"toggle\", () => {\n if (!this.active) {\n this.enter();\n } else {\n this.exit();\n }\n });\n\n // Keep reference to parent\n this.player = player; // Get prefix\n\n this.prefix = Fullscreen.prefix;\n this.property = Fullscreen.property; // Scroll position\n\n this.scrollPosition = {\n x: 0,\n y: 0\n }; // Force the use of 'full window/browser' rather than fullscreen\n\n this.forceFallback = player.config.fullscreen.fallback === 'force'; // Get the fullscreen element\n // Checks container is an ancestor, defaults to null\n\n this.player.elements.fullscreen = player.config.fullscreen.container && closest$1(this.player.elements.container, player.config.fullscreen.container); // Register event listeners\n // Handle event (incase user presses escape etc)\n\n on.call(this.player, document, this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`, () => {\n // TODO: Filter for target??\n this.onChange();\n }); // Fullscreen toggle on double click\n\n on.call(this.player, this.player.elements.container, 'dblclick', event => {\n // Ignore double click in controls\n if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) {\n return;\n }\n\n this.player.listeners.proxy(event, this.toggle, 'fullscreen');\n }); // Tap focus when in fullscreen\n\n on.call(this, this.player.elements.container, 'keydown', event => this.trapFocus(event)); // Update the UI\n\n this.update(); // this.toggle = this.toggle.bind(this);\n } // Determine if native supported\n\n\n static get native() {\n return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled);\n } // If we're actually using native\n\n\n get usingNative() {\n return Fullscreen.native && !this.forceFallback;\n } // Get the prefix for handlers\n\n\n static get prefix() {\n // No prefix\n if (is.function(document.exitFullscreen)) {\n return '';\n } // Check for fullscreen support by vendor prefix\n\n\n let value = '';\n const prefixes = ['webkit', 'moz', 'ms'];\n prefixes.some(pre => {\n if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) {\n value = pre;\n return true;\n }\n\n return false;\n });\n return value;\n }\n\n static get property() {\n return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen';\n } // Determine if fullscreen is enabled\n\n\n get enabled() {\n return (Fullscreen.native || this.player.config.fullscreen.fallback) && this.player.config.fullscreen.enabled && this.player.supported.ui && this.player.isVideo;\n } // Get active state\n\n\n get active() {\n if (!this.enabled) {\n return false;\n } // Fallback using classname\n\n\n if (!Fullscreen.native || this.forceFallback) {\n return hasClass(this.target, this.player.config.classNames.fullscreen.fallback);\n }\n\n const element = !this.prefix ? this.target.getRootNode().fullscreenElement : this.target.getRootNode()[`${this.prefix}${this.property}Element`];\n return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target;\n } // Get target element\n\n\n get target() {\n return browser.isIos && this.player.config.fullscreen.iosNative ? this.player.media : this.player.elements.fullscreen || this.player.elements.container;\n }\n\n}\n\n// ==========================================================================\n// Load image avoiding xhr/fetch CORS issues\n// Server status can't be obtained this way unfortunately, so this uses \"naturalWidth\" to determine if the image has loaded\n// By default it checks if it is at least 1px, but you can add a second argument to change this\n// ==========================================================================\nfunction loadImage(src, minWidth = 1) {\n return new Promise((resolve, reject) => {\n const image = new Image();\n\n const handler = () => {\n delete image.onload;\n delete image.onerror;\n (image.naturalWidth >= minWidth ? resolve : reject)(image);\n };\n\n Object.assign(image, {\n onload: handler,\n onerror: handler,\n src\n });\n });\n}\n\n// ==========================================================================\nconst ui = {\n addStyleHook() {\n toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);\n toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);\n },\n\n // Toggle native HTML5 media controls\n toggleNativeControls(toggle = false) {\n if (toggle && this.isHTML5) {\n this.media.setAttribute('controls', '');\n } else {\n this.media.removeAttribute('controls');\n }\n },\n\n // Setup the UI\n build() {\n // Re-attach media element listeners\n // TODO: Use event bubbling?\n this.listeners.media(); // Don't setup interface if no support\n\n if (!this.supported.ui) {\n this.debug.warn(`Basic support only for ${this.provider} ${this.type}`); // Restore native controls\n\n ui.toggleNativeControls.call(this, true); // Bail\n\n return;\n } // Inject custom controls if not present\n\n\n if (!is.element(this.elements.controls)) {\n // Inject custom controls\n controls.inject.call(this); // Re-attach control listeners\n\n this.listeners.controls();\n } // Remove native controls\n\n\n ui.toggleNativeControls.call(this); // Setup captions for HTML5\n\n if (this.isHTML5) {\n captions.setup.call(this);\n } // Reset volume\n\n\n this.volume = null; // Reset mute state\n\n this.muted = null; // Reset loop state\n\n this.loop = null; // Reset quality setting\n\n this.quality = null; // Reset speed\n\n this.speed = null; // Reset volume display\n\n controls.updateVolume.call(this); // Reset time display\n\n controls.timeUpdate.call(this); // Reset duration display\n\n controls.durationUpdate.call(this); // Update the UI\n\n ui.checkPlaying.call(this); // Check for picture-in-picture support\n\n toggleClass(this.elements.container, this.config.classNames.pip.supported, support.pip && this.isHTML5 && this.isVideo); // Check for airplay support\n\n toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5); // Add iOS class\n\n toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos); // Add touch class\n\n toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch); // Ready for API calls\n\n this.ready = true; // Ready event at end of execution stack\n\n setTimeout(() => {\n triggerEvent.call(this, this.media, 'ready');\n }, 0); // Set the title\n\n ui.setTitle.call(this); // Assure the poster image is set, if the property was added before the element was created\n\n if (this.poster) {\n ui.setPoster.call(this, this.poster, false).catch(() => {});\n } // Manually set the duration if user has overridden it.\n // The event listeners for it doesn't get called if preload is disabled (#701)\n\n\n if (this.config.duration) {\n controls.durationUpdate.call(this);\n }\n },\n\n // Setup aria attribute for play and iframe title\n setTitle() {\n // Find the current text\n let label = i18n.get('play', this.config); // If there's a media title set, use that for the label\n\n if (is.string(this.config.title) && !is.empty(this.config.title)) {\n label += `, ${this.config.title}`;\n } // If there's a play button, set label\n\n\n Array.from(this.elements.buttons.play || []).forEach(button => {\n button.setAttribute('aria-label', label);\n }); // Set iframe title\n // https://github.com/sampotts/plyr/issues/124\n\n if (this.isEmbed) {\n const iframe = getElement.call(this, 'iframe');\n\n if (!is.element(iframe)) {\n return;\n } // Default to media type\n\n\n const title = !is.empty(this.config.title) ? this.config.title : 'video';\n const format = i18n.get('frameTitle', this.config);\n iframe.setAttribute('title', format.replace('{title}', title));\n }\n },\n\n // Toggle poster\n togglePoster(enable) {\n toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);\n },\n\n // Set the poster image (async)\n // Used internally for the poster setter, with the passive option forced to false\n setPoster(poster, passive = true) {\n // Don't override if call is passive\n if (passive && this.poster) {\n return Promise.reject(new Error('Poster already set'));\n } // Set property synchronously to respect the call order\n\n\n this.media.setAttribute('data-poster', poster); // Show the poster\n\n this.elements.poster.removeAttribute('hidden'); // Wait until ui is ready\n\n return ready.call(this) // Load image\n .then(() => loadImage(poster)).catch(error => {\n // Hide poster on error unless it's been set by another call\n if (poster === this.poster) {\n ui.togglePoster.call(this, false);\n } // Rethrow\n\n\n throw error;\n }).then(() => {\n // Prevent race conditions\n if (poster !== this.poster) {\n throw new Error('setPoster cancelled by later call to setPoster');\n }\n }).then(() => {\n Object.assign(this.elements.poster.style, {\n backgroundImage: `url('${poster}')`,\n // Reset backgroundSize as well (since it can be set to \"cover\" for padded thumbnails for youtube)\n backgroundSize: ''\n });\n ui.togglePoster.call(this, true);\n return poster;\n });\n },\n\n // Check playing state\n checkPlaying(event) {\n // Class hooks\n toggleClass(this.elements.container, this.config.classNames.playing, this.playing);\n toggleClass(this.elements.container, this.config.classNames.paused, this.paused);\n toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped); // Set state\n\n Array.from(this.elements.buttons.play || []).forEach(target => {\n Object.assign(target, {\n pressed: this.playing\n });\n target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config));\n }); // Only update controls on non timeupdate events\n\n if (is.event(event) && event.type === 'timeupdate') {\n return;\n } // Toggle controls\n\n\n ui.toggleControls.call(this);\n },\n\n // Check if media is loading\n checkLoading(event) {\n this.loading = ['stalled', 'waiting'].includes(event.type); // Clear timer\n\n clearTimeout(this.timers.loading); // Timer to prevent flicker when seeking\n\n this.timers.loading = setTimeout(() => {\n // Update progress bar loading class state\n toggleClass(this.elements.container, this.config.classNames.loading, this.loading); // Update controls visibility\n\n ui.toggleControls.call(this);\n }, this.loading ? 250 : 0);\n },\n\n // Toggle controls based on state and `force` argument\n toggleControls(force) {\n const {\n controls: controlsElement\n } = this.elements;\n\n if (controlsElement && this.config.hideControls) {\n // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.)\n const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now(); // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide\n\n this.toggleControls(Boolean(force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek));\n }\n },\n\n // Migrate any custom properties from the media to the parent\n migrateStyles() {\n // Loop through values (as they are the keys when the object is spread 🤔)\n Object.values({ ...this.media.style\n }) // We're only fussed about Plyr specific properties\n .filter(key => !is.empty(key) && is.string(key) && key.startsWith('--plyr')).forEach(key => {\n // Set on the container\n this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key)); // Clean up from media element\n\n this.media.style.removeProperty(key);\n }); // Remove attribute if empty\n\n if (is.empty(this.media.style)) {\n this.media.removeAttribute('style');\n }\n }\n\n};\n\nclass Listeners {\n constructor(_player) {\n _defineProperty$1(this, \"firstTouch\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n player.touch = true; // Add touch class\n\n toggleClass(elements.container, player.config.classNames.isTouch, true);\n });\n\n _defineProperty$1(this, \"setTabFocus\", event => {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n clearTimeout(this.focusTimer); // Ignore any key other than tab\n\n if (event.type === 'keydown' && event.which !== 9) {\n return;\n } // Store reference to event timeStamp\n\n\n if (event.type === 'keydown') {\n this.lastKeyDown = event.timeStamp;\n } // Remove current classes\n\n\n const removeCurrent = () => {\n const className = player.config.classNames.tabFocus;\n const current = getElements.call(player, `.${className}`);\n toggleClass(current, className, false);\n }; // Determine if a key was pressed to trigger this event\n\n\n const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20; // Ignore focus events if a key was pressed prior\n\n if (event.type === 'focus' && !wasKeyDown) {\n return;\n } // Remove all current\n\n\n removeCurrent(); // Delay the adding of classname until the focus has changed\n // This event fires before the focusin event\n\n if (event.type !== 'focusout') {\n this.focusTimer = setTimeout(() => {\n const focused = document.activeElement; // Ignore if current focus element isn't inside the player\n\n if (!elements.container.contains(focused)) {\n return;\n }\n\n toggleClass(document.activeElement, player.config.classNames.tabFocus, true);\n }, 10);\n }\n });\n\n _defineProperty$1(this, \"global\", (toggle = true) => {\n const {\n player\n } = this; // Keyboard shortcuts\n\n if (player.config.keyboard.global) {\n toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false);\n } // Click anywhere closes menu\n\n\n toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle); // Detect touch by events\n\n once.call(player, document.body, 'touchstart', this.firstTouch); // Tab focus detection\n\n toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true);\n });\n\n _defineProperty$1(this, \"container\", () => {\n const {\n player\n } = this;\n const {\n config,\n elements,\n timers\n } = player; // Keyboard shortcuts\n\n if (!config.keyboard.global && config.keyboard.focused) {\n on.call(player, elements.container, 'keydown keyup', this.handleKey, false);\n } // Toggle controls on mouse events and entering fullscreen\n\n\n on.call(player, elements.container, 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen', event => {\n const {\n controls: controlsElement\n } = elements; // Remove button states for fullscreen\n\n if (controlsElement && event.type === 'enterfullscreen') {\n controlsElement.pressed = false;\n controlsElement.hover = false;\n } // Show, then hide after a timeout unless another control event occurs\n\n\n const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type);\n let delay = 0;\n\n if (show) {\n ui.toggleControls.call(player, true); // Use longer timeout for touch devices\n\n delay = player.touch ? 3000 : 2000;\n } // Clear timer\n\n\n clearTimeout(timers.controls); // Set new timer to prevent flicker when seeking\n\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n }); // Set a gutter for Vimeo\n\n const setGutter = () => {\n if (!player.isVimeo || player.config.vimeo.premium) {\n return;\n }\n\n const target = elements.wrapper;\n const {\n active\n } = player.fullscreen;\n const [videoWidth, videoHeight] = getAspectRatio.call(player);\n const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`); // If not active, remove styles\n\n if (!active) {\n if (useNativeAspectRatio) {\n target.style.width = null;\n target.style.height = null;\n } else {\n target.style.maxWidth = null;\n target.style.margin = null;\n }\n\n return;\n } // Determine which dimension will overflow and constrain view\n\n\n const [viewportWidth, viewportHeight] = getViewportSize();\n const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight;\n\n if (useNativeAspectRatio) {\n target.style.width = overflow ? 'auto' : '100%';\n target.style.height = overflow ? '100%' : 'auto';\n } else {\n target.style.maxWidth = overflow ? `${viewportHeight / videoHeight * videoWidth}px` : null;\n target.style.margin = overflow ? '0 auto' : null;\n }\n }; // Handle resizing\n\n\n const resized = () => {\n clearTimeout(timers.resized);\n timers.resized = setTimeout(setGutter, 50);\n };\n\n on.call(player, elements.container, 'enterfullscreen exitfullscreen', event => {\n const {\n target\n } = player.fullscreen; // Ignore events not from target\n\n if (target !== elements.container) {\n return;\n } // If it's not an embed and no ratio specified\n\n\n if (!player.isEmbed && is.empty(player.config.ratio)) {\n return;\n } // Set Vimeo gutter\n\n\n setGutter(); // Watch for resizes\n\n const method = event.type === 'enterfullscreen' ? on : off;\n method.call(player, window, 'resize', resized);\n });\n });\n\n _defineProperty$1(this, \"media\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player; // Time change on media\n\n on.call(player, player.media, 'timeupdate seeking seeked', event => controls.timeUpdate.call(player, event)); // Display duration\n\n on.call(player, player.media, 'durationchange loadeddata loadedmetadata', event => controls.durationUpdate.call(player, event)); // Handle the media finishing\n\n on.call(player, player.media, 'ended', () => {\n // Show poster on end\n if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) {\n // Restart\n player.restart(); // Call pause otherwise IE11 will start playing the video again\n\n player.pause();\n }\n }); // Check for buffer progress\n\n on.call(player, player.media, 'progress playing seeking seeked', event => controls.updateProgress.call(player, event)); // Handle volume changes\n\n on.call(player, player.media, 'volumechange', event => controls.updateVolume.call(player, event)); // Handle play/pause\n\n on.call(player, player.media, 'playing play pause ended emptied timeupdate', event => ui.checkPlaying.call(player, event)); // Loading state\n\n on.call(player, player.media, 'waiting canplay seeked playing', event => ui.checkLoading.call(player, event)); // Click video\n\n if (player.supported.ui && player.config.clickToPlay && !player.isAudio) {\n // Re-fetch the wrapper\n const wrapper = getElement.call(player, `.${player.config.classNames.video}`); // Bail if there's no wrapper (this should never happen)\n\n if (!is.element(wrapper)) {\n return;\n } // On click play, pause or restart\n\n\n on.call(player, elements.container, 'click', event => {\n const targets = [elements.container, wrapper]; // Ignore if click if not container or in video wrapper\n\n if (!targets.includes(event.target) && !wrapper.contains(event.target)) {\n return;\n } // Touch devices will just show controls (if hidden)\n\n\n if (player.touch && player.config.hideControls) {\n return;\n }\n\n if (player.ended) {\n this.proxy(event, player.restart, 'restart');\n this.proxy(event, () => {\n silencePromise(player.play());\n }, 'play');\n } else {\n this.proxy(event, () => {\n silencePromise(player.togglePlay());\n }, 'play');\n }\n });\n } // Disable right click\n\n\n if (player.supported.ui && player.config.disableContextMenu) {\n on.call(player, elements.wrapper, 'contextmenu', event => {\n event.preventDefault();\n }, false);\n } // Volume change\n\n\n on.call(player, player.media, 'volumechange', () => {\n // Save to storage\n player.storage.set({\n volume: player.volume,\n muted: player.muted\n });\n }); // Speed change\n\n on.call(player, player.media, 'ratechange', () => {\n // Update UI\n controls.updateSetting.call(player, 'speed'); // Save to storage\n\n player.storage.set({\n speed: player.speed\n });\n }); // Quality change\n\n on.call(player, player.media, 'qualitychange', event => {\n // Update UI\n controls.updateSetting.call(player, 'quality', null, event.detail.quality);\n }); // Update download link when ready and if quality changes\n\n on.call(player, player.media, 'ready qualitychange', () => {\n controls.setDownloadUrl.call(player);\n }); // Proxy events to container\n // Bubble up key events for Edge\n\n const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' ');\n on.call(player, player.media, proxyEvents, event => {\n let {\n detail = {}\n } = event; // Get error details from media\n\n if (event.type === 'error') {\n detail = player.media.error;\n }\n\n triggerEvent.call(player, elements.container, event.type, true, detail);\n });\n });\n\n _defineProperty$1(this, \"proxy\", (event, defaultHandler, customHandlerKey) => {\n const {\n player\n } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n let returned = true; // Execute custom handler\n\n if (hasCustomHandler) {\n returned = customHandler.call(player, event);\n } // Only call default handler if not prevented in custom handler\n\n\n if (returned !== false && is.function(defaultHandler)) {\n defaultHandler.call(player, event);\n }\n });\n\n _defineProperty$1(this, \"bind\", (element, type, defaultHandler, customHandlerKey, passive = true) => {\n const {\n player\n } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n on.call(player, element, type, event => this.proxy(event, defaultHandler, customHandlerKey), passive && !hasCustomHandler);\n });\n\n _defineProperty$1(this, \"controls\", () => {\n const {\n player\n } = this;\n const {\n elements\n } = player; // IE doesn't support input event, so we fallback to change\n\n const inputEvent = browser.isIE ? 'change' : 'input'; // Play/pause toggle\n\n if (elements.buttons.play) {\n Array.from(elements.buttons.play).forEach(button => {\n this.bind(button, 'click', () => {\n silencePromise(player.togglePlay());\n }, 'play');\n });\n } // Pause\n\n\n this.bind(elements.buttons.restart, 'click', player.restart, 'restart'); // Rewind\n\n this.bind(elements.buttons.rewind, 'click', () => {\n // Record seek time so we can prevent hiding controls for a few seconds after rewind\n player.lastSeekTime = Date.now();\n player.rewind();\n }, 'rewind'); // Rewind\n\n this.bind(elements.buttons.fastForward, 'click', () => {\n // Record seek time so we can prevent hiding controls for a few seconds after fast forward\n player.lastSeekTime = Date.now();\n player.forward();\n }, 'fastForward'); // Mute toggle\n\n this.bind(elements.buttons.mute, 'click', () => {\n player.muted = !player.muted;\n }, 'mute'); // Captions toggle\n\n this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions()); // Download\n\n this.bind(elements.buttons.download, 'click', () => {\n triggerEvent.call(player, player.media, 'download');\n }, 'download'); // Fullscreen toggle\n\n this.bind(elements.buttons.fullscreen, 'click', () => {\n player.fullscreen.toggle();\n }, 'fullscreen'); // Picture-in-Picture\n\n this.bind(elements.buttons.pip, 'click', () => {\n player.pip = 'toggle';\n }, 'pip'); // Airplay\n\n this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay'); // Settings menu - click toggle\n\n this.bind(elements.buttons.settings, 'click', event => {\n // Prevent the document click listener closing the menu\n event.stopPropagation();\n event.preventDefault();\n controls.toggleMenu.call(player, event);\n }, null, false); // Can't be passive as we're preventing default\n // Settings menu - keyboard toggle\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n\n this.bind(elements.buttons.settings, 'keyup', event => {\n const code = event.which; // We only care about space and return\n\n if (![13, 32].includes(code)) {\n return;\n } // Because return triggers a click anyway, all we need to do is set focus\n\n\n if (code === 13) {\n controls.focusFirstMenuItem.call(player, null, true);\n return;\n } // Prevent scroll\n\n\n event.preventDefault(); // Prevent playing video (Firefox)\n\n event.stopPropagation(); // Toggle menu\n\n controls.toggleMenu.call(player, event);\n }, null, false // Can't be passive as we're preventing default\n ); // Escape closes menu\n\n this.bind(elements.settings.menu, 'keydown', event => {\n if (event.which === 27) {\n controls.toggleMenu.call(player, event);\n }\n }); // Set range input alternative \"value\", which matches the tooltip time (#954)\n\n this.bind(elements.inputs.seek, 'mousedown mousemove', event => {\n const rect = elements.progress.getBoundingClientRect();\n const percent = 100 / rect.width * (event.pageX - rect.left);\n event.currentTarget.setAttribute('seek-value', percent);\n }); // Pause while seeking\n\n this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', event => {\n const seek = event.currentTarget;\n const code = event.keyCode ? event.keyCode : event.which;\n const attribute = 'play-on-seeked';\n\n if (is.keyboardEvent(event) && code !== 39 && code !== 37) {\n return;\n } // Record seek time so we can prevent hiding controls for a few seconds after seek\n\n\n player.lastSeekTime = Date.now(); // Was playing before?\n\n const play = seek.hasAttribute(attribute); // Done seeking\n\n const done = ['mouseup', 'touchend', 'keyup'].includes(event.type); // If we're done seeking and it was playing, resume playback\n\n if (play && done) {\n seek.removeAttribute(attribute);\n silencePromise(player.play());\n } else if (!done && player.playing) {\n seek.setAttribute(attribute, '');\n player.pause();\n }\n }); // Fix range inputs on iOS\n // Super weird iOS bug where after you interact with an <input type=\"range\">,\n // it takes over further interactions on the page. This is a hack\n\n if (browser.isIos) {\n const inputs = getElements.call(player, 'input[type=\"range\"]');\n Array.from(inputs).forEach(input => this.bind(input, inputEvent, event => repaint(event.target)));\n } // Seek\n\n\n this.bind(elements.inputs.seek, inputEvent, event => {\n const seek = event.currentTarget; // If it exists, use seek-value instead of \"value\" for consistency with tooltip time (#954)\n\n let seekTo = seek.getAttribute('seek-value');\n\n if (is.empty(seekTo)) {\n seekTo = seek.value;\n }\n\n seek.removeAttribute('seek-value');\n player.currentTime = seekTo / seek.max * player.duration;\n }, 'seek'); // Seek tooltip\n\n this.bind(elements.progress, 'mouseenter mouseleave mousemove', event => controls.updateSeekTooltip.call(player, event)); // Preview thumbnails plugin\n // TODO: Really need to work on some sort of plug-in wide event bus or pub-sub for this\n\n this.bind(elements.progress, 'mousemove touchmove', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startMove(event);\n }\n }); // Hide thumbnail preview - on mouse click, mouse leave, and video play/seek. All four are required, e.g., for buffering\n\n this.bind(elements.progress, 'mouseleave touchend click', () => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endMove(false, true);\n }\n }); // Show scrubbing preview\n\n this.bind(elements.progress, 'mousedown touchstart', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startScrubbing(event);\n }\n });\n this.bind(elements.progress, 'mouseup touchend', event => {\n const {\n previewThumbnails\n } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endScrubbing(event);\n }\n }); // Polyfill for lower fill in <input type=\"range\"> for webkit\n\n if (browser.isWebkit) {\n Array.from(getElements.call(player, 'input[type=\"range\"]')).forEach(element => {\n this.bind(element, 'input', event => controls.updateRangeFill.call(player, event.target));\n });\n } // Current time invert\n // Only if one time element is used for both currentTime and duration\n\n\n if (player.config.toggleInvert && !is.element(elements.display.duration)) {\n this.bind(elements.display.currentTime, 'click', () => {\n // Do nothing if we're at the start\n if (player.currentTime === 0) {\n return;\n }\n\n player.config.invertTime = !player.config.invertTime;\n controls.timeUpdate.call(player);\n });\n } // Volume\n\n\n this.bind(elements.inputs.volume, inputEvent, event => {\n player.volume = event.target.value;\n }, 'volume'); // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting)\n\n this.bind(elements.controls, 'mouseenter mouseleave', event => {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }); // Also update controls.hover state for any non-player children of fullscreen element (as above)\n\n if (elements.fullscreen) {\n Array.from(elements.fullscreen.children).filter(c => !c.contains(elements.container)).forEach(child => {\n this.bind(child, 'mouseenter mouseleave', event => {\n if (elements.controls) {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }\n });\n });\n } // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting)\n\n\n this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', event => {\n elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type);\n }); // Show controls when they receive focus (e.g., when using keyboard tab key)\n\n this.bind(elements.controls, 'focusin', () => {\n const {\n config,\n timers\n } = player; // Skip transition to prevent focus from scrolling the parent element\n\n toggleClass(elements.controls, config.classNames.noTransition, true); // Toggle\n\n ui.toggleControls.call(player, true); // Restore transition\n\n setTimeout(() => {\n toggleClass(elements.controls, config.classNames.noTransition, false);\n }, 0); // Delay a little more for mouse users\n\n const delay = this.touch ? 3000 : 4000; // Clear timer\n\n clearTimeout(timers.controls); // Hide again after delay\n\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n }); // Mouse wheel for volume\n\n this.bind(elements.inputs.volume, 'wheel', event => {\n // Detect \"natural\" scroll - suppored on OS X Safari only\n // Other browsers on OS X will be inverted until support improves\n const inverted = event.webkitDirectionInvertedFromDevice; // Get delta from event. Invert if `inverted` is true\n\n const [x, y] = [event.deltaX, -event.deltaY].map(value => inverted ? -value : value); // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta)\n\n const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y); // Change the volume by 2%\n\n player.increaseVolume(direction / 50); // Don't break page scrolling at max and min\n\n const {\n volume\n } = player.media;\n\n if (direction === 1 && volume < 1 || direction === -1 && volume > 0) {\n event.preventDefault();\n }\n }, 'volume', false);\n });\n\n this.player = _player;\n this.lastKey = null;\n this.focusTimer = null;\n this.lastKeyDown = null;\n this.handleKey = this.handleKey.bind(this);\n this.toggleMenu = this.toggleMenu.bind(this);\n this.setTabFocus = this.setTabFocus.bind(this);\n this.firstTouch = this.firstTouch.bind(this);\n } // Handle key presses\n\n\n handleKey(event) {\n const {\n player\n } = this;\n const {\n elements\n } = player;\n const code = event.keyCode ? event.keyCode : event.which;\n const pressed = event.type === 'keydown';\n const repeat = pressed && code === this.lastKey; // Bail if a modifier key is set\n\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {\n return;\n } // If the event is bubbled from the media element\n // Firefox doesn't get the keycode for whatever reason\n\n\n if (!is.number(code)) {\n return;\n } // Seek by the number keys\n\n\n const seekByKey = () => {\n // Divide the max duration into 10th's and times by the number value\n player.currentTime = player.duration / 10 * (code - 48);\n }; // Handle the key on keydown\n // Reset on keyup\n\n\n if (pressed) {\n // Check focused element\n // and if the focused element is not editable (e.g. text input)\n // and any that accept key input http://webaim.org/techniques/keyboard/\n const focused = document.activeElement;\n\n if (is.element(focused)) {\n const {\n editable\n } = player.config.selectors;\n const {\n seek\n } = elements.inputs;\n\n if (focused !== seek && matches(focused, editable)) {\n return;\n }\n\n if (event.which === 32 && matches(focused, 'button, [role^=\"menuitem\"]')) {\n return;\n }\n } // Which keycodes should we prevent default\n\n\n const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79]; // If the code is found prevent default (e.g. prevent scrolling for arrows)\n\n if (preventDefault.includes(code)) {\n event.preventDefault();\n event.stopPropagation();\n }\n\n switch (code) {\n case 48:\n case 49:\n case 50:\n case 51:\n case 52:\n case 53:\n case 54:\n case 55:\n case 56:\n case 57:\n // 0-9\n if (!repeat) {\n seekByKey();\n }\n\n break;\n\n case 32:\n case 75:\n // Space and K key\n if (!repeat) {\n silencePromise(player.togglePlay());\n }\n\n break;\n\n case 38:\n // Arrow up\n player.increaseVolume(0.1);\n break;\n\n case 40:\n // Arrow down\n player.decreaseVolume(0.1);\n break;\n\n case 77:\n // M key\n if (!repeat) {\n player.muted = !player.muted;\n }\n\n break;\n\n case 39:\n // Arrow forward\n player.forward();\n break;\n\n case 37:\n // Arrow back\n player.rewind();\n break;\n\n case 70:\n // F key\n player.fullscreen.toggle();\n break;\n\n case 67:\n // C key\n if (!repeat) {\n player.toggleCaptions();\n }\n\n break;\n\n case 76:\n // L key\n player.loop = !player.loop;\n break;\n } // Escape is handle natively when in full screen\n // So we only need to worry about non native\n\n\n if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) {\n player.fullscreen.toggle();\n } // Store last code for next cycle\n\n\n this.lastKey = code;\n } else {\n this.lastKey = null;\n }\n } // Toggle menu\n\n\n toggleMenu(event) {\n controls.toggleMenu.call(this.player, event);\n } // Device is touch enabled\n\n\n}\n\nvar loadjs_umd = createCommonjsModule(function (module, exports) {\n (function (root, factory) {\n {\n module.exports = factory();\n }\n })(commonjsGlobal, function () {\n /**\n * Global dependencies.\n * @global {Object} document - DOM\n */\n var devnull = function () {},\n bundleIdCache = {},\n bundleResultCache = {},\n bundleCallbackQueue = {};\n /**\n * Subscribe to bundle load event.\n * @param {string[]} bundleIds - Bundle ids\n * @param {Function} callbackFn - The callback function\n */\n\n\n function subscribe(bundleIds, callbackFn) {\n // listify\n bundleIds = bundleIds.push ? bundleIds : [bundleIds];\n var depsNotFound = [],\n i = bundleIds.length,\n numWaiting = i,\n fn,\n bundleId,\n r,\n q; // define callback function\n\n fn = function (bundleId, pathsNotFound) {\n if (pathsNotFound.length) depsNotFound.push(bundleId);\n numWaiting--;\n if (!numWaiting) callbackFn(depsNotFound);\n }; // register callback\n\n\n while (i--) {\n bundleId = bundleIds[i]; // execute callback if in result cache\n\n r = bundleResultCache[bundleId];\n\n if (r) {\n fn(bundleId, r);\n continue;\n } // add to callback queue\n\n\n q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];\n q.push(fn);\n }\n }\n /**\n * Publish bundle load event.\n * @param {string} bundleId - Bundle id\n * @param {string[]} pathsNotFound - List of files not found\n */\n\n\n function publish(bundleId, pathsNotFound) {\n // exit if id isn't defined\n if (!bundleId) return;\n var q = bundleCallbackQueue[bundleId]; // cache result\n\n bundleResultCache[bundleId] = pathsNotFound; // exit if queue is empty\n\n if (!q) return; // empty callback queue\n\n while (q.length) {\n q[0](bundleId, pathsNotFound);\n q.splice(0, 1);\n }\n }\n /**\n * Execute callbacks.\n * @param {Object or Function} args - The callback args\n * @param {string[]} depsNotFound - List of dependencies not found\n */\n\n\n function executeCallbacks(args, depsNotFound) {\n // accept function as argument\n if (args.call) args = {\n success: args\n }; // success and error callbacks\n\n if (depsNotFound.length) (args.error || devnull)(depsNotFound);else (args.success || devnull)(args);\n }\n /**\n * Load individual file.\n * @param {string} path - The file path\n * @param {Function} callbackFn - The callback function\n */\n\n\n function loadFile(path, callbackFn, args, numTries) {\n var doc = document,\n async = args.async,\n maxTries = (args.numRetries || 0) + 1,\n beforeCallbackFn = args.before || devnull,\n pathname = path.replace(/[\\?|#].*$/, ''),\n pathStripped = path.replace(/^(css|img)!/, ''),\n isLegacyIECss,\n e;\n numTries = numTries || 0;\n\n if (/(^css!|\\.css$)/.test(pathname)) {\n // css\n e = doc.createElement('link');\n e.rel = 'stylesheet';\n e.href = pathStripped; // tag IE9+\n\n isLegacyIECss = 'hideFocus' in e; // use preload in IE Edge (to detect load errors)\n\n if (isLegacyIECss && e.relList) {\n isLegacyIECss = 0;\n e.rel = 'preload';\n e.as = 'style';\n }\n } else if (/(^img!|\\.(png|gif|jpg|svg|webp)$)/.test(pathname)) {\n // image\n e = doc.createElement('img');\n e.src = pathStripped;\n } else {\n // javascript\n e = doc.createElement('script');\n e.src = path;\n e.async = async === undefined ? true : async;\n }\n\n e.onload = e.onerror = e.onbeforeload = function (ev) {\n var result = ev.type[0]; // treat empty stylesheets as failures to get around lack of onerror\n // support in IE9-11\n\n if (isLegacyIECss) {\n try {\n if (!e.sheet.cssText.length) result = 'e';\n } catch (x) {\n // sheets objects created from load errors don't allow access to\n // `cssText` (unless error is Code:18 SecurityError)\n if (x.code != 18) result = 'e';\n }\n } // handle retries in case of load failure\n\n\n if (result == 'e') {\n // increment counter\n numTries += 1; // exit function and try again\n\n if (numTries < maxTries) {\n return loadFile(path, callbackFn, args, numTries);\n }\n } else if (e.rel == 'preload' && e.as == 'style') {\n // activate preloaded stylesheets\n return e.rel = 'stylesheet'; // jshint ignore:line\n } // execute callback\n\n\n callbackFn(path, result, ev.defaultPrevented);\n }; // add to document (unless callback returns `false`)\n\n\n if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);\n }\n /**\n * Load multiple files.\n * @param {string[]} paths - The file paths\n * @param {Function} callbackFn - The callback function\n */\n\n\n function loadFiles(paths, callbackFn, args) {\n // listify paths\n paths = paths.push ? paths : [paths];\n var numWaiting = paths.length,\n x = numWaiting,\n pathsNotFound = [],\n fn,\n i; // define callback function\n\n fn = function (path, result, defaultPrevented) {\n // handle error\n if (result == 'e') pathsNotFound.push(path); // handle beforeload event. If defaultPrevented then that means the load\n // will be blocked (ex. Ghostery/ABP on Safari)\n\n if (result == 'b') {\n if (defaultPrevented) pathsNotFound.push(path);else return;\n }\n\n numWaiting--;\n if (!numWaiting) callbackFn(pathsNotFound);\n }; // load scripts\n\n\n for (i = 0; i < x; i++) loadFile(paths[i], fn, args);\n }\n /**\n * Initiate script load and register bundle.\n * @param {(string|string[])} paths - The file paths\n * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success\n * callback or (3) object literal with success/error arguments, numRetries,\n * etc.\n * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object\n * literal with success/error arguments, numRetries, etc.\n */\n\n\n function loadjs(paths, arg1, arg2) {\n var bundleId, args; // bundleId (if string)\n\n if (arg1 && arg1.trim) bundleId = arg1; // args (default is {})\n\n args = (bundleId ? arg2 : arg1) || {}; // throw error if bundle is already defined\n\n if (bundleId) {\n if (bundleId in bundleIdCache) {\n throw \"LoadJS\";\n } else {\n bundleIdCache[bundleId] = true;\n }\n }\n\n function loadFn(resolve, reject) {\n loadFiles(paths, function (pathsNotFound) {\n // execute callbacks\n executeCallbacks(args, pathsNotFound); // resolve Promise\n\n if (resolve) {\n executeCallbacks({\n success: resolve,\n error: reject\n }, pathsNotFound);\n } // publish bundle load event\n\n\n publish(bundleId, pathsNotFound);\n }, args);\n }\n\n if (args.returnPromise) return new Promise(loadFn);else loadFn();\n }\n /**\n * Execute callbacks when dependencies have been satisfied.\n * @param {(string|string[])} deps - List of bundle ids\n * @param {Object} args - success/error arguments\n */\n\n\n loadjs.ready = function ready(deps, args) {\n // subscribe to bundle load event\n subscribe(deps, function (depsNotFound) {\n // execute callbacks\n executeCallbacks(args, depsNotFound);\n });\n return loadjs;\n };\n /**\n * Manually satisfy bundle dependencies.\n * @param {string} bundleId - The bundle id\n */\n\n\n loadjs.done = function done(bundleId) {\n publish(bundleId, []);\n };\n /**\n * Reset loadjs dependencies statuses\n */\n\n\n loadjs.reset = function reset() {\n bundleIdCache = {};\n bundleResultCache = {};\n bundleCallbackQueue = {};\n };\n /**\n * Determine if bundle has already been defined\n * @param String} bundleId - The bundle id\n */\n\n\n loadjs.isDefined = function isDefined(bundleId) {\n return bundleId in bundleIdCache;\n }; // export\n\n\n return loadjs;\n });\n});\n\n// ==========================================================================\nfunction loadScript(url) {\n return new Promise((resolve, reject) => {\n loadjs_umd(url, {\n success: resolve,\n error: reject\n });\n });\n}\n\n// ==========================================================================\n\nfunction parseId$1(url) {\n if (is.empty(url)) {\n return null;\n }\n\n if (is.number(Number(url))) {\n return url;\n }\n\n const regex = /^.*(vimeo.com\\/|video\\/)(\\d+).*/;\n return url.match(regex) ? RegExp.$2 : url;\n} // Try to extract a hash for private videos from the URL\n\n\nfunction parseHash(url) {\n /* This regex matches a hexadecimal hash if given in any of these forms:\n * - [https://player.]vimeo.com/video/{id}/{hash}[?params]\n * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms]\n * - [https://player.]vimeo.com/video/{id}?[params]&h={hash}\n * - video/{id}/{hash}\n * If matched, the hash is available in the named group `hash`\n */\n const regex = /^.*(?:vimeo.com\\/|video\\/)(?:\\d+)(?:\\?.*&*h=|\\/)+(?<hash>[\\d,a-f]+)/;\n const found = url.match(regex);\n return found ? found.groups.hash : null;\n} // Set playback state and trigger change (only on actual change)\n\n\nfunction assurePlaybackState$1(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nconst vimeo = {\n setup() {\n const player = this; // Add embed class for responsive\n\n toggleClass(player.elements.wrapper, player.config.classNames.embed, true); // Set speed options from config\n\n player.options.speed = player.config.speed.options; // Set intial ratio\n\n setAspectRatio.call(player); // Load the SDK if not already\n\n if (!is.object(window.Vimeo)) {\n loadScript(player.config.urls.vimeo.sdk).then(() => {\n vimeo.ready.call(player);\n }).catch(error => {\n player.debug.warn('Vimeo SDK (player.js) failed to load', error);\n });\n } else {\n vimeo.ready.call(player);\n }\n },\n\n // API Ready\n ready() {\n const player = this;\n const config = player.config.vimeo;\n const {\n premium,\n referrerPolicy,\n ...frameParams\n } = config; // Get the source URL or ID\n\n let source = player.media.getAttribute('src');\n let hash = ''; // Get from <div> if needed\n\n if (is.empty(source)) {\n source = player.media.getAttribute(player.config.attributes.embed.id); // hash can also be set as attribute on the <div>\n\n hash = player.media.getAttribute(player.config.attributes.embed.hash);\n } else {\n hash = parseHash(source);\n }\n\n const hashParam = hash ? {\n h: hash\n } : {}; // If the owner has a pro or premium account then we can hide controls etc\n\n if (premium) {\n Object.assign(frameParams, {\n controls: false,\n sidedock: false\n });\n } // Get Vimeo params for the iframe\n\n\n const params = buildUrlParams({\n loop: player.config.loop.active,\n autoplay: player.autoplay,\n muted: player.muted,\n gesture: 'media',\n playsinline: !this.config.fullscreen.iosNative,\n // hash has to be added to iframe-URL\n ...hashParam,\n ...frameParams\n });\n const id = parseId$1(source); // Build an iframe\n\n const iframe = createElement('iframe');\n const src = format(player.config.urls.vimeo.iframe, id, params);\n iframe.setAttribute('src', src);\n iframe.setAttribute('allowfullscreen', '');\n iframe.setAttribute('allow', ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; ')); // Set the referrer policy if required\n\n if (!is.empty(referrerPolicy)) {\n iframe.setAttribute('referrerPolicy', referrerPolicy);\n } // Inject the package\n\n\n if (premium || !config.customControls) {\n iframe.setAttribute('data-poster', player.poster);\n player.media = replaceElement(iframe, player.media);\n } else {\n const wrapper = createElement('div', {\n class: player.config.classNames.embedContainer,\n 'data-poster': player.poster\n });\n wrapper.appendChild(iframe);\n player.media = replaceElement(wrapper, player.media);\n } // Get poster image\n\n\n if (!config.customControls) {\n fetch(format(player.config.urls.vimeo.api, src)).then(response => {\n if (is.empty(response) || !response.thumbnail_url) {\n return;\n } // Set and show poster\n\n\n ui.setPoster.call(player, response.thumbnail_url).catch(() => {});\n });\n } // Setup instance\n // https://github.com/vimeo/player.js\n\n\n player.embed = new window.Vimeo.Player(iframe, {\n autopause: player.config.autopause,\n muted: player.muted\n });\n player.media.paused = true;\n player.media.currentTime = 0; // Disable native text track rendering\n\n if (player.supported.ui) {\n player.embed.disableTextTrack();\n } // Create a faux HTML5 API using the Vimeo API\n\n\n player.media.play = () => {\n assurePlaybackState$1.call(player, true);\n return player.embed.play();\n };\n\n player.media.pause = () => {\n assurePlaybackState$1.call(player, false);\n return player.embed.pause();\n };\n\n player.media.stop = () => {\n player.pause();\n player.currentTime = 0;\n }; // Seeking\n\n\n let {\n currentTime\n } = player.media;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return currentTime;\n },\n\n set(time) {\n // Vimeo will automatically play on seek if the video hasn't been played before\n // Get current paused state and volume etc\n const {\n embed,\n media,\n paused,\n volume\n } = player;\n const restorePause = paused && !embed.hasPlayed; // Set seeking state and trigger event\n\n media.seeking = true;\n triggerEvent.call(player, media, 'seeking'); // If paused, mute until seek is complete\n\n Promise.resolve(restorePause && embed.setVolume(0)) // Seek\n .then(() => embed.setCurrentTime(time)) // Restore paused\n .then(() => restorePause && embed.pause()) // Restore volume\n .then(() => restorePause && embed.setVolume(volume)).catch(() => {// Do nothing\n });\n }\n\n }); // Playback speed\n\n let speed = player.config.speed.selected;\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return speed;\n },\n\n set(input) {\n player.embed.setPlaybackRate(input).then(() => {\n speed = input;\n triggerEvent.call(player, player.media, 'ratechange');\n }).catch(() => {\n // Cannot set Playback Rate, Video is probably not on Pro account\n player.options.speed = [1];\n });\n }\n\n }); // Volume\n\n let {\n volume\n } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n\n set(input) {\n player.embed.setVolume(input).then(() => {\n volume = input;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n }\n\n }); // Muted\n\n let {\n muted\n } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : false;\n player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => {\n muted = toggle;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n }\n\n }); // Loop\n\n let {\n loop\n } = player.config;\n Object.defineProperty(player.media, 'loop', {\n get() {\n return loop;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : player.config.loop.active;\n player.embed.setLoop(toggle).then(() => {\n loop = toggle;\n });\n }\n\n }); // Source\n\n let currentSrc;\n player.embed.getVideoUrl().then(value => {\n currentSrc = value;\n controls.setDownloadUrl.call(player);\n }).catch(error => {\n this.debug.warn(error);\n });\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return currentSrc;\n }\n\n }); // Ended\n\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n }\n\n }); // Set aspect ratio based on video size\n\n Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(dimensions => {\n const [width, height] = dimensions;\n player.embed.ratio = roundAspectRatio(width, height);\n setAspectRatio.call(this);\n }); // Set autopause\n\n player.embed.setAutopause(player.config.autopause).then(state => {\n player.config.autopause = state;\n }); // Get title\n\n player.embed.getVideoTitle().then(title => {\n player.config.title = title;\n ui.setTitle.call(this);\n }); // Get current time\n\n player.embed.getCurrentTime().then(value => {\n currentTime = value;\n triggerEvent.call(player, player.media, 'timeupdate');\n }); // Get duration\n\n player.embed.getDuration().then(value => {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }); // Get captions\n\n player.embed.getTextTracks().then(tracks => {\n player.media.textTracks = tracks;\n captions.setup.call(player);\n });\n player.embed.on('cuechange', ({\n cues = []\n }) => {\n const strippedCues = cues.map(cue => stripHTML(cue.text));\n captions.updateCues.call(player, strippedCues);\n });\n player.embed.on('loaded', () => {\n // Assure state and events are updated on autoplay\n player.embed.getPaused().then(paused => {\n assurePlaybackState$1.call(player, !paused);\n\n if (!paused) {\n triggerEvent.call(player, player.media, 'playing');\n }\n });\n\n if (is.element(player.embed.element) && player.supported.ui) {\n const frame = player.embed.element; // Fix keyboard focus issues\n // https://github.com/sampotts/plyr/issues/317\n\n frame.setAttribute('tabindex', -1);\n }\n });\n player.embed.on('bufferstart', () => {\n triggerEvent.call(player, player.media, 'waiting');\n });\n player.embed.on('bufferend', () => {\n triggerEvent.call(player, player.media, 'playing');\n });\n player.embed.on('play', () => {\n assurePlaybackState$1.call(player, true);\n triggerEvent.call(player, player.media, 'playing');\n });\n player.embed.on('pause', () => {\n assurePlaybackState$1.call(player, false);\n });\n player.embed.on('timeupdate', data => {\n player.media.seeking = false;\n currentTime = data.seconds;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n player.embed.on('progress', data => {\n player.media.buffered = data.percent;\n triggerEvent.call(player, player.media, 'progress'); // Check all loaded\n\n if (parseInt(data.percent, 10) === 1) {\n triggerEvent.call(player, player.media, 'canplaythrough');\n } // Get duration as if we do it before load, it gives an incorrect value\n // https://github.com/sampotts/plyr/issues/891\n\n\n player.embed.getDuration().then(value => {\n if (value !== player.media.duration) {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }\n });\n });\n player.embed.on('seeked', () => {\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n });\n player.embed.on('ended', () => {\n player.media.paused = true;\n triggerEvent.call(player, player.media, 'ended');\n });\n player.embed.on('error', detail => {\n player.media.error = detail;\n triggerEvent.call(player, player.media, 'error');\n }); // Rebuild UI\n\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 0);\n }\n }\n\n};\n\n// ==========================================================================\n\nfunction parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n const regex = /^.*(youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=|&v=)([^#&?]*).*/;\n return url.match(regex) ? RegExp.$2 : url;\n} // Set playback state and trigger change (only on actual change)\n\n\nfunction assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nfunction getHost(config) {\n if (config.noCookie) {\n return 'https://www.youtube-nocookie.com';\n }\n\n if (window.location.protocol === 'http:') {\n return 'http://www.youtube.com';\n } // Use YouTube's default\n\n\n return undefined;\n}\n\nconst youtube = {\n setup() {\n // Add embed class for responsive\n toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Setup API\n\n if (is.object(window.YT) && is.function(window.YT.Player)) {\n youtube.ready.call(this);\n } else {\n // Reference current global callback\n const callback = window.onYouTubeIframeAPIReady; // Set callback to process queue\n\n window.onYouTubeIframeAPIReady = () => {\n // Call global callback if set\n if (is.function(callback)) {\n callback();\n }\n\n youtube.ready.call(this);\n }; // Load the SDK\n\n\n loadScript(this.config.urls.youtube.sdk).catch(error => {\n this.debug.warn('YouTube API failed to load', error);\n });\n }\n },\n\n // Get the media title\n getTitle(videoId) {\n const url = format(this.config.urls.youtube.api, videoId);\n fetch(url).then(data => {\n if (is.object(data)) {\n const {\n title,\n height,\n width\n } = data; // Set title\n\n this.config.title = title;\n ui.setTitle.call(this); // Set aspect ratio\n\n this.embed.ratio = roundAspectRatio(width, height);\n }\n\n setAspectRatio.call(this);\n }).catch(() => {\n // Set aspect ratio\n setAspectRatio.call(this);\n });\n },\n\n // API ready\n ready() {\n const player = this;\n const config = player.config.youtube; // Ignore already setup (race condition)\n\n const currentId = player.media && player.media.getAttribute('id');\n\n if (!is.empty(currentId) && currentId.startsWith('youtube-')) {\n return;\n } // Get the source URL or ID\n\n\n let source = player.media.getAttribute('src'); // Get from <div> if needed\n\n if (is.empty(source)) {\n source = player.media.getAttribute(this.config.attributes.embed.id);\n } // Replace the <iframe> with a <div> due to YouTube API issues\n\n\n const videoId = parseId(source);\n const id = generateId(player.provider); // Replace media element\n\n const container = createElement('div', {\n id,\n 'data-poster': config.customControls ? player.poster : undefined\n });\n player.media = replaceElement(container, player.media); // Only load the poster when using custom controls\n\n if (config.customControls) {\n const posterSrc = s => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`; // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide)\n\n\n loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded\n .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3\n .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists\n .then(image => ui.setPoster.call(player, image.src)).then(src => {\n // If the image is padded, use background-size \"cover\" instead (like youtube does too with their posters)\n if (!src.includes('maxres')) {\n player.elements.poster.style.backgroundSize = 'cover';\n }\n }).catch(() => {});\n } // Setup instance\n // https://developers.google.com/youtube/iframe_api_reference\n\n\n player.embed = new window.YT.Player(player.media, {\n videoId,\n host: getHost(config),\n playerVars: extend({}, {\n // Autoplay\n autoplay: player.config.autoplay ? 1 : 0,\n // iframe interface language\n hl: player.config.hl,\n // Only show controls if not fully supported or opted out\n controls: player.supported.ui && config.customControls ? 0 : 1,\n // Disable keyboard as we handle it\n disablekb: 1,\n // Allow iOS inline playback\n playsinline: !player.config.fullscreen.iosNative ? 1 : 0,\n // Captions are flaky on YouTube\n cc_load_policy: player.captions.active ? 1 : 0,\n cc_lang_pref: player.config.captions.language,\n // Tracking for stats\n widget_referrer: window ? window.location.href : null\n }, config),\n events: {\n onError(event) {\n // YouTube may fire onError twice, so only handle it once\n if (!player.media.error) {\n const code = event.data; // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError\n\n const message = {\n 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.',\n 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.',\n 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.',\n 101: 'The owner of the requested video does not allow it to be played in embedded players.',\n 150: 'The owner of the requested video does not allow it to be played in embedded players.'\n }[code] || 'An unknown error occured';\n player.media.error = {\n code,\n message\n };\n triggerEvent.call(player, player.media, 'error');\n }\n },\n\n onPlaybackRateChange(event) {\n // Get the instance\n const instance = event.target; // Get current speed\n\n player.media.playbackRate = instance.getPlaybackRate();\n triggerEvent.call(player, player.media, 'ratechange');\n },\n\n onReady(event) {\n // Bail if onReady has already been called. See issue #1108\n if (is.function(player.media.play)) {\n return;\n } // Get the instance\n\n\n const instance = event.target; // Get the title\n\n youtube.getTitle.call(player, videoId); // Create a faux HTML5 API using the YouTube API\n\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n instance.playVideo();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n instance.pauseVideo();\n };\n\n player.media.stop = () => {\n instance.stopVideo();\n };\n\n player.media.duration = instance.getDuration();\n player.media.paused = true; // Seeking\n\n player.media.currentTime = 0;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return Number(instance.getCurrentTime());\n },\n\n set(time) {\n // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet).\n if (player.paused && !player.embed.hasPlayed) {\n player.embed.mute();\n } // Set seeking state and trigger event\n\n\n player.media.seeking = true;\n triggerEvent.call(player, player.media, 'seeking'); // Seek after events sent\n\n instance.seekTo(time);\n }\n\n }); // Playback speed\n\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return instance.getPlaybackRate();\n },\n\n set(input) {\n instance.setPlaybackRate(input);\n }\n\n }); // Volume\n\n let {\n volume\n } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n\n set(input) {\n volume = input;\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n }\n\n }); // Muted\n\n let {\n muted\n } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n\n set(input) {\n const toggle = is.boolean(input) ? input : muted;\n muted = toggle;\n instance[toggle ? 'mute' : 'unMute']();\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n }\n\n }); // Source\n\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return instance.getVideoUrl();\n }\n\n }); // Ended\n\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n }\n\n }); // Get available speeds\n\n const speeds = instance.getAvailablePlaybackRates(); // Filter based on config\n\n player.options.speed = speeds.filter(s => player.config.speed.options.includes(s)); // Set the tabindex to avoid focus entering iframe\n\n if (player.supported.ui && config.customControls) {\n player.media.setAttribute('tabindex', -1);\n }\n\n triggerEvent.call(player, player.media, 'timeupdate');\n triggerEvent.call(player, player.media, 'durationchange'); // Reset timer\n\n clearInterval(player.timers.buffering); // Setup buffering\n\n player.timers.buffering = setInterval(() => {\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction(); // Trigger progress only when we actually buffer something\n\n if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) {\n triggerEvent.call(player, player.media, 'progress');\n } // Set last buffer point\n\n\n player.media.lastBuffered = player.media.buffered; // Bail if we're at 100%\n\n if (player.media.buffered === 1) {\n clearInterval(player.timers.buffering); // Trigger event\n\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n }, 200); // Rebuild UI\n\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 50);\n }\n },\n\n onStateChange(event) {\n // Get the instance\n const instance = event.target; // Reset timer\n\n clearInterval(player.timers.playing);\n const seeked = player.media.seeking && [1, 2].includes(event.data);\n\n if (seeked) {\n // Unset seeking and fire seeked event\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n } // Handle events\n // -1 Unstarted\n // 0 Ended\n // 1 Playing\n // 2 Paused\n // 3 Buffering\n // 5 Video cued\n\n\n switch (event.data) {\n case -1:\n // Update scrubber\n triggerEvent.call(player, player.media, 'timeupdate'); // Get loaded % from YouTube\n\n player.media.buffered = instance.getVideoLoadedFraction();\n triggerEvent.call(player, player.media, 'progress');\n break;\n\n case 0:\n assurePlaybackState.call(player, false); // YouTube doesn't support loop for a single video, so mimick it.\n\n if (player.media.loop) {\n // YouTube needs a call to `stopVideo` before playing again\n instance.stopVideo();\n instance.playVideo();\n } else {\n triggerEvent.call(player, player.media, 'ended');\n }\n\n break;\n\n case 1:\n // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet)\n if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) {\n player.media.pause();\n } else {\n assurePlaybackState.call(player, true);\n triggerEvent.call(player, player.media, 'playing'); // Poll to get playback progress\n\n player.timers.playing = setInterval(() => {\n triggerEvent.call(player, player.media, 'timeupdate');\n }, 50); // Check duration again due to YouTube bug\n // https://github.com/sampotts/plyr/issues/374\n // https://code.google.com/p/gdata-issues/issues/detail?id=8690\n\n if (player.media.duration !== instance.getDuration()) {\n player.media.duration = instance.getDuration();\n triggerEvent.call(player, player.media, 'durationchange');\n }\n }\n\n break;\n\n case 2:\n // Restore audio (YouTube starts playing on seek if the video hasn't been played yet)\n if (!player.muted) {\n player.embed.unMute();\n }\n\n assurePlaybackState.call(player, false);\n break;\n\n case 3:\n // Trigger waiting event to add loading classes to container as the video buffers.\n triggerEvent.call(player, player.media, 'waiting');\n break;\n }\n\n triggerEvent.call(player, player.elements.container, 'statechange', false, {\n code: event.data\n });\n }\n\n }\n });\n }\n\n};\n\n// ==========================================================================\nconst media = {\n // Setup media\n setup() {\n // If there's no media, bail\n if (!this.media) {\n this.debug.warn('No media element found!');\n return;\n } // Add type class\n\n\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true); // Add provider class\n\n toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true); // Add video class for embeds\n // This will require changes if audio embeds are added\n\n if (this.isEmbed) {\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true);\n } // Inject the player wrapper\n\n\n if (this.isVideo) {\n // Create the wrapper div\n this.elements.wrapper = createElement('div', {\n class: this.config.classNames.video\n }); // Wrap the video in a container\n\n wrap(this.media, this.elements.wrapper); // Poster image container\n\n this.elements.poster = createElement('div', {\n class: this.config.classNames.poster\n });\n this.elements.wrapper.appendChild(this.elements.poster);\n }\n\n if (this.isHTML5) {\n html5.setup.call(this);\n } else if (this.isYouTube) {\n youtube.setup.call(this);\n } else if (this.isVimeo) {\n vimeo.setup.call(this);\n }\n }\n\n};\n\nconst destroy = instance => {\n // Destroy our adsManager\n if (instance.manager) {\n instance.manager.destroy();\n } // Destroy our adsManager\n\n\n if (instance.elements.displayContainer) {\n instance.elements.displayContainer.destroy();\n }\n\n instance.elements.container.remove();\n};\n\nclass Ads {\n /**\n * Ads constructor.\n * @param {Object} player\n * @return {Ads}\n */\n constructor(player) {\n _defineProperty$1(this, \"load\", () => {\n if (!this.enabled) {\n return;\n } // Check if the Google IMA3 SDK is loaded or load it ourselves\n\n\n if (!is.object(window.google) || !is.object(window.google.ima)) {\n loadScript(this.player.config.urls.googleIMA.sdk).then(() => {\n this.ready();\n }).catch(() => {\n // Script failed to load or is blocked\n this.trigger('error', new Error('Google IMA SDK failed to load'));\n });\n } else {\n this.ready();\n }\n });\n\n _defineProperty$1(this, \"ready\", () => {\n // Double check we're enabled\n if (!this.enabled) {\n destroy(this);\n } // Start ticking our safety timer. If the whole advertisement\n // thing doesn't resolve within our set time; we bail\n\n\n this.startSafetyTimer(12000, 'ready()'); // Clear the safety timer\n\n this.managerPromise.then(() => {\n this.clearSafetyTimer('onAdsManagerLoaded()');\n }); // Set listeners on the Plyr instance\n\n this.listeners(); // Setup the IMA SDK\n\n this.setupIMA();\n });\n\n _defineProperty$1(this, \"setupIMA\", () => {\n // Create the container for our advertisements\n this.elements.container = createElement('div', {\n class: this.player.config.classNames.ads\n });\n this.player.elements.container.appendChild(this.elements.container); // So we can run VPAID2\n\n google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED); // Set language\n\n google.ima.settings.setLocale(this.player.config.ads.language); // Set playback for iOS10+\n\n 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\n\n this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container, this.player.media); // Create ads loader\n\n this.loader = new google.ima.AdsLoader(this.elements.displayContainer); // Listen and respond to ads loaded and error events\n\n this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false);\n this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false); // Request video ads to be pre-loaded\n\n this.requestAds();\n });\n\n _defineProperty$1(this, \"requestAds\", () => {\n const {\n container\n } = this.player.elements;\n\n try {\n // Request video ads\n const request = new google.ima.AdsRequest();\n request.adTagUrl = this.tagUrl; // Specify the linear and nonlinear slot sizes. This helps the SDK\n // to select the correct creative if multiple are returned\n\n request.linearAdSlotWidth = container.offsetWidth;\n request.linearAdSlotHeight = container.offsetHeight;\n request.nonLinearAdSlotWidth = container.offsetWidth;\n request.nonLinearAdSlotHeight = container.offsetHeight; // We only overlay ads as we only support video.\n\n request.forceNonLinearFullSlot = false; // Mute based on current state\n\n request.setAdWillPlayMuted(!this.player.muted);\n this.loader.requestAds(request);\n } catch (error) {\n this.onAdError(error);\n }\n });\n\n _defineProperty$1(this, \"pollCountdown\", (start = false) => {\n if (!start) {\n clearInterval(this.countdownTimer);\n this.elements.container.removeAttribute('data-badge-text');\n return;\n }\n\n const update = () => {\n const time = formatTime(Math.max(this.manager.getRemainingTime(), 0));\n const label = `${i18n.get('advertisement', this.player.config)} - ${time}`;\n this.elements.container.setAttribute('data-badge-text', label);\n };\n\n this.countdownTimer = setInterval(update, 100);\n });\n\n _defineProperty$1(this, \"onAdsManagerLoaded\", event => {\n // Load could occur after a source change (race condition)\n if (!this.enabled) {\n return;\n } // Get the ads manager\n\n\n const settings = new google.ima.AdsRenderingSettings(); // Tell the SDK to save and restore content video state on our behalf\n\n settings.restoreCustomPlaybackStateOnAdBreakComplete = true;\n settings.enablePreloading = true; // The SDK is polling currentTime on the contentPlayback. And needs a duration\n // so it can determine when to start the mid- and post-roll\n\n this.manager = event.getAdsManager(this.player, settings); // Get the cue points for any mid-rolls by filtering out the pre- and post-roll\n\n this.cuePoints = this.manager.getCuePoints(); // Add listeners to the required events\n // Advertisement error events\n\n this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error)); // Advertisement regular events\n\n Object.keys(google.ima.AdEvent.Type).forEach(type => {\n this.manager.addEventListener(google.ima.AdEvent.Type[type], e => this.onAdEvent(e));\n }); // Resolve our adsManager\n\n this.trigger('loaded');\n });\n\n _defineProperty$1(this, \"addCuePoints\", () => {\n // Add advertisement cue's within the time line if available\n if (!is.empty(this.cuePoints)) {\n this.cuePoints.forEach(cuePoint => {\n if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {\n const seekElement = this.player.elements.progress;\n\n if (is.element(seekElement)) {\n const cuePercentage = 100 / this.player.duration * cuePoint;\n const cue = createElement('span', {\n class: this.player.config.classNames.cues\n });\n cue.style.left = `${cuePercentage.toString()}%`;\n seekElement.appendChild(cue);\n }\n }\n });\n }\n });\n\n _defineProperty$1(this, \"onAdEvent\", event => {\n const {\n container\n } = this.player.elements; // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)\n // don't have ad object associated\n\n const ad = event.getAd();\n const adData = event.getAdData(); // Proxy event\n\n const dispatchEvent = type => {\n triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`);\n }; // Bubble the event\n\n\n dispatchEvent(event.type);\n\n switch (event.type) {\n case google.ima.AdEvent.Type.LOADED:\n // This is the first event sent for an ad - it is possible to determine whether the\n // ad is a video ad or an overlay\n this.trigger('loaded'); // Start countdown\n\n this.pollCountdown(true);\n\n if (!ad.isLinear()) {\n // Position AdDisplayContainer correctly for overlay\n ad.width = container.offsetWidth;\n ad.height = container.offsetHeight;\n } // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex());\n // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset());\n\n\n break;\n\n case google.ima.AdEvent.Type.STARTED:\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n break;\n\n case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:\n // All ads for the current videos are done. We can now request new advertisements\n // in case the video is re-played\n // TODO: Example for what happens when a next video in a playlist would be loaded.\n // So here we load a new video when all ads are done.\n // Then we load new ads within a new adsManager. When the video\n // Is started - after - the ads are loaded, then we get ads.\n // You can also easily test cancelling and reloading by running\n // player.ads.cancel() and player.ads.play from the console I guess.\n // this.player.source = {\n // type: 'video',\n // title: 'View From A Blue Moon',\n // sources: [{\n // src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type:\n // 'video/mp4', }], poster:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks:\n // [ { kind: 'captions', label: 'English', srclang: 'en', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',\n // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ],\n // };\n // TODO: So there is still this thing where a video should only be allowed to start\n // playing when the IMA SDK is ready or has failed\n if (this.player.ended) {\n this.loadAds();\n } else {\n // The SDK won't allow new ads to be called without receiving a contentComplete()\n this.loader.contentComplete();\n }\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:\n // This event indicates the ad has started - the video player can adjust the UI,\n // for example display a pause button and remaining time. Fired when content should\n // be paused. This usually happens right before an ad is about to cover the content\n this.pauseContent();\n break;\n\n case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:\n // This event indicates the ad has finished - the video player can perform\n // appropriate UI actions, such as removing the timer for remaining time detection.\n // Fired when content should be resumed. This usually happens when an ad finishes\n // or collapses\n this.pollCountdown();\n this.resumeContent();\n break;\n\n case google.ima.AdEvent.Type.LOG:\n if (adData.adError) {\n this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);\n }\n\n break;\n }\n });\n\n _defineProperty$1(this, \"onAdError\", event => {\n this.cancel();\n this.player.debug.warn('Ads error', event);\n });\n\n _defineProperty$1(this, \"listeners\", () => {\n const {\n container\n } = this.player.elements;\n let time;\n this.player.on('canplay', () => {\n this.addCuePoints();\n });\n this.player.on('ended', () => {\n this.loader.contentComplete();\n });\n this.player.on('timeupdate', () => {\n time = this.player.currentTime;\n });\n this.player.on('seeked', () => {\n const seekedTime = this.player.currentTime;\n\n if (is.empty(this.cuePoints)) {\n return;\n }\n\n this.cuePoints.forEach((cuePoint, index) => {\n if (time < cuePoint && cuePoint < seekedTime) {\n this.manager.discardAdBreak();\n this.cuePoints.splice(index, 1);\n }\n });\n }); // Listen to the resizing of the window. And resize ad accordingly\n // TODO: eventually implement ResizeObserver\n\n window.addEventListener('resize', () => {\n if (this.manager) {\n this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n }\n });\n });\n\n _defineProperty$1(this, \"play\", () => {\n const {\n container\n } = this.player.elements;\n\n if (!this.managerPromise) {\n this.resumeContent();\n } // Play the requested advertisement whenever the adsManager is ready\n\n\n this.managerPromise.then(() => {\n // Set volume to match player\n this.manager.setVolume(this.player.volume); // Initialize the container. Must be done via a user action on mobile devices\n\n this.elements.displayContainer.initialize();\n\n try {\n if (!this.initialized) {\n // Initialize the ads manager. Ad rules playlist will start at this time\n this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will\n // start at this time; the call will be ignored for ad rules\n\n this.manager.start();\n }\n\n this.initialized = true;\n } catch (adError) {\n // An error may be thrown if there was a problem with the\n // VAST response\n this.onAdError(adError);\n }\n }).catch(() => {});\n });\n\n _defineProperty$1(this, \"resumeContent\", () => {\n // Hide the advertisement container\n this.elements.container.style.zIndex = ''; // Ad is stopped\n\n this.playing = false; // Play video\n\n silencePromise(this.player.media.play());\n });\n\n _defineProperty$1(this, \"pauseContent\", () => {\n // Show the advertisement container\n this.elements.container.style.zIndex = 3; // Ad is playing\n\n this.playing = true; // Pause our video.\n\n this.player.media.pause();\n });\n\n _defineProperty$1(this, \"cancel\", () => {\n // Pause our video\n if (this.initialized) {\n this.resumeContent();\n } // Tell our instance that we're done for now\n\n\n this.trigger('error'); // Re-create our adsManager\n\n this.loadAds();\n });\n\n _defineProperty$1(this, \"loadAds\", () => {\n // Tell our adsManager to go bye bye\n this.managerPromise.then(() => {\n // Destroy our adsManager\n if (this.manager) {\n this.manager.destroy();\n } // Re-set our adsManager promises\n\n\n this.managerPromise = new Promise(resolve => {\n this.on('loaded', resolve);\n this.player.debug.log(this.manager);\n }); // Now that the manager has been destroyed set it to also be un-initialized\n\n this.initialized = false; // Now request some new advertisements\n\n this.requestAds();\n }).catch(() => {});\n });\n\n _defineProperty$1(this, \"trigger\", (event, ...args) => {\n const handlers = this.events[event];\n\n if (is.array(handlers)) {\n handlers.forEach(handler => {\n if (is.function(handler)) {\n handler.apply(this, args);\n }\n });\n }\n });\n\n _defineProperty$1(this, \"on\", (event, callback) => {\n if (!is.array(this.events[event])) {\n this.events[event] = [];\n }\n\n this.events[event].push(callback);\n return this;\n });\n\n _defineProperty$1(this, \"startSafetyTimer\", (time, from) => {\n this.player.debug.log(`Safety timer invoked from: ${from}`);\n this.safetyTimer = setTimeout(() => {\n this.cancel();\n this.clearSafetyTimer('startSafetyTimer()');\n }, time);\n });\n\n _defineProperty$1(this, \"clearSafetyTimer\", from => {\n if (!is.nullOrUndefined(this.safetyTimer)) {\n this.player.debug.log(`Safety timer cleared from: ${from}`);\n clearTimeout(this.safetyTimer);\n this.safetyTimer = null;\n }\n });\n\n this.player = player;\n this.config = player.config.ads;\n this.playing = false;\n this.initialized = false;\n this.elements = {\n container: null,\n displayContainer: null\n };\n this.manager = null;\n this.loader = null;\n this.cuePoints = null;\n this.events = {};\n this.safetyTimer = null;\n this.countdownTimer = null; // Setup a promise to resolve when the IMA manager is ready\n\n this.managerPromise = new Promise((resolve, reject) => {\n // The ad is loaded and ready\n this.on('loaded', resolve); // Ads failed\n\n this.on('error', reject);\n });\n this.load();\n }\n\n get enabled() {\n const {\n config\n } = this;\n return this.player.isHTML5 && this.player.isVideo && config.enabled && (!is.empty(config.publisherId) || is.url(config.tagUrl));\n }\n /**\n * Load the IMA SDK\n */\n\n\n // Build the tag URL\n get tagUrl() {\n const {\n config\n } = this;\n\n if (is.url(config.tagUrl)) {\n return config.tagUrl;\n }\n\n const params = {\n AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',\n AV_CHANNELID: '5a0458dc28a06145e4519d21',\n AV_URL: window.location.hostname,\n cb: Date.now(),\n AV_WIDTH: 640,\n AV_HEIGHT: 480,\n AV_CDIM2: config.publisherId\n };\n const base = 'https://go.aniview.com/api/adserver6/vast/';\n return `${base}?${buildUrlParams(params)}`;\n }\n /**\n * In order for the SDK to display ads for our video, we need to tell it where to put them,\n * so here we define our ad container. This div is set up to render on top of the video player.\n * Using the code below, we tell the SDK to render ads within that div. We also provide a\n * handle to the content video player - the SDK will poll the current time of our player to\n * properly place mid-rolls. After we create the ad display container, we initialize it. On\n * mobile devices, this initialization is done as the result of a user action.\n */\n\n\n}\n\nconst parseVtt = vttDataString => {\n const processedList = [];\n const frames = vttDataString.split(/\\r\\n\\r\\n|\\n\\n|\\r\\r/);\n frames.forEach(frame => {\n const result = {};\n const lines = frame.split(/\\r\\n|\\n|\\r/);\n lines.forEach(line => {\n if (!is.number(result.startTime)) {\n // The line with start and end times on it is the first line of interest\n 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\n\n if (matchTimes) {\n result.startTime = Number(matchTimes[1] || 0) * 60 * 60 + Number(matchTimes[2]) * 60 + Number(matchTimes[3]) + Number(`0.${matchTimes[4]}`);\n result.endTime = Number(matchTimes[6] || 0) * 60 * 60 + Number(matchTimes[7]) * 60 + Number(matchTimes[8]) + Number(`0.${matchTimes[9]}`);\n }\n } else if (!is.empty(line.trim()) && is.empty(result.text)) {\n // If we already have the startTime, then we're definitely up to the text line(s)\n const lineSplit = line.trim().split('#xywh=');\n [result.text] = lineSplit; // If there's content in lineSplit[1], then we have sprites. If not, then it's just one frame per image\n\n if (lineSplit[1]) {\n [result.x, result.y, result.w, result.h] = lineSplit[1].split(',');\n }\n }\n });\n\n if (result.text) {\n processedList.push(result);\n }\n });\n return processedList;\n};\n/**\n * Preview thumbnails for seek hover and scrubbing\n * Seeking: Hover over the seek bar (desktop only): shows a small preview container above the seek bar\n * 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\n *\n * Notes:\n * - 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\n * - 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\n * - 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\n */\n\n\nconst fitRatio = (ratio, outer) => {\n const targetRatio = outer.width / outer.height;\n const result = {};\n\n if (ratio > targetRatio) {\n result.width = outer.width;\n result.height = 1 / ratio * outer.width;\n } else {\n result.height = outer.height;\n result.width = ratio * outer.height;\n }\n\n return result;\n};\n\nclass PreviewThumbnails {\n /**\n * PreviewThumbnails constructor.\n * @param {Plyr} player\n * @return {PreviewThumbnails}\n */\n constructor(player) {\n _defineProperty$1(this, \"load\", () => {\n // Toggle the regular seek tooltip\n if (this.player.elements.display.seekTooltip) {\n this.player.elements.display.seekTooltip.hidden = this.enabled;\n }\n\n if (!this.enabled) {\n return;\n }\n\n this.getThumbnails().then(() => {\n if (!this.enabled) {\n return;\n } // Render DOM elements\n\n\n this.render(); // Check to see if thumb container size was specified manually in CSS\n\n this.determineContainerAutoSizing();\n this.loaded = true;\n });\n });\n\n _defineProperty$1(this, \"getThumbnails\", () => {\n return new Promise(resolve => {\n const {\n src\n } = this.player.config.previewThumbnails;\n\n if (is.empty(src)) {\n throw new Error('Missing previewThumbnails.src config attribute');\n } // Resolve promise\n\n\n const sortAndResolve = () => {\n // Sort smallest to biggest (e.g., [120p, 480p, 1080p])\n this.thumbnails.sort((x, y) => x.height - y.height);\n this.player.debug.log('Preview thumbnails', this.thumbnails);\n resolve();\n }; // Via callback()\n\n\n if (is.function(src)) {\n src(thumbnails => {\n this.thumbnails = thumbnails;\n sortAndResolve();\n });\n } // VTT urls\n else {\n // If string, convert into single-element list\n 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\n\n const promises = urls.map(u => this.getThumbnail(u)); // Resolve\n\n Promise.all(promises).then(sortAndResolve);\n }\n });\n });\n\n _defineProperty$1(this, \"getThumbnail\", url => {\n return new Promise(resolve => {\n fetch(url).then(response => {\n const thumbnail = {\n frames: parseVtt(response),\n height: null,\n urlPrefix: ''\n }; // If the URLs don't start with '/', then we need to set their relative path to be the location of the VTT file\n // If the URLs do start with '/', then they obviously don't need a prefix, so it will remain blank\n // If the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file\n\n if (!thumbnail.frames[0].text.startsWith('/') && !thumbnail.frames[0].text.startsWith('http://') && !thumbnail.frames[0].text.startsWith('https://')) {\n thumbnail.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1);\n } // Download the first frame, so that we can determine/set the height of this thumbnailsDef\n\n\n const tempImage = new Image();\n\n tempImage.onload = () => {\n thumbnail.height = tempImage.naturalHeight;\n thumbnail.width = tempImage.naturalWidth;\n this.thumbnails.push(thumbnail);\n resolve();\n };\n\n tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;\n });\n });\n });\n\n _defineProperty$1(this, \"startMove\", event => {\n if (!this.loaded) {\n return;\n }\n\n if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {\n return;\n } // Wait until media has a duration\n\n\n if (!this.player.media.duration) {\n return;\n }\n\n if (event.type === 'touchmove') {\n // Calculate seek hover position as approx video seconds\n this.seekTime = this.player.media.duration * (this.player.elements.inputs.seek.value / 100);\n } else {\n // Calculate seek hover position as approx video seconds\n const clientRect = this.player.elements.progress.getBoundingClientRect();\n const percentage = 100 / clientRect.width * (event.pageX - clientRect.left);\n this.seekTime = this.player.media.duration * (percentage / 100);\n\n if (this.seekTime < 0) {\n // The mousemove fires for 10+px out to the left\n this.seekTime = 0;\n }\n\n if (this.seekTime > this.player.media.duration - 1) {\n // Took 1 second off the duration for safety, because different players can disagree on the real duration of a video\n this.seekTime = this.player.media.duration - 1;\n }\n\n this.mousePosX = event.pageX; // Set time text inside image container\n\n this.elements.thumb.time.innerText = formatTime(this.seekTime);\n } // Download and show image\n\n\n this.showImageAtCurrentTime();\n });\n\n _defineProperty$1(this, \"endMove\", () => {\n this.toggleThumbContainer(false, true);\n });\n\n _defineProperty$1(this, \"startScrubbing\", event => {\n // Only act on left mouse button (0), or touch device (event.button does not exist or is false)\n if (is.nullOrUndefined(event.button) || event.button === false || event.button === 0) {\n this.mouseDown = true; // Wait until media has a duration\n\n if (this.player.media.duration) {\n this.toggleScrubbingContainer(true);\n this.toggleThumbContainer(false, true); // Download and show image\n\n this.showImageAtCurrentTime();\n }\n }\n });\n\n _defineProperty$1(this, \"endScrubbing\", () => {\n this.mouseDown = false; // Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview\n\n if (Math.ceil(this.lastTime) === Math.ceil(this.player.media.currentTime)) {\n // The video was already seeked/loaded at the chosen time - hide immediately\n this.toggleScrubbingContainer(false);\n } else {\n // The video hasn't seeked yet. Wait for that\n once.call(this.player, this.player.media, 'timeupdate', () => {\n // Re-check mousedown - we might have already started scrubbing again\n if (!this.mouseDown) {\n this.toggleScrubbingContainer(false);\n }\n });\n }\n });\n\n _defineProperty$1(this, \"listeners\", () => {\n // 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\n this.player.on('play', () => {\n this.toggleThumbContainer(false, true);\n });\n this.player.on('seeked', () => {\n this.toggleThumbContainer(false);\n });\n this.player.on('timeupdate', () => {\n this.lastTime = this.player.media.currentTime;\n });\n });\n\n _defineProperty$1(this, \"render\", () => {\n // Create HTML element: plyr__preview-thumbnail-container\n this.elements.thumb.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.thumbContainer\n }); // Wrapper for the image for styling\n\n this.elements.thumb.imageContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.imageContainer\n });\n this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer); // Create HTML element, parent+span: time text (e.g., 01:32:00)\n\n const timeContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.timeContainer\n });\n this.elements.thumb.time = createElement('span', {}, '00:00');\n timeContainer.appendChild(this.elements.thumb.time);\n this.elements.thumb.container.appendChild(timeContainer); // Inject the whole thumb\n\n if (is.element(this.player.elements.progress)) {\n this.player.elements.progress.appendChild(this.elements.thumb.container);\n } // Create HTML element: plyr__preview-scrubbing-container\n\n\n this.elements.scrubbing.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.scrubbingContainer\n });\n this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);\n });\n\n _defineProperty$1(this, \"destroy\", () => {\n if (this.elements.thumb.container) {\n this.elements.thumb.container.remove();\n }\n\n if (this.elements.scrubbing.container) {\n this.elements.scrubbing.container.remove();\n }\n });\n\n _defineProperty$1(this, \"showImageAtCurrentTime\", () => {\n if (this.mouseDown) {\n this.setScrubbingContainerSize();\n } else {\n this.setThumbContainerSizeAndPos();\n } // Find the desired thumbnail index\n // TODO: Handle a video longer than the thumbs where thumbNum is null\n\n\n const thumbNum = this.thumbnails[0].frames.findIndex(frame => this.seekTime >= frame.startTime && this.seekTime <= frame.endTime);\n const hasThumb = thumbNum >= 0;\n let qualityIndex = 0; // Show the thumb container if we're not scrubbing\n\n if (!this.mouseDown) {\n this.toggleThumbContainer(hasThumb);\n } // No matching thumb found\n\n\n if (!hasThumb) {\n return;\n } // Check to see if we've already downloaded higher quality versions of this image\n\n\n this.thumbnails.forEach((thumbnail, index) => {\n if (this.loadedImages.includes(thumbnail.frames[thumbNum].text)) {\n qualityIndex = index;\n }\n }); // Only proceed if either thumbnum or thumbfilename has changed\n\n if (thumbNum !== this.showingThumb) {\n this.showingThumb = thumbNum;\n this.loadImage(qualityIndex);\n }\n });\n\n _defineProperty$1(this, \"loadImage\", (qualityIndex = 0) => {\n const thumbNum = this.showingThumb;\n const thumbnail = this.thumbnails[qualityIndex];\n const {\n urlPrefix\n } = thumbnail;\n const frame = thumbnail.frames[thumbNum];\n const thumbFilename = thumbnail.frames[thumbNum].text;\n const thumbUrl = urlPrefix + thumbFilename;\n\n if (!this.currentImageElement || this.currentImageElement.dataset.filename !== thumbFilename) {\n // If we're already loading a previous image, remove its onload handler - we don't want it to load after this one\n // Only do this if not using sprites. Without sprites we really want to show as many images as possible, as a best-effort\n if (this.loadingImage && this.usingSprites) {\n this.loadingImage.onload = null;\n } // We're building and adding a new image. In other implementations of similar functionality (YouTube), background image\n // is instead used. But this causes issues with larger images in Firefox and Safari - switching between background\n // images causes a flicker. Putting a new image over the top does not\n\n\n const previewImage = new Image();\n previewImage.src = thumbUrl;\n previewImage.dataset.index = thumbNum;\n previewImage.dataset.filename = thumbFilename;\n this.showingThumbFilename = thumbFilename;\n 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...\n\n previewImage.onload = () => this.showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, true);\n\n this.loadingImage = previewImage;\n this.removeOldImages(previewImage);\n } else {\n // Update the existing image\n this.showImage(this.currentImageElement, frame, qualityIndex, thumbNum, thumbFilename, false);\n this.currentImageElement.dataset.index = thumbNum;\n this.removeOldImages(this.currentImageElement);\n }\n });\n\n _defineProperty$1(this, \"showImage\", (previewImage, frame, qualityIndex, thumbNum, thumbFilename, newImage = true) => {\n this.player.debug.log(`Showing thumb: ${thumbFilename}. num: ${thumbNum}. qual: ${qualityIndex}. newimg: ${newImage}`);\n this.setImageSizeAndOffset(previewImage, frame);\n\n if (newImage) {\n this.currentImageContainer.appendChild(previewImage);\n this.currentImageElement = previewImage;\n\n if (!this.loadedImages.includes(thumbFilename)) {\n this.loadedImages.push(thumbFilename);\n }\n } // Preload images before and after the current one\n // Show higher quality of the same frame\n // 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\n\n\n this.preloadNearby(thumbNum, true).then(this.preloadNearby(thumbNum, false)).then(this.getHigherQuality(qualityIndex, previewImage, frame, thumbFilename));\n });\n\n _defineProperty$1(this, \"removeOldImages\", currentImage => {\n // Get a list of all images, convert it from a DOM list to an array\n Array.from(this.currentImageContainer.children).forEach(image => {\n if (image.tagName.toLowerCase() !== 'img') {\n return;\n }\n\n const removeDelay = this.usingSprites ? 500 : 1000;\n\n if (image.dataset.index !== currentImage.dataset.index && !image.dataset.deleting) {\n // 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\n // First set attribute 'deleting' to prevent multi-handling of this on repeat firing of this function\n // eslint-disable-next-line no-param-reassign\n image.dataset.deleting = true; // This has to be set before the timeout - to prevent issues switching between hover and scrub\n\n const {\n currentImageContainer\n } = this;\n setTimeout(() => {\n currentImageContainer.removeChild(image);\n this.player.debug.log(`Removing thumb: ${image.dataset.filename}`);\n }, removeDelay);\n }\n });\n });\n\n _defineProperty$1(this, \"preloadNearby\", (thumbNum, forward = true) => {\n return new Promise(resolve => {\n setTimeout(() => {\n const oldThumbFilename = this.thumbnails[0].frames[thumbNum].text;\n\n if (this.showingThumbFilename === oldThumbFilename) {\n // 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\n let thumbnailsClone;\n\n if (forward) {\n thumbnailsClone = this.thumbnails[0].frames.slice(thumbNum);\n } else {\n thumbnailsClone = this.thumbnails[0].frames.slice(0, thumbNum).reverse();\n }\n\n let foundOne = false;\n thumbnailsClone.forEach(frame => {\n const newThumbFilename = frame.text;\n\n if (newThumbFilename !== oldThumbFilename) {\n // Found one with a different filename. Make sure it hasn't already been loaded on this page visit\n if (!this.loadedImages.includes(newThumbFilename)) {\n foundOne = true;\n this.player.debug.log(`Preloading thumb filename: ${newThumbFilename}`);\n const {\n urlPrefix\n } = this.thumbnails[0];\n const thumbURL = urlPrefix + newThumbFilename;\n const previewImage = new Image();\n previewImage.src = thumbURL;\n\n previewImage.onload = () => {\n this.player.debug.log(`Preloaded thumb filename: ${newThumbFilename}`);\n if (!this.loadedImages.includes(newThumbFilename)) this.loadedImages.push(newThumbFilename); // We don't resolve until the thumb is loaded\n\n resolve();\n };\n }\n }\n }); // If there are none to preload then we want to resolve immediately\n\n if (!foundOne) {\n resolve();\n }\n }\n }, 300);\n });\n });\n\n _defineProperty$1(this, \"getHigherQuality\", (currentQualityIndex, previewImage, frame, thumbFilename) => {\n if (currentQualityIndex < this.thumbnails.length - 1) {\n // 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\n let previewImageHeight = previewImage.naturalHeight;\n\n if (this.usingSprites) {\n previewImageHeight = frame.h;\n }\n\n if (previewImageHeight < this.thumbContainerHeight) {\n // Recurse back to the loadImage function - show a higher quality one, but only if the viewer is on this frame for a while\n setTimeout(() => {\n // Make sure the mouse hasn't already moved on and started hovering at another image\n if (this.showingThumbFilename === thumbFilename) {\n this.player.debug.log(`Showing higher quality thumb for: ${thumbFilename}`);\n this.loadImage(currentQualityIndex + 1);\n }\n }, 300);\n }\n }\n });\n\n _defineProperty$1(this, \"toggleThumbContainer\", (toggle = false, clearShowing = false) => {\n const className = this.player.config.classNames.previewThumbnails.thumbContainerShown;\n this.elements.thumb.container.classList.toggle(className, toggle);\n\n if (!toggle && clearShowing) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n });\n\n _defineProperty$1(this, \"toggleScrubbingContainer\", (toggle = false) => {\n const className = this.player.config.classNames.previewThumbnails.scrubbingContainerShown;\n this.elements.scrubbing.container.classList.toggle(className, toggle);\n\n if (!toggle) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n });\n\n _defineProperty$1(this, \"determineContainerAutoSizing\", () => {\n if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) {\n // This will prevent auto sizing in this.setThumbContainerSizeAndPos()\n this.sizeSpecifiedInCSS = true;\n }\n });\n\n _defineProperty$1(this, \"setThumbContainerSizeAndPos\", () => {\n if (!this.sizeSpecifiedInCSS) {\n const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${this.thumbContainerHeight}px`;\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (this.elements.thumb.imageContainer.clientHeight > 20 && this.elements.thumb.imageContainer.clientWidth < 20) {\n const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (this.elements.thumb.imageContainer.clientHeight < 20 && this.elements.thumb.imageContainer.clientWidth > 20) {\n const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`;\n }\n\n this.setThumbContainerPos();\n });\n\n _defineProperty$1(this, \"setThumbContainerPos\", () => {\n const seekbarRect = this.player.elements.progress.getBoundingClientRect();\n const plyrRect = this.player.elements.container.getBoundingClientRect();\n const {\n container\n } = this.elements.thumb; // Find the lowest and highest desired left-position, so we don't slide out the side of the video container\n\n const minVal = plyrRect.left - seekbarRect.left + 10;\n const maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10; // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth\n\n let previewPos = this.mousePosX - seekbarRect.left - container.clientWidth / 2;\n\n if (previewPos < minVal) {\n previewPos = minVal;\n }\n\n if (previewPos > maxVal) {\n previewPos = maxVal;\n }\n\n container.style.left = `${previewPos}px`;\n });\n\n _defineProperty$1(this, \"setScrubbingContainerSize\", () => {\n const {\n width,\n height\n } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight\n });\n this.elements.scrubbing.container.style.width = `${width}px`;\n this.elements.scrubbing.container.style.height = `${height}px`;\n });\n\n _defineProperty$1(this, \"setImageSizeAndOffset\", (previewImage, frame) => {\n if (!this.usingSprites) {\n return;\n } // Find difference between height and preview container height\n\n\n const multiplier = this.thumbContainerHeight / frame.h; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.left = `-${frame.x * multiplier}px`; // eslint-disable-next-line no-param-reassign\n\n previewImage.style.top = `-${frame.y * multiplier}px`;\n });\n\n this.player = player;\n this.thumbnails = [];\n this.loaded = false;\n this.lastMouseMoveTime = Date.now();\n this.mouseDown = false;\n this.loadedImages = [];\n this.elements = {\n thumb: {},\n scrubbing: {}\n };\n this.load();\n }\n\n get enabled() {\n return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;\n }\n\n get currentImageContainer() {\n if (this.mouseDown) {\n return this.elements.scrubbing.container;\n }\n\n return this.elements.thumb.imageContainer;\n }\n\n get usingSprites() {\n return Object.keys(this.thumbnails[0].frames[0]).includes('w');\n }\n\n get thumbAspectRatio() {\n if (this.usingSprites) {\n return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;\n }\n\n return this.thumbnails[0].width / this.thumbnails[0].height;\n }\n\n get thumbContainerHeight() {\n if (this.mouseDown) {\n const {\n height\n } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight\n });\n return height;\n } // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset)\n\n\n if (this.sizeSpecifiedInCSS) {\n return this.elements.thumb.imageContainer.clientHeight;\n }\n\n return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);\n }\n\n get currentImageElement() {\n if (this.mouseDown) {\n return this.currentScrubbingImageElement;\n }\n\n return this.currentThumbnailImageElement;\n }\n\n set currentImageElement(element) {\n if (this.mouseDown) {\n this.currentScrubbingImageElement = element;\n } else {\n this.currentThumbnailImageElement = element;\n }\n }\n\n}\n\n// ==========================================================================\nconst source = {\n // Add elements to HTML5 media (source, tracks, etc)\n insertElements(type, attributes) {\n if (is.string(attributes)) {\n insertElement(type, this.media, {\n src: attributes\n });\n } else if (is.array(attributes)) {\n attributes.forEach(attribute => {\n insertElement(type, this.media, attribute);\n });\n }\n },\n\n // Update source\n // Sources are not checked for support so be careful\n change(input) {\n if (!getDeep(input, 'sources.length')) {\n this.debug.warn('Invalid source format');\n return;\n } // Cancel current network requests\n\n\n html5.cancelRequests.call(this); // Destroy instance and re-setup\n\n this.destroy.call(this, () => {\n // Reset quality options\n this.options.quality = []; // Remove elements\n\n removeElement(this.media);\n this.media = null; // Reset class name\n\n if (is.element(this.elements.container)) {\n this.elements.container.removeAttribute('class');\n } // Set the type and provider\n\n\n const {\n sources,\n type\n } = input;\n const [{\n provider = providers.html5,\n src\n }] = sources;\n const tagName = provider === 'html5' ? type : 'div';\n const attributes = provider === 'html5' ? {} : {\n src\n };\n Object.assign(this, {\n provider,\n type,\n // Check for support\n supported: support.check(type, provider, this.config.playsinline),\n // Create new element\n media: createElement(tagName, attributes)\n }); // Inject the new element\n\n this.elements.container.appendChild(this.media); // Autoplay the new source?\n\n if (is.boolean(input.autoplay)) {\n this.config.autoplay = input.autoplay;\n } // Set attributes for audio and video\n\n\n if (this.isHTML5) {\n if (this.config.crossorigin) {\n this.media.setAttribute('crossorigin', '');\n }\n\n if (this.config.autoplay) {\n this.media.setAttribute('autoplay', '');\n }\n\n if (!is.empty(input.poster)) {\n this.poster = input.poster;\n }\n\n if (this.config.loop.active) {\n this.media.setAttribute('loop', '');\n }\n\n if (this.config.muted) {\n this.media.setAttribute('muted', '');\n }\n\n if (this.config.playsinline) {\n this.media.setAttribute('playsinline', '');\n }\n } // Restore class hook\n\n\n ui.addStyleHook.call(this); // Set new sources for html5\n\n if (this.isHTML5) {\n source.insertElements.call(this, 'source', sources);\n } // Set video title\n\n\n this.config.title = input.title; // Set up from scratch\n\n media.setup.call(this); // HTML5 stuff\n\n if (this.isHTML5) {\n // Setup captions\n if (Object.keys(input).includes('tracks')) {\n source.insertElements.call(this, 'track', input.tracks);\n }\n } // If HTML5 or embed but not fully supported, setupInterface and call ready now\n\n\n if (this.isHTML5 || this.isEmbed && !this.supported.ui) {\n // Setup interface\n ui.build.call(this);\n } // Load HTML5 sources\n\n\n if (this.isHTML5) {\n this.media.load();\n } // Update previewThumbnails config & reload plugin\n\n\n if (!is.empty(input.previewThumbnails)) {\n Object.assign(this.config.previewThumbnails, input.previewThumbnails); // Cleanup previewThumbnails plugin if it was loaded\n\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n } // Create new instance if it is still enabled\n\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n } // Update the fullscreen support\n\n\n this.fullscreen.update();\n }, true);\n }\n\n};\n\n/**\n * Returns a number whose value is limited to the given range.\n *\n * Example: limit the output of this computation to between 0 and 255\n * (x * 255).clamp(0, 255)\n *\n * @param {Number} input\n * @param {Number} min The lower boundary of the output range\n * @param {Number} max The upper boundary of the output range\n * @returns A number in the range [min, max]\n * @type Number\n */\nfunction clamp(input = 0, min = 0, max = 255) {\n return Math.min(Math.max(input, min), max);\n}\n\n// TODO: Use a WeakMap for private globals\n// const globals = new WeakMap();\n// Plyr instance\n\nclass Plyr {\n constructor(target, options) {\n _defineProperty$1(this, \"play\", () => {\n if (!is.function(this.media.play)) {\n return null;\n } // Intecept play with ads\n\n\n if (this.ads && this.ads.enabled) {\n this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play()));\n } // Return the promise (for HTML5)\n\n\n return this.media.play();\n });\n\n _defineProperty$1(this, \"pause\", () => {\n if (!this.playing || !is.function(this.media.pause)) {\n return null;\n }\n\n return this.media.pause();\n });\n\n _defineProperty$1(this, \"togglePlay\", input => {\n // Toggle based on current state if nothing passed\n const toggle = is.boolean(input) ? input : !this.playing;\n\n if (toggle) {\n return this.play();\n }\n\n return this.pause();\n });\n\n _defineProperty$1(this, \"stop\", () => {\n if (this.isHTML5) {\n this.pause();\n this.restart();\n } else if (is.function(this.media.stop)) {\n this.media.stop();\n }\n });\n\n _defineProperty$1(this, \"restart\", () => {\n this.currentTime = 0;\n });\n\n _defineProperty$1(this, \"rewind\", seekTime => {\n this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime;\n });\n\n _defineProperty$1(this, \"forward\", seekTime => {\n this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime;\n });\n\n _defineProperty$1(this, \"increaseVolume\", step => {\n const volume = this.media.muted ? 0 : this.volume;\n this.volume = volume + (is.number(step) ? step : 0);\n });\n\n _defineProperty$1(this, \"decreaseVolume\", step => {\n this.increaseVolume(-step);\n });\n\n _defineProperty$1(this, \"airplay\", () => {\n // Show dialog if supported\n if (support.airplay) {\n this.media.webkitShowPlaybackTargetPicker();\n }\n });\n\n _defineProperty$1(this, \"toggleControls\", toggle => {\n // Don't toggle if missing UI support or if it's audio\n if (this.supported.ui && !this.isAudio) {\n // Get state before change\n const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls); // Negate the argument if not undefined since adding the class to hides the controls\n\n const force = typeof toggle === 'undefined' ? undefined : !toggle; // Apply and get updated state\n\n const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force); // Close menu\n\n if (hiding && is.array(this.config.controls) && this.config.controls.includes('settings') && !is.empty(this.config.settings)) {\n controls.toggleMenu.call(this, false);\n } // Trigger event on change\n\n\n if (hiding !== isHidden) {\n const eventName = hiding ? 'controlshidden' : 'controlsshown';\n triggerEvent.call(this, this.media, eventName);\n }\n\n return !hiding;\n }\n\n return false;\n });\n\n _defineProperty$1(this, \"on\", (event, callback) => {\n on.call(this, this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"once\", (event, callback) => {\n once.call(this, this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"off\", (event, callback) => {\n off(this.elements.container, event, callback);\n });\n\n _defineProperty$1(this, \"destroy\", (callback, soft = false) => {\n if (!this.ready) {\n return;\n }\n\n const done = () => {\n // Reset overflow (incase destroyed while in fullscreen)\n document.body.style.overflow = ''; // GC for embed\n\n this.embed = null; // If it's a soft destroy, make minimal changes\n\n if (soft) {\n if (Object.keys(this.elements).length) {\n // Remove elements\n removeElement(this.elements.buttons.play);\n removeElement(this.elements.captions);\n removeElement(this.elements.controls);\n removeElement(this.elements.wrapper); // Clear for GC\n\n this.elements.buttons.play = null;\n this.elements.captions = null;\n this.elements.controls = null;\n this.elements.wrapper = null;\n } // Callback\n\n\n if (is.function(callback)) {\n callback();\n }\n } else {\n // Unbind listeners\n unbindListeners.call(this); // Cancel current network requests\n\n html5.cancelRequests.call(this); // Replace the container with the original element provided\n\n replaceElement(this.elements.original, this.elements.container); // Event\n\n triggerEvent.call(this, this.elements.original, 'destroyed', true); // Callback\n\n if (is.function(callback)) {\n callback.call(this.elements.original);\n } // Reset state\n\n\n this.ready = false; // Clear for garbage collection\n\n setTimeout(() => {\n this.elements = null;\n this.media = null;\n }, 200);\n }\n }; // Stop playback\n\n\n this.stop(); // Clear timeouts\n\n clearTimeout(this.timers.loading);\n clearTimeout(this.timers.controls);\n clearTimeout(this.timers.resized); // Provider specific stuff\n\n if (this.isHTML5) {\n // Restore native video controls\n ui.toggleNativeControls.call(this, true); // Clean up\n\n done();\n } else if (this.isYouTube) {\n // Clear timers\n clearInterval(this.timers.buffering);\n clearInterval(this.timers.playing); // Destroy YouTube API\n\n if (this.embed !== null && is.function(this.embed.destroy)) {\n this.embed.destroy();\n } // Clean up\n\n\n done();\n } else if (this.isVimeo) {\n // Destroy Vimeo API\n // then clean up (wait, to prevent postmessage errors)\n if (this.embed !== null) {\n this.embed.unload().then(done);\n } // Vimeo does not always return\n\n\n setTimeout(done, 200);\n }\n });\n\n _defineProperty$1(this, \"supports\", type => support.mime.call(this, type));\n\n this.timers = {}; // State\n\n this.ready = false;\n this.loading = false;\n this.failed = false; // Touch device\n\n this.touch = support.touch; // Set the media element\n\n this.media = target; // String selector passed\n\n if (is.string(this.media)) {\n this.media = document.querySelectorAll(this.media);\n } // jQuery, NodeList or Array passed, use first element\n\n\n if (window.jQuery && this.media instanceof jQuery || is.nodeList(this.media) || is.array(this.media)) {\n // eslint-disable-next-line\n this.media = this.media[0];\n } // Set config\n\n\n this.config = extend({}, defaults, Plyr.defaults, options || {}, (() => {\n try {\n return JSON.parse(this.media.getAttribute('data-plyr-config'));\n } catch (_) {\n return {};\n }\n })()); // Elements cache\n\n this.elements = {\n container: null,\n fullscreen: null,\n captions: null,\n buttons: {},\n display: {},\n progress: {},\n inputs: {},\n settings: {\n popup: null,\n menu: null,\n panels: {},\n buttons: {}\n }\n }; // Captions\n\n this.captions = {\n active: null,\n currentTrack: -1,\n meta: new WeakMap()\n }; // Fullscreen\n\n this.fullscreen = {\n active: false\n }; // Options\n\n this.options = {\n speed: [],\n quality: []\n }; // Debugging\n // TODO: move to globals\n\n this.debug = new Console(this.config.debug); // Log config options and support\n\n this.debug.log('Config', this.config);\n this.debug.log('Support', support); // We need an element to setup\n\n if (is.nullOrUndefined(this.media) || !is.element(this.media)) {\n this.debug.error('Setup failed: no suitable element passed');\n return;\n } // Bail if the element is initialized\n\n\n if (this.media.plyr) {\n this.debug.warn('Target already setup');\n return;\n } // Bail if not enabled\n\n\n if (!this.config.enabled) {\n this.debug.error('Setup failed: disabled by config');\n return;\n } // Bail if disabled or no basic support\n // You may want to disable certain UAs etc\n\n\n if (!support.check().api) {\n this.debug.error('Setup failed: no support');\n return;\n } // Cache original element state for .destroy()\n\n\n const clone = this.media.cloneNode(true);\n clone.autoplay = false;\n this.elements.original = clone; // Set media type based on tag or data attribute\n // Supported: video, audio, vimeo, youtube\n\n const _type = this.media.tagName.toLowerCase(); // Embed properties\n\n\n let iframe = null;\n let url = null; // Different setup based on type\n\n switch (_type) {\n case 'div':\n // Find the frame\n iframe = this.media.querySelector('iframe'); // <iframe> type\n\n if (is.element(iframe)) {\n // Detect provider\n url = parseUrl(iframe.getAttribute('src'));\n this.provider = getProviderByUrl(url.toString()); // Rework elements\n\n this.elements.container = this.media;\n this.media = iframe; // Reset classname\n\n this.elements.container.className = ''; // Get attributes from URL and set config\n\n if (url.search.length) {\n const truthy = ['1', 'true'];\n\n if (truthy.includes(url.searchParams.get('autoplay'))) {\n this.config.autoplay = true;\n }\n\n if (truthy.includes(url.searchParams.get('loop'))) {\n this.config.loop.active = true;\n } // TODO: replace fullscreen.iosNative with this playsinline config option\n // YouTube requires the playsinline in the URL\n\n\n if (this.isYouTube) {\n this.config.playsinline = truthy.includes(url.searchParams.get('playsinline'));\n this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language?\n } else {\n this.config.playsinline = true;\n }\n }\n } else {\n // <div> with attributes\n this.provider = this.media.getAttribute(this.config.attributes.embed.provider); // Remove attribute\n\n this.media.removeAttribute(this.config.attributes.embed.provider);\n } // Unsupported or missing provider\n\n\n if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) {\n this.debug.error('Setup failed: Invalid provider');\n return;\n } // Audio will come later for external providers\n\n\n this.type = types.video;\n break;\n\n case 'video':\n case 'audio':\n this.type = _type;\n this.provider = providers.html5; // Get config from attributes\n\n if (this.media.hasAttribute('crossorigin')) {\n this.config.crossorigin = true;\n }\n\n if (this.media.hasAttribute('autoplay')) {\n this.config.autoplay = true;\n }\n\n if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) {\n this.config.playsinline = true;\n }\n\n if (this.media.hasAttribute('muted')) {\n this.config.muted = true;\n }\n\n if (this.media.hasAttribute('loop')) {\n this.config.loop.active = true;\n }\n\n break;\n\n default:\n this.debug.error('Setup failed: unsupported type');\n return;\n } // Check for support again but with type\n\n\n this.supported = support.check(this.type, this.provider, this.config.playsinline); // If no support for even API, bail\n\n if (!this.supported.api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n this.eventListeners = []; // Create listeners\n\n this.listeners = new Listeners(this); // Setup local storage for user settings\n\n this.storage = new Storage(this); // Store reference\n\n this.media.plyr = this; // Wrap media\n\n if (!is.element(this.elements.container)) {\n this.elements.container = createElement('div', {\n tabindex: 0\n });\n wrap(this.media, this.elements.container);\n } // Migrate custom properties from media to container (so they work 😉)\n\n\n ui.migrateStyles.call(this); // Add style hook\n\n ui.addStyleHook.call(this); // Setup media\n\n media.setup.call(this); // Listen for events if debugging\n\n if (this.config.debug) {\n on.call(this, this.elements.container, this.config.events.join(' '), event => {\n this.debug.log(`event: ${event.type}`);\n });\n } // Setup fullscreen\n\n\n this.fullscreen = new Fullscreen(this); // Setup interface\n // If embed but not fully supported, build interface now to avoid flash of controls\n\n if (this.isHTML5 || this.isEmbed && !this.supported.ui) {\n ui.build.call(this);\n } // Container listeners\n\n\n this.listeners.container(); // Global listeners\n\n this.listeners.global(); // Setup ads if provided\n\n if (this.config.ads.enabled) {\n this.ads = new Ads(this);\n } // Autoplay if required\n\n\n if (this.isHTML5 && this.config.autoplay) {\n this.once('canplay', () => silencePromise(this.play()));\n } // Seek time will be recorded (in listeners.js) so we can prevent hiding controls for a few seconds after seek\n\n\n this.lastSeekTime = 0; // Setup preview thumbnails if enabled\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n } // ---------------------------------------\n // API\n // ---------------------------------------\n\n /**\n * Types and provider helpers\n */\n\n\n get isHTML5() {\n return this.provider === providers.html5;\n }\n\n get isEmbed() {\n return this.isYouTube || this.isVimeo;\n }\n\n get isYouTube() {\n return this.provider === providers.youtube;\n }\n\n get isVimeo() {\n return this.provider === providers.vimeo;\n }\n\n get isVideo() {\n return this.type === types.video;\n }\n\n get isAudio() {\n return this.type === types.audio;\n }\n /**\n * Play the media, or play the advertisement (if they are not blocked)\n */\n\n\n /**\n * Get playing state\n */\n get playing() {\n return Boolean(this.ready && !this.paused && !this.ended);\n }\n /**\n * Get paused state\n */\n\n\n get paused() {\n return Boolean(this.media.paused);\n }\n /**\n * Get stopped state\n */\n\n\n get stopped() {\n return Boolean(this.paused && this.currentTime === 0);\n }\n /**\n * Get ended state\n */\n\n\n get ended() {\n return Boolean(this.media.ended);\n }\n /**\n * Toggle playback based on current status\n * @param {Boolean} input\n */\n\n\n /**\n * Seek to a time\n * @param {Number} input - where to seek to in seconds. Defaults to 0 (the start)\n */\n set currentTime(input) {\n // Bail if media duration isn't available yet\n if (!this.duration) {\n return;\n } // Validate input\n\n\n const inputIsValid = is.number(input) && input > 0; // Set\n\n this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0; // Logging\n\n this.debug.log(`Seeking to ${this.currentTime} seconds`);\n }\n /**\n * Get current time\n */\n\n\n get currentTime() {\n return Number(this.media.currentTime);\n }\n /**\n * Get buffered\n */\n\n\n get buffered() {\n const {\n buffered\n } = this.media; // YouTube / Vimeo return a float between 0-1\n\n if (is.number(buffered)) {\n return buffered;\n } // HTML5\n // TODO: Handle buffered chunks of the media\n // (i.e. seek to another section buffers only that section)\n\n\n if (buffered && buffered.length && this.duration > 0) {\n return buffered.end(0) / this.duration;\n }\n\n return 0;\n }\n /**\n * Get seeking status\n */\n\n\n get seeking() {\n return Boolean(this.media.seeking);\n }\n /**\n * Get the duration of the current media\n */\n\n\n get duration() {\n // Faux duration set via config\n const fauxDuration = parseFloat(this.config.duration); // Media duration can be NaN or Infinity before the media has loaded\n\n const realDuration = (this.media || {}).duration;\n const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration; // If config duration is funky, use regular duration\n\n return fauxDuration || duration;\n }\n /**\n * Set the player volume\n * @param {Number} value - must be between 0 and 1. Defaults to the value from local storage and config.volume if not set in storage\n */\n\n\n set volume(value) {\n let volume = value;\n const max = 1;\n const min = 0;\n\n if (is.string(volume)) {\n volume = Number(volume);\n } // Load volume from storage if no value specified\n\n\n if (!is.number(volume)) {\n volume = this.storage.get('volume');\n } // Use config if all else fails\n\n\n if (!is.number(volume)) {\n ({\n volume\n } = this.config);\n } // Maximum is volumeMax\n\n\n if (volume > max) {\n volume = max;\n } // Minimum is volumeMin\n\n\n if (volume < min) {\n volume = min;\n } // Update config\n\n\n this.config.volume = volume; // Set the player volume\n\n this.media.volume = volume; // If muted, and we're increasing volume manually, reset muted state\n\n if (!is.empty(value) && this.muted && volume > 0) {\n this.muted = false;\n }\n }\n /**\n * Get the current player volume\n */\n\n\n get volume() {\n return Number(this.media.volume);\n }\n /**\n * Increase volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n\n\n /**\n * Set muted state\n * @param {Boolean} mute\n */\n set muted(mute) {\n let toggle = mute; // Load muted state from storage\n\n if (!is.boolean(toggle)) {\n toggle = this.storage.get('muted');\n } // Use config if all else fails\n\n\n if (!is.boolean(toggle)) {\n toggle = this.config.muted;\n } // Update config\n\n\n this.config.muted = toggle; // Set mute on the player\n\n this.media.muted = toggle;\n }\n /**\n * Get current muted state\n */\n\n\n get muted() {\n return Boolean(this.media.muted);\n }\n /**\n * Check if the media has audio\n */\n\n\n get hasAudio() {\n // Assume yes for all non HTML5 (as we can't tell...)\n if (!this.isHTML5) {\n return true;\n }\n\n if (this.isAudio) {\n return true;\n } // Get audio tracks\n\n\n return Boolean(this.media.mozHasAudio) || Boolean(this.media.webkitAudioDecodedByteCount) || Boolean(this.media.audioTracks && this.media.audioTracks.length);\n }\n /**\n * Set playback speed\n * @param {Number} speed - the speed of playback (0.5-2.0)\n */\n\n\n set speed(input) {\n let speed = null;\n\n if (is.number(input)) {\n speed = input;\n }\n\n if (!is.number(speed)) {\n speed = this.storage.get('speed');\n }\n\n if (!is.number(speed)) {\n speed = this.config.speed.selected;\n } // Clamp to min/max\n\n\n const {\n minimumSpeed: min,\n maximumSpeed: max\n } = this;\n speed = clamp(speed, min, max); // Update config\n\n this.config.speed.selected = speed; // Set media speed\n\n setTimeout(() => {\n if (this.media) {\n this.media.playbackRate = speed;\n }\n }, 0);\n }\n /**\n * Get current playback speed\n */\n\n\n get speed() {\n return Number(this.media.playbackRate);\n }\n /**\n * Get the minimum allowed speed\n */\n\n\n get minimumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.min(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 0.5;\n } // https://stackoverflow.com/a/32320020/1191319\n\n\n return 0.0625;\n }\n /**\n * Get the maximum allowed speed\n */\n\n\n get maximumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.max(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 2;\n } // https://stackoverflow.com/a/32320020/1191319\n\n\n return 16;\n }\n /**\n * Set playback quality\n * Currently HTML5 & YouTube only\n * @param {Number} input - Quality level\n */\n\n\n set quality(input) {\n const config = this.config.quality;\n const options = this.options.quality;\n\n if (!options.length) {\n return;\n }\n\n let quality = [!is.empty(input) && Number(input), this.storage.get('quality'), config.selected, config.default].find(is.number);\n let updateStorage = true;\n\n if (!options.includes(quality)) {\n const value = closest(options, quality);\n this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`);\n quality = value; // Don't update storage if quality is not supported\n\n updateStorage = false;\n } // Update config\n\n\n config.selected = quality; // Set quality\n\n this.media.quality = quality; // Save to storage\n\n if (updateStorage) {\n this.storage.set({\n quality\n });\n }\n }\n /**\n * Get current quality level\n */\n\n\n get quality() {\n return this.media.quality;\n }\n /**\n * Toggle loop\n * TODO: Finish fancy new logic. Set the indicator on load as user may pass loop as config\n * @param {Boolean} input - Whether to loop or not\n */\n\n\n set loop(input) {\n const toggle = is.boolean(input) ? input : this.config.loop.active;\n this.config.loop.active = toggle;\n this.media.loop = toggle; // Set default to be a true toggle\n\n /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle';\n switch (type) {\n case 'start':\n if (this.config.loop.end && this.config.loop.end <= this.currentTime) {\n this.config.loop.end = null;\n }\n this.config.loop.start = this.currentTime;\n // this.config.loop.indicator.start = this.elements.display.played.value;\n break;\n case 'end':\n if (this.config.loop.start >= this.currentTime) {\n return this;\n }\n this.config.loop.end = this.currentTime;\n // this.config.loop.indicator.end = this.elements.display.played.value;\n break;\n case 'all':\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n this.config.loop.indicator.start = 0;\n this.config.loop.indicator.end = 100;\n break;\n case 'toggle':\n if (this.config.loop.active) {\n this.config.loop.start = 0;\n this.config.loop.end = null;\n } else {\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n }\n break;\n default:\n this.config.loop.start = 0;\n this.config.loop.end = null;\n break;\n } */\n }\n /**\n * Get current loop state\n */\n\n\n get loop() {\n return Boolean(this.media.loop);\n }\n /**\n * Set new media source\n * @param {Object} input - The new source object (see docs)\n */\n\n\n set source(input) {\n source.change.call(this, input);\n }\n /**\n * Get current source\n */\n\n\n get source() {\n return this.media.currentSrc;\n }\n /**\n * Get a download URL (either source or custom)\n */\n\n\n get download() {\n const {\n download\n } = this.config.urls;\n return is.url(download) ? download : this.source;\n }\n /**\n * Set the download URL\n */\n\n\n set download(input) {\n if (!is.url(input)) {\n return;\n }\n\n this.config.urls.download = input;\n controls.setDownloadUrl.call(this);\n }\n /**\n * Set the poster image for a video\n * @param {String} input - the URL for the new poster image\n */\n\n\n set poster(input) {\n if (!this.isVideo) {\n this.debug.warn('Poster can only be set for video');\n return;\n }\n\n ui.setPoster.call(this, input, false).catch(() => {});\n }\n /**\n * Get the current poster image\n */\n\n\n get poster() {\n if (!this.isVideo) {\n return null;\n }\n\n return this.media.getAttribute('poster') || this.media.getAttribute('data-poster');\n }\n /**\n * Get the current aspect ratio in use\n */\n\n\n get ratio() {\n if (!this.isVideo) {\n return null;\n }\n\n const ratio = reduceAspectRatio(getAspectRatio.call(this));\n return is.array(ratio) ? ratio.join(':') : ratio;\n }\n /**\n * Set video aspect ratio\n */\n\n\n set ratio(input) {\n if (!this.isVideo) {\n this.debug.warn('Aspect ratio can only be set for video');\n return;\n }\n\n if (!is.string(input) || !validateAspectRatio(input)) {\n this.debug.error(`Invalid aspect ratio specified (${input})`);\n return;\n }\n\n this.config.ratio = reduceAspectRatio(input);\n setAspectRatio.call(this);\n }\n /**\n * Set the autoplay state\n * @param {Boolean} input - Whether to autoplay or not\n */\n\n\n set autoplay(input) {\n const toggle = is.boolean(input) ? input : this.config.autoplay;\n this.config.autoplay = toggle;\n }\n /**\n * Get the current autoplay state\n */\n\n\n get autoplay() {\n return Boolean(this.config.autoplay);\n }\n /**\n * Toggle captions\n * @param {Boolean} input - Whether to enable captions\n */\n\n\n toggleCaptions(input) {\n captions.toggle.call(this, input, false);\n }\n /**\n * Set the caption track by index\n * @param {Number} - Caption index\n */\n\n\n set currentTrack(input) {\n captions.set.call(this, input, false);\n captions.setup();\n }\n /**\n * Get the current caption track index (-1 if disabled)\n */\n\n\n get currentTrack() {\n const {\n toggled,\n currentTrack\n } = this.captions;\n return toggled ? currentTrack : -1;\n }\n /**\n * Set the wanted language for captions\n * Since tracks can be added later it won't update the actual caption track until there is a matching track\n * @param {String} - Two character ISO language code (e.g. EN, FR, PT, etc)\n */\n\n\n set language(input) {\n captions.setLanguage.call(this, input, false);\n }\n /**\n * Get the current track's language\n */\n\n\n get language() {\n return (captions.getCurrentTrack.call(this) || {}).language;\n }\n /**\n * Toggle picture-in-picture playback on WebKit/MacOS\n * TODO: update player with state, support, enabled\n * TODO: detect outside changes\n */\n\n\n set pip(input) {\n // Bail if no support\n if (!support.pip) {\n return;\n } // Toggle based on current state if not passed\n\n\n const toggle = is.boolean(input) ? input : !this.pip; // Toggle based on current state\n // Safari\n\n if (is.function(this.media.webkitSetPresentationMode)) {\n this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive);\n } // Chrome\n\n\n if (is.function(this.media.requestPictureInPicture)) {\n if (!this.pip && toggle) {\n this.media.requestPictureInPicture();\n } else if (this.pip && !toggle) {\n document.exitPictureInPicture();\n }\n }\n }\n /**\n * Get the current picture-in-picture state\n */\n\n\n get pip() {\n if (!support.pip) {\n return null;\n } // Safari\n\n\n if (!is.empty(this.media.webkitPresentationMode)) {\n return this.media.webkitPresentationMode === pip.active;\n } // Chrome\n\n\n return this.media === document.pictureInPictureElement;\n }\n /**\n * Sets the preview thubmnails for the current source\n */\n\n\n setPreviewThumbnails(thumbnailSource) {\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n Object.assign(this.config.previewThumbnails, thumbnailSource); // Create new instance if it is still enabled\n\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n /**\n * Trigger the airplay dialog\n * TODO: update player with state, support, enabled\n */\n\n\n /**\n * Check for support\n * @param {String} type - Player type (audio/video)\n * @param {String} provider - Provider (html5/youtube/vimeo)\n * @param {Boolean} inline - Where player has `playsinline` sttribute\n */\n static supported(type, provider, inline) {\n return support.check(type, provider, inline);\n }\n /**\n * Load an SVG sprite into the page\n * @param {String} url - URL for the SVG sprite\n * @param {String} [id] - Unique ID\n */\n\n\n static loadSprite(url, id) {\n return loadSprite(url, id);\n }\n /**\n * Setup multiple instances\n * @param {*} selector\n * @param {Object} options\n */\n\n\n static setup(selector, options = {}) {\n let targets = null;\n\n if (is.string(selector)) {\n targets = Array.from(document.querySelectorAll(selector));\n } else if (is.nodeList(selector)) {\n targets = Array.from(selector);\n } else if (is.array(selector)) {\n targets = selector.filter(is.element);\n }\n\n if (is.empty(targets)) {\n return null;\n }\n\n return targets.map(t => new Plyr(t, options));\n }\n\n}\n\nPlyr.defaults = cloneDeep(defaults);\n\n// ==========================================================================\n\nexport { Plyr as default };\n","function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ownKeys(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(n),!0).forEach((function(t){_defineProperty(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ownKeys(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var defaults={addCSS:!0,thumbWidth:15,watch:!0};function matches(e,t){return function(){return Array.from(document.querySelectorAll(t)).includes(this)}.call(e,t)}function trigger(e,t){if(e&&t){var n=new Event(t,{bubbles:!0});e.dispatchEvent(n)}}var getConstructor=function(e){return null!=e?e.constructor:null},instanceOf=function(e,t){return!!(e&&t&&e instanceof t)},isNullOrUndefined=function(e){return null==e},isObject=function(e){return getConstructor(e)===Object},isNumber=function(e){return getConstructor(e)===Number&&!Number.isNaN(e)},isString=function(e){return getConstructor(e)===String},isBoolean=function(e){return getConstructor(e)===Boolean},isFunction=function(e){return getConstructor(e)===Function},isArray=function(e){return Array.isArray(e)},isNodeList=function(e){return instanceOf(e,NodeList)},isElement=function(e){return instanceOf(e,Element)},isEvent=function(e){return instanceOf(e,Event)},isEmpty=function(e){return isNullOrUndefined(e)||(isString(e)||isArray(e)||isNodeList(e))&&!e.length||isObject(e)&&!Object.keys(e).length},is={nullOrUndefined:isNullOrUndefined,object:isObject,number:isNumber,string:isString,boolean:isBoolean,function:isFunction,array:isArray,nodeList:isNodeList,element:isElement,event:isEvent,empty:isEmpty};function getDecimalPlaces(e){var t=\"\".concat(e).match(/(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0}function round(e,t){if(1>t){var n=getDecimalPlaces(t);return parseFloat(e.toFixed(n))}return Math.round(e/t)*t}var RangeTouch=function(){function e(t,n){_classCallCheck(this,e),is.element(t)?this.element=t:is.string(t)&&(this.element=document.querySelector(t)),is.element(this.element)&&is.empty(this.element.rangeTouch)&&(this.config=_objectSpread2({},defaults,{},n),this.init())}return _createClass(e,[{key:\"init\",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect=\"none\",this.element.style.webKitUserSelect=\"none\",this.element.style.touchAction=\"manipulation\"),this.listeners(!0),this.element.rangeTouch=this)}},{key:\"destroy\",value:function(){e.enabled&&(this.config.addCSS&&(this.element.style.userSelect=\"\",this.element.style.webKitUserSelect=\"\",this.element.style.touchAction=\"\"),this.listeners(!1),this.element.rangeTouch=null)}},{key:\"listeners\",value:function(e){var t=this,n=e?\"addEventListener\":\"removeEventListener\";[\"touchstart\",\"touchmove\",\"touchend\"].forEach((function(e){t.element[n](e,(function(e){return t.set(e)}),!1)}))}},{key:\"get\",value:function(t){if(!e.enabled||!is.event(t))return null;var n,r=t.target,i=t.changedTouches[0],o=parseFloat(r.getAttribute(\"min\"))||0,s=parseFloat(r.getAttribute(\"max\"))||100,u=parseFloat(r.getAttribute(\"step\"))||1,c=r.getBoundingClientRect(),a=100/c.width*(this.config.thumbWidth/2)/100;return 0>(n=100/c.width*(i.clientX-c.left))?n=0:100<n&&(n=100),50>n?n-=(100-2*n)*a:50<n&&(n+=2*(n-50)*a),o+round(n/100*(s-o),u)}},{key:\"set\",value:function(t){e.enabled&&is.event(t)&&!t.target.disabled&&(t.preventDefault(),t.target.value=this.get(t),trigger(t.target,\"touchend\"===t.type?\"change\":\"input\"))}}],[{key:\"setup\",value:function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r=null;if(is.empty(t)||is.string(t)?r=Array.from(document.querySelectorAll(is.string(t)?t:'input[type=\"range\"]')):is.element(t)?r=[t]:is.nodeList(t)?r=Array.from(t):is.array(t)&&(r=t.filter(is.element)),is.empty(r))return null;var i=_objectSpread2({},defaults,{},n);if(is.string(t)&&i.watch){var o=new MutationObserver((function(n){Array.from(n).forEach((function(n){Array.from(n.addedNodes).forEach((function(n){is.element(n)&&matches(n,t)&&new e(n,i)}))}))}));o.observe(document.body,{childList:!0,subtree:!0})}return r.map((function(t){return new e(t,n)}))}},{key:\"enabled\",get:function(){return\"ontouchstart\"in document.documentElement}}]),e}();export default RangeTouch;","(function(global) {\r\n /**\r\n * Polyfill URLSearchParams\r\n *\r\n * Inspired from : https://github.com/WebReflection/url-search-params/blob/master/src/url-search-params.js\r\n */\r\n\r\n var checkIfIteratorIsSupported = function() {\r\n try {\r\n return !!Symbol.iterator;\r\n } catch (error) {\r\n return false;\r\n }\r\n };\r\n\r\n\r\n var iteratorSupported = checkIfIteratorIsSupported();\r\n\r\n var createIterator = function(items) {\r\n var iterator = {\r\n next: function() {\r\n var value = items.shift();\r\n return { done: value === void 0, value: value };\r\n }\r\n };\r\n\r\n if (iteratorSupported) {\r\n iterator[Symbol.iterator] = function() {\r\n return iterator;\r\n };\r\n }\r\n\r\n return iterator;\r\n };\r\n\r\n /**\r\n * Search param name and values should be encoded according to https://url.spec.whatwg.org/#urlencoded-serializing\r\n * encodeURIComponent() produces the same result except encoding spaces as `%20` instead of `+`.\r\n */\r\n var serializeParam = function(value) {\r\n return encodeURIComponent(value).replace(/%20/g, '+');\r\n };\r\n\r\n var deserializeParam = function(value) {\r\n return decodeURIComponent(String(value).replace(/\\+/g, ' '));\r\n };\r\n\r\n var polyfillURLSearchParams = function() {\r\n\r\n var URLSearchParams = function(searchString) {\r\n Object.defineProperty(this, '_entries', { writable: true, value: {} });\r\n var typeofSearchString = typeof searchString;\r\n\r\n if (typeofSearchString === 'undefined') {\r\n // do nothing\r\n } else if (typeofSearchString === 'string') {\r\n if (searchString !== '') {\r\n this._fromString(searchString);\r\n }\r\n } else if (searchString instanceof URLSearchParams) {\r\n var _this = this;\r\n searchString.forEach(function(value, name) {\r\n _this.append(name, value);\r\n });\r\n } else if ((searchString !== null) && (typeofSearchString === 'object')) {\r\n if (Object.prototype.toString.call(searchString) === '[object Array]') {\r\n for (var i = 0; i < searchString.length; i++) {\r\n var entry = searchString[i];\r\n if ((Object.prototype.toString.call(entry) === '[object Array]') || (entry.length !== 2)) {\r\n this.append(entry[0], entry[1]);\r\n } else {\r\n throw new TypeError('Expected [string, any] as entry at index ' + i + ' of URLSearchParams\\'s input');\r\n }\r\n }\r\n } else {\r\n for (var key in searchString) {\r\n if (searchString.hasOwnProperty(key)) {\r\n this.append(key, searchString[key]);\r\n }\r\n }\r\n }\r\n } else {\r\n throw new TypeError('Unsupported input\\'s type for URLSearchParams');\r\n }\r\n };\r\n\r\n var proto = URLSearchParams.prototype;\r\n\r\n proto.append = function(name, value) {\r\n if (name in this._entries) {\r\n this._entries[name].push(String(value));\r\n } else {\r\n this._entries[name] = [String(value)];\r\n }\r\n };\r\n\r\n proto.delete = function(name) {\r\n delete this._entries[name];\r\n };\r\n\r\n proto.get = function(name) {\r\n return (name in this._entries) ? this._entries[name][0] : null;\r\n };\r\n\r\n proto.getAll = function(name) {\r\n return (name in this._entries) ? this._entries[name].slice(0) : [];\r\n };\r\n\r\n proto.has = function(name) {\r\n return (name in this._entries);\r\n };\r\n\r\n proto.set = function(name, value) {\r\n this._entries[name] = [String(value)];\r\n };\r\n\r\n proto.forEach = function(callback, thisArg) {\r\n var entries;\r\n for (var name in this._entries) {\r\n if (this._entries.hasOwnProperty(name)) {\r\n entries = this._entries[name];\r\n for (var i = 0; i < entries.length; i++) {\r\n callback.call(thisArg, entries[i], name, this);\r\n }\r\n }\r\n }\r\n };\r\n\r\n proto.keys = function() {\r\n var items = [];\r\n this.forEach(function(value, name) {\r\n items.push(name);\r\n });\r\n return createIterator(items);\r\n };\r\n\r\n proto.values = function() {\r\n var items = [];\r\n this.forEach(function(value) {\r\n items.push(value);\r\n });\r\n return createIterator(items);\r\n };\r\n\r\n proto.entries = function() {\r\n var items = [];\r\n this.forEach(function(value, name) {\r\n items.push([name, value]);\r\n });\r\n return createIterator(items);\r\n };\r\n\r\n if (iteratorSupported) {\r\n proto[Symbol.iterator] = proto.entries;\r\n }\r\n\r\n proto.toString = function() {\r\n var searchArray = [];\r\n this.forEach(function(value, name) {\r\n searchArray.push(serializeParam(name) + '=' + serializeParam(value));\r\n });\r\n return searchArray.join('&');\r\n };\r\n\r\n\r\n global.URLSearchParams = URLSearchParams;\r\n };\r\n\r\n var checkIfURLSearchParamsSupported = function() {\r\n try {\r\n var URLSearchParams = global.URLSearchParams;\r\n\r\n return (\r\n (new URLSearchParams('?a=1').toString() === 'a=1') &&\r\n (typeof URLSearchParams.prototype.set === 'function') &&\r\n (typeof URLSearchParams.prototype.entries === 'function')\r\n );\r\n } catch (e) {\r\n return false;\r\n }\r\n };\r\n\r\n if (!checkIfURLSearchParamsSupported()) {\r\n polyfillURLSearchParams();\r\n }\r\n\r\n var proto = global.URLSearchParams.prototype;\r\n\r\n if (typeof proto.sort !== 'function') {\r\n proto.sort = function() {\r\n var _this = this;\r\n var items = [];\r\n this.forEach(function(value, name) {\r\n items.push([name, value]);\r\n if (!_this._entries) {\r\n _this.delete(name);\r\n }\r\n });\r\n items.sort(function(a, b) {\r\n if (a[0] < b[0]) {\r\n return -1;\r\n } else if (a[0] > b[0]) {\r\n return +1;\r\n } else {\r\n return 0;\r\n }\r\n });\r\n if (_this._entries) { // force reset because IE keeps keys index\r\n _this._entries = {};\r\n }\r\n for (var i = 0; i < items.length; i++) {\r\n this.append(items[i][0], items[i][1]);\r\n }\r\n };\r\n }\r\n\r\n if (typeof proto._fromString !== 'function') {\r\n Object.defineProperty(proto, '_fromString', {\r\n enumerable: false,\r\n configurable: false,\r\n writable: false,\r\n value: function(searchString) {\r\n if (this._entries) {\r\n this._entries = {};\r\n } else {\r\n var keys = [];\r\n this.forEach(function(value, name) {\r\n keys.push(name);\r\n });\r\n for (var i = 0; i < keys.length; i++) {\r\n this.delete(keys[i]);\r\n }\r\n }\r\n\r\n searchString = searchString.replace(/^\\?/, '');\r\n var attributes = searchString.split('&');\r\n var attribute;\r\n for (var i = 0; i < attributes.length; i++) {\r\n attribute = attributes[i].split('=');\r\n this.append(\r\n deserializeParam(attribute[0]),\r\n (attribute.length > 1) ? deserializeParam(attribute[1]) : ''\r\n );\r\n }\r\n }\r\n });\r\n }\r\n\r\n // HTMLAnchorElement\r\n\r\n})(\r\n (typeof global !== 'undefined') ? global\r\n : ((typeof window !== 'undefined') ? window\r\n : ((typeof self !== 'undefined') ? self : this))\r\n);\r\n\r\n(function(global) {\r\n /**\r\n * Polyfill URL\r\n *\r\n * Inspired from : https://github.com/arv/DOM-URL-Polyfill/blob/master/src/url.js\r\n */\r\n\r\n var checkIfURLIsSupported = function() {\r\n try {\r\n var u = new global.URL('b', 'http://a');\r\n u.pathname = 'c d';\r\n return (u.href === 'http://a/c%20d') && u.searchParams;\r\n } catch (e) {\r\n return false;\r\n }\r\n };\r\n\r\n\r\n var polyfillURL = function() {\r\n var _URL = global.URL;\r\n\r\n var URL = function(url, base) {\r\n if (typeof url !== 'string') url = String(url);\r\n if (base && typeof base !== 'string') base = String(base);\r\n\r\n // Only create another document if the base is different from current location.\r\n var doc = document, baseElement;\r\n if (base && (global.location === void 0 || base !== global.location.href)) {\r\n base = base.toLowerCase();\r\n doc = document.implementation.createHTMLDocument('');\r\n baseElement = doc.createElement('base');\r\n baseElement.href = base;\r\n doc.head.appendChild(baseElement);\r\n try {\r\n if (baseElement.href.indexOf(base) !== 0) throw new Error(baseElement.href);\r\n } catch (err) {\r\n throw new Error('URL unable to set base ' + base + ' due to ' + err);\r\n }\r\n }\r\n\r\n var anchorElement = doc.createElement('a');\r\n anchorElement.href = url;\r\n if (baseElement) {\r\n doc.body.appendChild(anchorElement);\r\n anchorElement.href = anchorElement.href; // force href to refresh\r\n }\r\n\r\n var inputElement = doc.createElement('input');\r\n inputElement.type = 'url';\r\n inputElement.value = url;\r\n\r\n if (anchorElement.protocol === ':' || !/:/.test(anchorElement.href) || (!inputElement.checkValidity() && !base)) {\r\n throw new TypeError('Invalid URL');\r\n }\r\n\r\n Object.defineProperty(this, '_anchorElement', {\r\n value: anchorElement\r\n });\r\n\r\n\r\n // create a linked searchParams which reflect its changes on URL\r\n var searchParams = new global.URLSearchParams(this.search);\r\n var enableSearchUpdate = true;\r\n var enableSearchParamsUpdate = true;\r\n var _this = this;\r\n ['append', 'delete', 'set'].forEach(function(methodName) {\r\n var method = searchParams[methodName];\r\n searchParams[methodName] = function() {\r\n method.apply(searchParams, arguments);\r\n if (enableSearchUpdate) {\r\n enableSearchParamsUpdate = false;\r\n _this.search = searchParams.toString();\r\n enableSearchParamsUpdate = true;\r\n }\r\n };\r\n });\r\n\r\n Object.defineProperty(this, 'searchParams', {\r\n value: searchParams,\r\n enumerable: true\r\n });\r\n\r\n var search = void 0;\r\n Object.defineProperty(this, '_updateSearchParams', {\r\n enumerable: false,\r\n configurable: false,\r\n writable: false,\r\n value: function() {\r\n if (this.search !== search) {\r\n search = this.search;\r\n if (enableSearchParamsUpdate) {\r\n enableSearchUpdate = false;\r\n this.searchParams._fromString(this.search);\r\n enableSearchUpdate = true;\r\n }\r\n }\r\n }\r\n });\r\n };\r\n\r\n var proto = URL.prototype;\r\n\r\n var linkURLWithAnchorAttribute = function(attributeName) {\r\n Object.defineProperty(proto, attributeName, {\r\n get: function() {\r\n return this._anchorElement[attributeName];\r\n },\r\n set: function(value) {\r\n this._anchorElement[attributeName] = value;\r\n },\r\n enumerable: true\r\n });\r\n };\r\n\r\n ['hash', 'host', 'hostname', 'port', 'protocol']\r\n .forEach(function(attributeName) {\r\n linkURLWithAnchorAttribute(attributeName);\r\n });\r\n\r\n Object.defineProperty(proto, 'search', {\r\n get: function() {\r\n return this._anchorElement['search'];\r\n },\r\n set: function(value) {\r\n this._anchorElement['search'] = value;\r\n this._updateSearchParams();\r\n },\r\n enumerable: true\r\n });\r\n\r\n Object.defineProperties(proto, {\r\n\r\n 'toString': {\r\n get: function() {\r\n var _this = this;\r\n return function() {\r\n return _this.href;\r\n };\r\n }\r\n },\r\n\r\n 'href': {\r\n get: function() {\r\n return this._anchorElement.href.replace(/\\?$/, '');\r\n },\r\n set: function(value) {\r\n this._anchorElement.href = value;\r\n this._updateSearchParams();\r\n },\r\n enumerable: true\r\n },\r\n\r\n 'pathname': {\r\n get: function() {\r\n return this._anchorElement.pathname.replace(/(^\\/?)/, '/');\r\n },\r\n set: function(value) {\r\n this._anchorElement.pathname = value;\r\n },\r\n enumerable: true\r\n },\r\n\r\n 'origin': {\r\n get: function() {\r\n // get expected port from protocol\r\n var expectedPort = { 'http:': 80, 'https:': 443, 'ftp:': 21 }[this._anchorElement.protocol];\r\n // add port to origin if, expected port is different than actual port\r\n // and it is not empty f.e http://foo:8080\r\n // 8080 != 80 && 8080 != ''\r\n var addPortToOrigin = this._anchorElement.port != expectedPort &&\r\n this._anchorElement.port !== '';\r\n\r\n return this._anchorElement.protocol +\r\n '//' +\r\n this._anchorElement.hostname +\r\n (addPortToOrigin ? (':' + this._anchorElement.port) : '');\r\n },\r\n enumerable: true\r\n },\r\n\r\n 'password': { // TODO\r\n get: function() {\r\n return '';\r\n },\r\n set: function(value) {\r\n },\r\n enumerable: true\r\n },\r\n\r\n 'username': { // TODO\r\n get: function() {\r\n return '';\r\n },\r\n set: function(value) {\r\n },\r\n enumerable: true\r\n },\r\n });\r\n\r\n URL.createObjectURL = function(blob) {\r\n return _URL.createObjectURL.apply(_URL, arguments);\r\n };\r\n\r\n URL.revokeObjectURL = function(url) {\r\n return _URL.revokeObjectURL.apply(_URL, arguments);\r\n };\r\n\r\n global.URL = URL;\r\n\r\n };\r\n\r\n if (!checkIfURLIsSupported()) {\r\n polyfillURL();\r\n }\r\n\r\n if ((global.location !== void 0) && !('origin' in global.location)) {\r\n var getOrigin = function() {\r\n return global.location.protocol + '//' + global.location.hostname + (global.location.port ? (':' + global.location.port) : '');\r\n };\r\n\r\n try {\r\n Object.defineProperty(global.location, 'origin', {\r\n get: getOrigin,\r\n enumerable: true\r\n });\r\n } catch (e) {\r\n setInterval(function() {\r\n global.location.origin = getOrigin();\r\n }, 100);\r\n }\r\n }\r\n\r\n})(\r\n (typeof global !== 'undefined') ? global\r\n : ((typeof window !== 'undefined') ? window\r\n : ((typeof self !== 'undefined') ? self : this))\r\n);\r\n","// ==========================================================================\n// Type checking utils\n// ==========================================================================\n\nconst getConstructor = (input) => (input !== null && typeof input !== 'undefined' ? input.constructor : null);\nconst instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor);\nconst isNullOrUndefined = (input) => input === null || typeof input === 'undefined';\nconst isObject = (input) => getConstructor(input) === Object;\nconst isNumber = (input) => getConstructor(input) === Number && !Number.isNaN(input);\nconst isString = (input) => getConstructor(input) === String;\nconst isBoolean = (input) => getConstructor(input) === Boolean;\nconst isFunction = (input) => getConstructor(input) === Function;\nconst isArray = (input) => Array.isArray(input);\nconst isWeakMap = (input) => instanceOf(input, WeakMap);\nconst isNodeList = (input) => instanceOf(input, NodeList);\nconst isTextNode = (input) => getConstructor(input) === Text;\nconst isEvent = (input) => instanceOf(input, Event);\nconst isKeyboardEvent = (input) => instanceOf(input, KeyboardEvent);\nconst isCue = (input) => instanceOf(input, window.TextTrackCue) || instanceOf(input, window.VTTCue);\nconst isTrack = (input) => instanceOf(input, TextTrack) || (!isNullOrUndefined(input) && isString(input.kind));\nconst isPromise = (input) => instanceOf(input, Promise) && isFunction(input.then);\n\nconst isElement = (input) =>\n input !== null &&\n typeof input === 'object' &&\n input.nodeType === 1 &&\n typeof input.style === 'object' &&\n typeof input.ownerDocument === 'object';\n\nconst isEmpty = (input) =>\n isNullOrUndefined(input) ||\n ((isString(input) || isArray(input) || isNodeList(input)) && !input.length) ||\n (isObject(input) && !Object.keys(input).length);\n\nconst isUrl = (input) => {\n // Accept a URL object\n if (instanceOf(input, window.URL)) {\n return true;\n }\n\n // Must be string from here\n if (!isString(input)) {\n return false;\n }\n\n // Add the protocol if required\n let string = input;\n if (!input.startsWith('http://') || !input.startsWith('https://')) {\n string = `http://${input}`;\n }\n\n try {\n return !isEmpty(new URL(string).hostname);\n } catch (_) {\n return false;\n }\n};\n\nexport default {\n nullOrUndefined: isNullOrUndefined,\n object: isObject,\n number: isNumber,\n string: isString,\n boolean: isBoolean,\n function: isFunction,\n array: isArray,\n weakMap: isWeakMap,\n nodeList: isNodeList,\n element: isElement,\n textNode: isTextNode,\n event: isEvent,\n keyboardEvent: isKeyboardEvent,\n cue: isCue,\n track: isTrack,\n promise: isPromise,\n url: isUrl,\n empty: isEmpty,\n};\n","// ==========================================================================\n// Animation utils\n// ==========================================================================\n\nimport is from './is';\n\nexport const transitionEndEvent = (() => {\n const element = document.createElement('span');\n\n const events = {\n WebkitTransition: 'webkitTransitionEnd',\n MozTransition: 'transitionend',\n OTransition: 'oTransitionEnd otransitionend',\n transition: 'transitionend',\n };\n\n const type = Object.keys(events).find((event) => element.style[event] !== undefined);\n\n return is.string(type) ? events[type] : false;\n})();\n\n// Force repaint of element\nexport function repaint(element, delay) {\n setTimeout(() => {\n try {\n // eslint-disable-next-line no-param-reassign\n element.hidden = true;\n\n // eslint-disable-next-line no-unused-expressions\n element.offsetHeight;\n\n // eslint-disable-next-line no-param-reassign\n element.hidden = false;\n } catch (_) {\n // Do nothing\n }\n }, delay);\n}\n","// ==========================================================================\n// Browser sniffing\n// Unfortunately, due to mixed support, UA sniffing is required\n// ==========================================================================\n\nconst browser = {\n isIE: Boolean(window.document.documentMode),\n isEdge: window.navigator.userAgent.includes('Edge'),\n isWebkit: 'WebkitAppearance' in document.documentElement.style && !/Edge/.test(navigator.userAgent),\n isIPhone: /(iPhone|iPod)/gi.test(navigator.platform),\n isIos:\n (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) ||\n /(iPad|iPhone|iPod)/gi.test(navigator.platform),\n};\n\nexport default browser;\n","// ==========================================================================\n// Object utils\n// ==========================================================================\n\nimport is from './is';\n\n// Clone nested objects\nexport function cloneDeep(object) {\n return JSON.parse(JSON.stringify(object));\n}\n\n// Get a nested value in an object\nexport function getDeep(object, path) {\n return path.split('.').reduce((obj, key) => obj && obj[key], object);\n}\n\n// Deep extend destination object with N more objects\nexport function extend(target = {}, ...sources) {\n if (!sources.length) {\n return target;\n }\n\n const source = sources.shift();\n\n if (!is.object(source)) {\n return target;\n }\n\n Object.keys(source).forEach((key) => {\n if (is.object(source[key])) {\n if (!Object.keys(target).includes(key)) {\n Object.assign(target, { [key]: {} });\n }\n\n extend(target[key], source[key]);\n } else {\n Object.assign(target, { [key]: source[key] });\n }\n });\n\n return extend(target, ...sources);\n}\n","// ==========================================================================\n// Element utils\n// ==========================================================================\n\nimport is from './is';\nimport { extend } from './objects';\n\n// Wrap an element\nexport function wrap(elements, wrapper) {\n // Convert `elements` to an array, if necessary.\n const targets = elements.length ? elements : [elements];\n\n // Loops backwards to prevent having to clone the wrapper on the\n // first element (see `child` below).\n Array.from(targets)\n .reverse()\n .forEach((element, index) => {\n const child = index > 0 ? wrapper.cloneNode(true) : wrapper;\n // Cache the current parent and sibling.\n const parent = element.parentNode;\n const sibling = element.nextSibling;\n\n // Wrap the element (is automatically removed from its current\n // parent).\n child.appendChild(element);\n\n // If the element had a sibling, insert the wrapper before\n // the sibling to maintain the HTML structure; otherwise, just\n // append it to the parent.\n if (sibling) {\n parent.insertBefore(child, sibling);\n } else {\n parent.appendChild(child);\n }\n });\n}\n\n// Set attributes\nexport function setAttributes(element, attributes) {\n if (!is.element(element) || is.empty(attributes)) {\n return;\n }\n\n // Assume null and undefined attributes should be left out,\n // Setting them would otherwise convert them to \"null\" and \"undefined\"\n Object.entries(attributes)\n .filter(([, value]) => !is.nullOrUndefined(value))\n .forEach(([key, value]) => element.setAttribute(key, value));\n}\n\n// Create a DocumentFragment\nexport function createElement(type, attributes, text) {\n // Create a new <element>\n const element = document.createElement(type);\n\n // Set all passed attributes\n if (is.object(attributes)) {\n setAttributes(element, attributes);\n }\n\n // Add text node\n if (is.string(text)) {\n element.innerText = text;\n }\n\n // Return built element\n return element;\n}\n\n// Inaert an element after another\nexport function insertAfter(element, target) {\n if (!is.element(element) || !is.element(target)) {\n return;\n }\n\n target.parentNode.insertBefore(element, target.nextSibling);\n}\n\n// Insert a DocumentFragment\nexport function insertElement(type, parent, attributes, text) {\n if (!is.element(parent)) {\n return;\n }\n\n parent.appendChild(createElement(type, attributes, text));\n}\n\n// Remove element(s)\nexport function removeElement(element) {\n if (is.nodeList(element) || is.array(element)) {\n Array.from(element).forEach(removeElement);\n return;\n }\n\n if (!is.element(element) || !is.element(element.parentNode)) {\n return;\n }\n\n element.parentNode.removeChild(element);\n}\n\n// Remove all child elements\nexport function emptyElement(element) {\n if (!is.element(element)) {\n return;\n }\n\n let { length } = element.childNodes;\n\n while (length > 0) {\n element.removeChild(element.lastChild);\n length -= 1;\n }\n}\n\n// Replace element\nexport function replaceElement(newChild, oldChild) {\n if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) {\n return null;\n }\n\n oldChild.parentNode.replaceChild(newChild, oldChild);\n\n return newChild;\n}\n\n// Get an attribute object from a string selector\nexport function getAttributesFromSelector(sel, existingAttributes) {\n // For example:\n // '.test' to { class: 'test' }\n // '#test' to { id: 'test' }\n // '[data-test=\"test\"]' to { 'data-test': 'test' }\n\n if (!is.string(sel) || is.empty(sel)) {\n return {};\n }\n\n const attributes = {};\n const existing = extend({}, existingAttributes);\n\n sel.split(',').forEach((s) => {\n // Remove whitespace\n const selector = s.trim();\n const className = selector.replace('.', '');\n const stripped = selector.replace(/[[\\]]/g, '');\n // Get the parts and value\n const parts = stripped.split('=');\n const [key] = parts;\n const value = parts.length > 1 ? parts[1].replace(/[\"']/g, '') : '';\n // Get the first character\n const start = selector.charAt(0);\n\n switch (start) {\n case '.':\n // Add to existing classname\n if (is.string(existing.class)) {\n attributes.class = `${existing.class} ${className}`;\n } else {\n attributes.class = className;\n }\n break;\n\n case '#':\n // ID selector\n attributes.id = selector.replace('#', '');\n break;\n\n case '[':\n // Attribute selector\n attributes[key] = value;\n\n break;\n\n default:\n break;\n }\n });\n\n return extend(existing, attributes);\n}\n\n// Toggle hidden\nexport function toggleHidden(element, hidden) {\n if (!is.element(element)) {\n return;\n }\n\n let hide = hidden;\n\n if (!is.boolean(hide)) {\n hide = !element.hidden;\n }\n\n // eslint-disable-next-line no-param-reassign\n element.hidden = hide;\n}\n\n// Mirror Element.classList.toggle, with IE compatibility for \"force\" argument\nexport function toggleClass(element, className, force) {\n if (is.nodeList(element)) {\n return Array.from(element).map((e) => toggleClass(e, className, force));\n }\n\n if (is.element(element)) {\n let method = 'toggle';\n if (typeof force !== 'undefined') {\n method = force ? 'add' : 'remove';\n }\n\n element.classList[method](className);\n return element.classList.contains(className);\n }\n\n return false;\n}\n\n// Has class name\nexport function hasClass(element, className) {\n return is.element(element) && element.classList.contains(className);\n}\n\n// Element matches selector\nexport function matches(element, selector) {\n const { prototype } = Element;\n\n function match() {\n return Array.from(document.querySelectorAll(selector)).includes(this);\n }\n\n const method =\n prototype.matches ||\n prototype.webkitMatchesSelector ||\n prototype.mozMatchesSelector ||\n prototype.msMatchesSelector ||\n match;\n\n return method.call(element, selector);\n}\n\n// Closest ancestor element matching selector (also tests element itself)\nexport function closest(element, selector) {\n const { prototype } = Element;\n\n // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill\n function closestElement() {\n let el = this;\n\n do {\n if (matches.matches(el, selector)) return el;\n el = el.parentElement || el.parentNode;\n } while (el !== null && el.nodeType === 1);\n return null;\n }\n\n const method = prototype.closest || closestElement;\n\n return method.call(element, selector);\n}\n\n// Find all elements\nexport function getElements(selector) {\n return this.elements.container.querySelectorAll(selector);\n}\n\n// Find a single element\nexport function getElement(selector) {\n return this.elements.container.querySelector(selector);\n}\n\n// Set focus and tab focus class\nexport function setFocus(element = null, tabFocus = false) {\n if (!is.element(element)) {\n return;\n }\n\n // Set regular focus\n element.focus({ preventScroll: true });\n\n // If we want to mimic keyboard focus via tab\n if (tabFocus) {\n toggleClass(element, this.config.classNames.tabFocus);\n }\n}\n","// ==========================================================================\n// Plyr support checks\n// ==========================================================================\n\nimport { transitionEndEvent } from './utils/animation';\nimport browser from './utils/browser';\nimport { createElement } from './utils/elements';\nimport is from './utils/is';\n\n// Default codecs for checking mimetype support\nconst defaultCodecs = {\n 'audio/ogg': 'vorbis',\n 'audio/wav': '1',\n 'video/webm': 'vp8, vorbis',\n 'video/mp4': 'avc1.42E01E, mp4a.40.2',\n 'video/ogg': 'theora',\n};\n\n// Check for feature support\nconst support = {\n // Basic support\n audio: 'canPlayType' in document.createElement('audio'),\n video: 'canPlayType' in document.createElement('video'),\n\n // Check for support\n // Basic functionality vs full UI\n check(type, provider, playsinline) {\n const canPlayInline = browser.isIPhone && playsinline && support.playsinline;\n const api = support[type] || provider !== 'html5';\n const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline);\n\n return {\n api,\n ui,\n };\n },\n\n // Picture-in-picture support\n // Safari & Chrome only currently\n pip: (() => {\n if (browser.isIPhone) {\n return false;\n }\n\n // Safari\n // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls\n if (is.function(createElement('video').webkitSetPresentationMode)) {\n return true;\n }\n\n // Chrome\n // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture\n if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) {\n return true;\n }\n\n return false;\n })(),\n\n // Airplay support\n // Safari only currently\n airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent),\n\n // Inline playback support\n // https://webkit.org/blog/6784/new-video-policies-for-ios/\n playsinline: 'playsInline' in document.createElement('video'),\n\n // Check for mime type support against a player instance\n // Credits: http://diveintohtml5.info/everything.html\n // Related: http://www.leanbackplayer.com/test/h5mt.html\n mime(input) {\n if (is.empty(input)) {\n return false;\n }\n\n const [mediaType] = input.split('/');\n let type = input;\n\n // Verify we're using HTML5 and there's no media type mismatch\n if (!this.isHTML5 || mediaType !== this.type) {\n return false;\n }\n\n // Add codec if required\n if (Object.keys(defaultCodecs).includes(type)) {\n type += `; codecs=\"${defaultCodecs[input]}\"`;\n }\n\n try {\n return Boolean(type && this.media.canPlayType(type).replace(/no/, ''));\n } catch (_) {\n return false;\n }\n },\n\n // Check for textTracks support\n textTracks: 'textTracks' in document.createElement('video'),\n\n // <input type=\"range\"> Sliders\n rangeInput: (() => {\n const range = document.createElement('input');\n range.type = 'range';\n return range.type === 'range';\n })(),\n\n // Touch\n // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event\n touch: 'ontouchstart' in document.documentElement,\n\n // Detect transitions support\n transitions: transitionEndEvent !== false,\n\n // Reduced motion iOS & MacOS setting\n // https://webkit.org/blog/7551/responsive-design-for-motion/\n reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches,\n};\n\nexport default support;\n","// ==========================================================================\n// Event utils\n// ==========================================================================\n\nimport is from './is';\n\n// Check for passive event listener support\n// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md\n// https://www.youtube.com/watch?v=NPM6172J22g\nconst supportsPassiveListeners = (() => {\n // Test via a getter in the options object to see if the passive property is accessed\n let supported = false;\n try {\n const options = Object.defineProperty({}, 'passive', {\n get() {\n supported = true;\n return null;\n },\n });\n window.addEventListener('test', null, options);\n window.removeEventListener('test', null, options);\n } catch (_) {\n // Do nothing\n }\n\n return supported;\n})();\n\n// Toggle event listener\nexport function toggleListener(element, event, callback, toggle = false, passive = true, capture = false) {\n // Bail if no element, event, or callback\n if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) {\n return;\n }\n\n // Allow multiple events\n const events = event.split(' ');\n // Build options\n // Default to just the capture boolean for browsers with no passive listener support\n let options = capture;\n\n // If passive events listeners are supported\n if (supportsPassiveListeners) {\n options = {\n // Whether the listener can be passive (i.e. default never prevented)\n passive,\n // Whether the listener is a capturing listener or not\n capture,\n };\n }\n\n // If a single node is passed, bind the event listener\n events.forEach((type) => {\n if (this && this.eventListeners && toggle) {\n // Cache event listener\n this.eventListeners.push({ element, type, callback, options });\n }\n\n element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options);\n });\n}\n\n// Bind event handler\nexport function on(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, true, passive, capture);\n}\n\n// Unbind event handler\nexport function off(element, events = '', callback, passive = true, capture = false) {\n toggleListener.call(this, element, events, callback, false, passive, capture);\n}\n\n// Bind once-only event handler\nexport function once(element, events = '', callback, passive = true, capture = false) {\n const onceCallback = (...args) => {\n off(element, events, onceCallback, passive, capture);\n callback.apply(this, args);\n };\n\n toggleListener.call(this, element, events, onceCallback, true, passive, capture);\n}\n\n// Trigger event\nexport function triggerEvent(element, type = '', bubbles = false, detail = {}) {\n // Bail if no element\n if (!is.element(element) || is.empty(type)) {\n return;\n }\n\n // Create and dispatch the event\n const event = new CustomEvent(type, {\n bubbles,\n detail: { ...detail, plyr: this },\n });\n\n // Dispatch the event\n element.dispatchEvent(event);\n}\n\n// Unbind all cached event listeners\nexport function unbindListeners() {\n if (this && this.eventListeners) {\n this.eventListeners.forEach((item) => {\n const { element, type, callback, options } = item;\n element.removeEventListener(type, callback, options);\n });\n\n this.eventListeners = [];\n }\n}\n\n// Run method when / if player is ready\nexport function ready() {\n return new Promise((resolve) =>\n this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve),\n ).then(() => {});\n}\n","import is from './is';\n/**\n * Silence a Promise-like object.\n * This is useful for avoiding non-harmful, but potentially confusing \"uncaught\n * play promise\" rejection error messages.\n * @param {Object} value An object that may or may not be `Promise`-like.\n */\nexport function silencePromise(value) {\n if (is.promise(value)) {\n value.then(null, () => {});\n }\n}\n\nexport default { silencePromise };\n","// ==========================================================================\n// Array utils\n// ==========================================================================\n\nimport is from './is';\n\n// Remove duplicates in an array\nexport function dedupe(array) {\n if (!is.array(array)) {\n return array;\n }\n\n return array.filter((item, index) => array.indexOf(item) === index);\n}\n\n// Get the closest value in an array\nexport function closest(array, value) {\n if (!is.array(array) || !array.length) {\n return null;\n }\n\n return array.reduce((prev, curr) => (Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev));\n}\n","// ==========================================================================\n// Style utils\n// ==========================================================================\n\nimport { closest } from './arrays';\nimport is from './is';\n\n// Check support for a CSS declaration\nexport function supportsCSS(declaration) {\n if (!window || !window.CSS) {\n return false;\n }\n\n return window.CSS.supports(declaration);\n}\n\n// Standard/common aspect ratios\nconst standardRatios = [\n [1, 1],\n [4, 3],\n [3, 4],\n [5, 4],\n [4, 5],\n [3, 2],\n [2, 3],\n [16, 10],\n [10, 16],\n [16, 9],\n [9, 16],\n [21, 9],\n [9, 21],\n [32, 9],\n [9, 32],\n].reduce((out, [x, y]) => ({ ...out, [x / y]: [x, y] }), {});\n\n// Validate an aspect ratio\nexport function validateAspectRatio(input) {\n if (!is.array(input) && (!is.string(input) || !input.includes(':'))) {\n return false;\n }\n\n const ratio = is.array(input) ? input : input.split(':');\n\n return ratio.map(Number).every(is.number);\n}\n\n// Reduce an aspect ratio to it's lowest form\nexport function reduceAspectRatio(ratio) {\n if (!is.array(ratio) || !ratio.every(is.number)) {\n return null;\n }\n\n const [width, height] = ratio;\n const getDivider = (w, h) => (h === 0 ? w : getDivider(h, w % h));\n const divider = getDivider(width, height);\n\n return [width / divider, height / divider];\n}\n\n// Calculate an aspect ratio\nexport function getAspectRatio(input) {\n const parse = (ratio) => (validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null);\n // Try provided ratio\n let ratio = parse(input);\n\n // Get from config\n if (ratio === null) {\n ratio = parse(this.config.ratio);\n }\n\n // Get from embed\n if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) {\n ({ ratio } = this.embed);\n }\n\n // Get from HTML5 video\n if (ratio === null && this.isHTML5) {\n const { videoWidth, videoHeight } = this.media;\n ratio = [videoWidth, videoHeight];\n }\n\n return reduceAspectRatio(ratio);\n}\n\n// Set aspect ratio for responsive container\nexport function setAspectRatio(input) {\n if (!this.isVideo) {\n return {};\n }\n\n const { wrapper } = this.elements;\n const ratio = getAspectRatio.call(this, input);\n\n if (!is.array(ratio)) {\n return {};\n }\n\n const [x, y] = reduceAspectRatio(ratio);\n const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`);\n const padding = (100 / x) * y;\n\n if (useNative) {\n wrapper.style.aspectRatio = `${x}/${y}`;\n } else {\n wrapper.style.paddingBottom = `${padding}%`;\n }\n\n // For Vimeo we have an extra <div> to hide the standard controls and UI\n if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) {\n const height = (100 / this.media.offsetWidth) * parseInt(window.getComputedStyle(this.media).paddingBottom, 10);\n const offset = (height - padding) / (height / 50);\n\n if (this.fullscreen.active) {\n wrapper.style.paddingBottom = null;\n } else {\n this.media.style.transform = `translateY(-${offset}%)`;\n }\n } else if (this.isHTML5) {\n wrapper.classList.add(this.config.classNames.videoFixedRatio);\n }\n\n return { padding, ratio };\n}\n\n// Round an aspect ratio to closest standard ratio\nexport function roundAspectRatio(x, y, tolerance = 0.05) {\n const ratio = x / y;\n const closestRatio = closest(Object.keys(standardRatios), ratio);\n\n // Check match is within tolerance\n if (Math.abs(closestRatio - ratio) <= tolerance) {\n return standardRatios[closestRatio];\n }\n\n // No match\n return [x, y];\n}\n\n// Get the size of the viewport\n// https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions\nexport function getViewportSize() {\n const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);\n const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);\n return [width, height];\n}\n","// ==========================================================================\n// Plyr HTML5 helpers\n// ==========================================================================\n\nimport support from './support';\nimport { removeElement } from './utils/elements';\nimport { triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\nimport { setAspectRatio } from './utils/style';\n\nconst html5 = {\n getSources() {\n if (!this.isHTML5) {\n return [];\n }\n\n const sources = Array.from(this.media.querySelectorAll('source'));\n\n // Filter out unsupported sources (if type is specified)\n return sources.filter((source) => {\n const type = source.getAttribute('type');\n\n if (is.empty(type)) {\n return true;\n }\n\n return support.mime.call(this, type);\n });\n },\n\n // Get quality levels\n getQualityOptions() {\n // Whether we're forcing all options (e.g. for streaming)\n if (this.config.quality.forced) {\n return this.config.quality.options;\n }\n\n // Get sizes from <source> elements\n return html5.getSources\n .call(this)\n .map((source) => Number(source.getAttribute('data-res')))\n .filter(Boolean);\n },\n\n setup() {\n if (!this.isHTML5) {\n return;\n }\n\n const player = this;\n\n // Set speed options from config\n player.options.speed = player.config.speed.options;\n\n // Set aspect ratio if fixed\n if (!is.empty(this.config.ratio)) {\n setAspectRatio.call(player);\n }\n\n // Quality\n Object.defineProperty(player.media, 'quality', {\n get() {\n // Get sources\n const sources = html5.getSources.call(player);\n const source = sources.find((s) => s.getAttribute('src') === player.source);\n\n // Return size, if match is found\n return source && Number(source.getAttribute('data-res'));\n },\n set(input) {\n if (player.quality === input) {\n return;\n }\n\n // If we're using an external handler...\n if (player.config.quality.forced && is.function(player.config.quality.onChange)) {\n player.config.quality.onChange(input);\n } else {\n // Get sources\n const sources = html5.getSources.call(player);\n // Get first match for requested size\n const source = sources.find((s) => Number(s.getAttribute('data-res')) === input);\n\n // No matching source found\n if (!source) {\n return;\n }\n\n // Get current state\n const { currentTime, paused, preload, readyState, playbackRate } = player.media;\n\n // Set new source\n player.media.src = source.getAttribute('src');\n\n // Prevent loading if preload=\"none\" and the current source isn't loaded (#1044)\n if (preload !== 'none' || readyState) {\n // Restore time\n player.once('loadedmetadata', () => {\n player.speed = playbackRate;\n player.currentTime = currentTime;\n\n // Resume playing\n if (!paused) {\n silencePromise(player.play());\n }\n });\n\n // Load new source\n player.media.load();\n }\n }\n\n // Trigger change event\n triggerEvent.call(player, player.media, 'qualitychange', false, {\n quality: input,\n });\n },\n });\n },\n\n // Cancel current network requests\n // See https://github.com/sampotts/plyr/issues/174\n cancelRequests() {\n if (!this.isHTML5) {\n return;\n }\n\n // Remove child sources\n removeElement(html5.getSources.call(this));\n\n // Set blank video src attribute\n // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error\n // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection\n this.media.setAttribute('src', this.config.blankVideo);\n\n // Load the new empty source\n // This will cancel existing requests\n // See https://github.com/sampotts/plyr/issues/174\n this.media.load();\n\n // Debugging\n this.debug.log('Cancelled network requests');\n },\n};\n\nexport default html5;\n","// ==========================================================================\n// String utils\n// ==========================================================================\n\nimport is from './is';\n\n// Generate a random ID\nexport function generateId(prefix) {\n return `${prefix}-${Math.floor(Math.random() * 10000)}`;\n}\n\n// Format string\nexport function format(input, ...args) {\n if (is.empty(input)) {\n return input;\n }\n\n return input.toString().replace(/{(\\d+)}/g, (match, i) => args[i].toString());\n}\n\n// Get percentage\nexport function getPercentage(current, max) {\n if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) {\n return 0;\n }\n\n return ((current / max) * 100).toFixed(2);\n}\n\n// Replace all occurances of a string in a string\nexport const replaceAll = (input = '', find = '', replace = '') =>\n input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\\]/\\\\])/g, '\\\\$1'), 'g'), replace.toString());\n\n// Convert to title case\nexport const toTitleCase = (input = '') =>\n input.toString().replace(/\\w\\S*/g, (text) => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase());\n\n// Convert string to pascalCase\nexport function toPascalCase(input = '') {\n let string = input.toString();\n\n // Convert kebab case\n string = replaceAll(string, '-', ' ');\n\n // Convert snake case\n string = replaceAll(string, '_', ' ');\n\n // Convert to title case\n string = toTitleCase(string);\n\n // Convert to pascal case\n return replaceAll(string, ' ', '');\n}\n\n// Convert string to pascalCase\nexport function toCamelCase(input = '') {\n let string = input.toString();\n\n // Convert to pascal case\n string = toPascalCase(string);\n\n // Convert first character to lowercase\n return string.charAt(0).toLowerCase() + string.slice(1);\n}\n\n// Remove HTML from a string\nexport function stripHTML(source) {\n const fragment = document.createDocumentFragment();\n const element = document.createElement('div');\n fragment.appendChild(element);\n element.innerHTML = source;\n return fragment.firstChild.innerText;\n}\n\n// Like outerHTML, but also works for DocumentFragment\nexport function getHTML(element) {\n const wrapper = document.createElement('div');\n wrapper.appendChild(element);\n return wrapper.innerHTML;\n}\n","// ==========================================================================\n// Plyr internationalization\n// ==========================================================================\n\nimport is from './is';\nimport { getDeep } from './objects';\nimport { replaceAll } from './strings';\n\n// Skip i18n for abbreviations and brand names\nconst resources = {\n pip: 'PIP',\n airplay: 'AirPlay',\n html5: 'HTML5',\n vimeo: 'Vimeo',\n youtube: 'YouTube',\n};\n\nconst i18n = {\n get(key = '', config = {}) {\n if (is.empty(key) || is.empty(config)) {\n return '';\n }\n\n let string = getDeep(config.i18n, key);\n\n if (is.empty(string)) {\n if (Object.keys(resources).includes(key)) {\n return resources[key];\n }\n\n return '';\n }\n\n const replace = {\n '{seektime}': config.seekTime,\n '{title}': config.title,\n };\n\n Object.entries(replace).forEach(([k, v]) => {\n string = replaceAll(string, k, v);\n });\n\n return string;\n },\n};\n\nexport default i18n;\n","// ==========================================================================\n// Plyr storage\n// ==========================================================================\n\nimport is from './utils/is';\nimport { extend } from './utils/objects';\n\nclass Storage {\n constructor(player) {\n this.enabled = player.config.storage.enabled;\n this.key = player.config.storage.key;\n }\n\n // Check for actual support (see if we can use it)\n static get supported() {\n try {\n if (!('localStorage' in window)) {\n return false;\n }\n\n const test = '___test';\n\n // Try to use it (it might be disabled, e.g. user is in private mode)\n // see: https://github.com/sampotts/plyr/issues/131\n window.localStorage.setItem(test, test);\n window.localStorage.removeItem(test);\n\n return true;\n } catch (_) {\n return false;\n }\n }\n\n get = (key) => {\n if (!Storage.supported || !this.enabled) {\n return null;\n }\n\n const store = window.localStorage.getItem(this.key);\n\n if (is.empty(store)) {\n return null;\n }\n\n const json = JSON.parse(store);\n\n return is.string(key) && key.length ? json[key] : json;\n };\n\n set = (object) => {\n // Bail if we don't have localStorage support or it's disabled\n if (!Storage.supported || !this.enabled) {\n return;\n }\n\n // Can only store objectst\n if (!is.object(object)) {\n return;\n }\n\n // Get current storage\n let storage = this.get();\n\n // Default to empty object\n if (is.empty(storage)) {\n storage = {};\n }\n\n // Update the working copy of the values\n extend(storage, object);\n\n // Update storage\n try {\n window.localStorage.setItem(this.key, JSON.stringify(storage));\n } catch (_) {\n // Do nothing\n }\n };\n}\n\nexport default Storage;\n","// ==========================================================================\n// Fetch wrapper\n// Using XHR to avoid issues with older browsers\n// ==========================================================================\n\nexport default function fetch(url, responseType = 'text') {\n return new Promise((resolve, reject) => {\n try {\n const request = new XMLHttpRequest();\n\n // Check for CORS support\n if (!('withCredentials' in request)) {\n return;\n }\n\n request.addEventListener('load', () => {\n if (responseType === 'text') {\n try {\n resolve(JSON.parse(request.responseText));\n } catch (_) {\n resolve(request.responseText);\n }\n } else {\n resolve(request.response);\n }\n });\n\n request.addEventListener('error', () => {\n throw new Error(request.status);\n });\n\n request.open('GET', url, true);\n\n // Set the required response type\n request.responseType = responseType;\n\n request.send();\n } catch (error) {\n reject(error);\n }\n });\n}\n","// ==========================================================================\n// Sprite loader\n// ==========================================================================\n\nimport Storage from '../storage';\nimport fetch from './fetch';\nimport is from './is';\n\n// Load an external SVG sprite\nexport default function loadSprite(url, id) {\n if (!is.string(url)) {\n return;\n }\n\n const prefix = 'cache';\n const hasId = is.string(id);\n let isCached = false;\n const exists = () => document.getElementById(id) !== null;\n\n const update = (container, data) => {\n // eslint-disable-next-line no-param-reassign\n container.innerHTML = data;\n\n // Check again incase of race condition\n if (hasId && exists()) {\n return;\n }\n\n // Inject the SVG to the body\n document.body.insertAdjacentElement('afterbegin', container);\n };\n\n // Only load once if ID set\n if (!hasId || !exists()) {\n const useStorage = Storage.supported;\n // Create container\n const container = document.createElement('div');\n container.setAttribute('hidden', '');\n\n if (hasId) {\n container.setAttribute('id', id);\n }\n\n // Check in cache\n if (useStorage) {\n const cached = window.localStorage.getItem(`${prefix}-${id}`);\n isCached = cached !== null;\n\n if (isCached) {\n const data = JSON.parse(cached);\n update(container, data.content);\n }\n }\n\n // Get the sprite\n fetch(url)\n .then((result) => {\n if (is.empty(result)) {\n return;\n }\n\n if (useStorage) {\n try {\n window.localStorage.setItem(\n `${prefix}-${id}`,\n JSON.stringify({\n content: result,\n }),\n );\n } catch (_) {\n // Do nothing\n }\n }\n\n update(container, result);\n })\n .catch(() => {});\n }\n}\n","// ==========================================================================\n// Time utils\n// ==========================================================================\n\nimport is from './is';\n\n// Time helpers\nexport const getHours = (value) => Math.trunc((value / 60 / 60) % 60, 10);\nexport const getMinutes = (value) => Math.trunc((value / 60) % 60, 10);\nexport const getSeconds = (value) => Math.trunc(value % 60, 10);\n\n// Format time to UI friendly string\nexport function formatTime(time = 0, displayHours = false, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return formatTime(undefined, displayHours, inverted);\n }\n\n // Format time component to add leading zero\n const format = (value) => `0${value}`.slice(-2);\n // Breakdown to hours, mins, secs\n let hours = getHours(time);\n const mins = getMinutes(time);\n const secs = getSeconds(time);\n\n // Do we need to display hours?\n if (displayHours || hours > 0) {\n hours = `${hours}:`;\n } else {\n hours = '';\n }\n\n // Render\n return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`;\n}\n","// ==========================================================================\n// Plyr controls\n// TODO: This needs to be split into smaller files and cleaned up\n// ==========================================================================\n\nimport RangeTouch from 'rangetouch';\n\nimport captions from './captions';\nimport html5 from './html5';\nimport support from './support';\nimport { repaint, transitionEndEvent } from './utils/animation';\nimport { dedupe } from './utils/arrays';\nimport browser from './utils/browser';\nimport {\n createElement,\n emptyElement,\n getAttributesFromSelector,\n getElement,\n getElements,\n hasClass,\n matches,\n removeElement,\n setAttributes,\n setFocus,\n toggleClass,\n toggleHidden,\n} from './utils/elements';\nimport { off, on } from './utils/events';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport loadSprite from './utils/load-sprite';\nimport { extend } from './utils/objects';\nimport { getPercentage, replaceAll, toCamelCase, toTitleCase } from './utils/strings';\nimport { formatTime, getHours } from './utils/time';\n\n// TODO: Don't export a massive object - break down and create class\nconst controls = {\n // Get icon URL\n getIconUrl() {\n const url = new URL(this.config.iconUrl, window.location);\n const host = window.location.host ? window.location.host : window.top.location.host;\n const cors = url.host !== host || (browser.isIE && !window.svg4everybody);\n\n return {\n url: this.config.iconUrl,\n cors,\n };\n },\n\n // Find the UI controls\n findElements() {\n try {\n this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper);\n\n // Buttons\n this.elements.buttons = {\n play: getElements.call(this, this.config.selectors.buttons.play),\n pause: getElement.call(this, this.config.selectors.buttons.pause),\n restart: getElement.call(this, this.config.selectors.buttons.restart),\n rewind: getElement.call(this, this.config.selectors.buttons.rewind),\n fastForward: getElement.call(this, this.config.selectors.buttons.fastForward),\n mute: getElement.call(this, this.config.selectors.buttons.mute),\n pip: getElement.call(this, this.config.selectors.buttons.pip),\n airplay: getElement.call(this, this.config.selectors.buttons.airplay),\n settings: getElement.call(this, this.config.selectors.buttons.settings),\n captions: getElement.call(this, this.config.selectors.buttons.captions),\n fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen),\n };\n\n // Progress\n this.elements.progress = getElement.call(this, this.config.selectors.progress);\n\n // Inputs\n this.elements.inputs = {\n seek: getElement.call(this, this.config.selectors.inputs.seek),\n volume: getElement.call(this, this.config.selectors.inputs.volume),\n };\n\n // Display\n this.elements.display = {\n buffer: getElement.call(this, this.config.selectors.display.buffer),\n currentTime: getElement.call(this, this.config.selectors.display.currentTime),\n duration: getElement.call(this, this.config.selectors.display.duration),\n };\n\n // Seek tooltip\n if (is.element(this.elements.progress)) {\n this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`);\n }\n\n return true;\n } catch (error) {\n // Log it\n this.debug.warn('It looks like there is a problem with your custom controls HTML', error);\n\n // Restore native video controls\n this.toggleNativeControls(true);\n\n return false;\n }\n },\n\n // Create <svg> icon\n createIcon(type, attributes) {\n const namespace = 'http://www.w3.org/2000/svg';\n const iconUrl = controls.getIconUrl.call(this);\n const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`;\n // Create <svg>\n const icon = document.createElementNS(namespace, 'svg');\n setAttributes(\n icon,\n extend(attributes, {\n 'aria-hidden': 'true',\n focusable: 'false',\n }),\n );\n\n // Create the <use> to reference sprite\n const use = document.createElementNS(namespace, 'use');\n const path = `${iconPath}-${type}`;\n\n // Set `href` attributes\n // https://github.com/sampotts/plyr/issues/460\n // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href\n if ('href' in use) {\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path);\n }\n\n // Always set the older attribute even though it's \"deprecated\" (it'll be around for ages)\n use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path);\n\n // Add <use> to <svg>\n icon.appendChild(use);\n\n return icon;\n },\n\n // Create hidden text label\n createLabel(key, attr = {}) {\n const text = i18n.get(key, this.config);\n const attributes = { ...attr, class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ') };\n\n return createElement('span', attributes, text);\n },\n\n // Create a badge\n createBadge(text) {\n if (is.empty(text)) {\n return null;\n }\n\n const badge = createElement('span', {\n class: this.config.classNames.menu.value,\n });\n\n badge.appendChild(\n createElement(\n 'span',\n {\n class: this.config.classNames.menu.badge,\n },\n text,\n ),\n );\n\n return badge;\n },\n\n // Create a <button>\n createButton(buttonType, attr) {\n const attributes = extend({}, attr);\n let type = toCamelCase(buttonType);\n\n const props = {\n element: 'button',\n toggle: false,\n label: null,\n icon: null,\n labelPressed: null,\n iconPressed: null,\n };\n\n ['element', 'icon', 'label'].forEach((key) => {\n if (Object.keys(attributes).includes(key)) {\n props[key] = attributes[key];\n delete attributes[key];\n }\n });\n\n // Default to 'button' type to prevent form submission\n if (props.element === 'button' && !Object.keys(attributes).includes('type')) {\n attributes.type = 'button';\n }\n\n // Set class name\n if (Object.keys(attributes).includes('class')) {\n if (!attributes.class.split(' ').some((c) => c === this.config.classNames.control)) {\n extend(attributes, {\n class: `${attributes.class} ${this.config.classNames.control}`,\n });\n }\n } else {\n attributes.class = this.config.classNames.control;\n }\n\n // Large play button\n switch (buttonType) {\n case 'play':\n props.toggle = true;\n props.label = 'play';\n props.labelPressed = 'pause';\n props.icon = 'play';\n props.iconPressed = 'pause';\n break;\n\n case 'mute':\n props.toggle = true;\n props.label = 'mute';\n props.labelPressed = 'unmute';\n props.icon = 'volume';\n props.iconPressed = 'muted';\n break;\n\n case 'captions':\n props.toggle = true;\n props.label = 'enableCaptions';\n props.labelPressed = 'disableCaptions';\n props.icon = 'captions-off';\n props.iconPressed = 'captions-on';\n break;\n\n case 'fullscreen':\n props.toggle = true;\n props.label = 'enterFullscreen';\n props.labelPressed = 'exitFullscreen';\n props.icon = 'enter-fullscreen';\n props.iconPressed = 'exit-fullscreen';\n break;\n\n case 'play-large':\n attributes.class += ` ${this.config.classNames.control}--overlaid`;\n type = 'play';\n props.label = 'play';\n props.icon = 'play';\n break;\n\n default:\n if (is.empty(props.label)) {\n props.label = type;\n }\n if (is.empty(props.icon)) {\n props.icon = buttonType;\n }\n }\n\n const button = createElement(props.element);\n\n // Setup toggle icon and labels\n if (props.toggle) {\n // Icon\n button.appendChild(\n controls.createIcon.call(this, props.iconPressed, {\n class: 'icon--pressed',\n }),\n );\n button.appendChild(\n controls.createIcon.call(this, props.icon, {\n class: 'icon--not-pressed',\n }),\n );\n\n // Label/Tooltip\n button.appendChild(\n controls.createLabel.call(this, props.labelPressed, {\n class: 'label--pressed',\n }),\n );\n button.appendChild(\n controls.createLabel.call(this, props.label, {\n class: 'label--not-pressed',\n }),\n );\n } else {\n button.appendChild(controls.createIcon.call(this, props.icon));\n button.appendChild(controls.createLabel.call(this, props.label));\n }\n\n // Merge and set attributes\n extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes));\n setAttributes(button, attributes);\n\n // We have multiple play buttons\n if (type === 'play') {\n if (!is.array(this.elements.buttons[type])) {\n this.elements.buttons[type] = [];\n }\n\n this.elements.buttons[type].push(button);\n } else {\n this.elements.buttons[type] = button;\n }\n\n return button;\n },\n\n // Create an <input type='range'>\n createRange(type, attributes) {\n // Seek input\n const input = createElement(\n 'input',\n extend(\n getAttributesFromSelector(this.config.selectors.inputs[type]),\n {\n type: 'range',\n min: 0,\n max: 100,\n step: 0.01,\n value: 0,\n autocomplete: 'off',\n // A11y fixes for https://github.com/sampotts/plyr/issues/905\n role: 'slider',\n 'aria-label': i18n.get(type, this.config),\n 'aria-valuemin': 0,\n 'aria-valuemax': 100,\n 'aria-valuenow': 0,\n },\n attributes,\n ),\n );\n\n this.elements.inputs[type] = input;\n\n // Set the fill for webkit now\n controls.updateRangeFill.call(this, input);\n\n // Improve support on touch devices\n RangeTouch.setup(input);\n\n return input;\n },\n\n // Create a <progress>\n createProgress(type, attributes) {\n const progress = createElement(\n 'progress',\n extend(\n getAttributesFromSelector(this.config.selectors.display[type]),\n {\n min: 0,\n max: 100,\n value: 0,\n role: 'progressbar',\n 'aria-hidden': true,\n },\n attributes,\n ),\n );\n\n // Create the label inside\n if (type !== 'volume') {\n progress.appendChild(createElement('span', null, '0'));\n\n const suffixKey = {\n played: 'played',\n buffer: 'buffered',\n }[type];\n const suffix = suffixKey ? i18n.get(suffixKey, this.config) : '';\n\n progress.innerText = `% ${suffix.toLowerCase()}`;\n }\n\n this.elements.display[type] = progress;\n\n return progress;\n },\n\n // Create time display\n createTime(type, attrs) {\n const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs);\n\n const container = createElement(\n 'div',\n extend(attributes, {\n class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(),\n 'aria-label': i18n.get(type, this.config),\n }),\n '00:00',\n );\n\n // Reference for updates\n this.elements.display[type] = container;\n\n return container;\n },\n\n // Bind keyboard shortcuts for a menu item\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n bindMenuItemShortcuts(menuItem, type) {\n // Navigate through menus via arrow keys and space\n on.call(\n this,\n menuItem,\n 'keydown keyup',\n (event) => {\n // We only care about space and ⬆️ ⬇️️ ➡️\n if (![32, 38, 39, 40].includes(event.which)) {\n return;\n }\n\n // Prevent play / seek\n event.preventDefault();\n event.stopPropagation();\n\n // We're just here to prevent the keydown bubbling\n if (event.type === 'keydown') {\n return;\n }\n\n const isRadioButton = matches(menuItem, '[role=\"menuitemradio\"]');\n\n // Show the respective menu\n if (!isRadioButton && [32, 39].includes(event.which)) {\n controls.showMenuPanel.call(this, type, true);\n } else {\n let target;\n\n if (event.which !== 32) {\n if (event.which === 40 || (isRadioButton && event.which === 39)) {\n target = menuItem.nextElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.firstElementChild;\n }\n } else {\n target = menuItem.previousElementSibling;\n\n if (!is.element(target)) {\n target = menuItem.parentNode.lastElementChild;\n }\n }\n\n setFocus.call(this, target, true);\n }\n }\n },\n false,\n );\n\n // Enter will fire a `click` event but we still need to manage focus\n // So we bind to keyup which fires after and set focus here\n on.call(this, menuItem, 'keyup', (event) => {\n if (event.which !== 13) {\n return;\n }\n\n controls.focusFirstMenuItem.call(this, null, true);\n });\n },\n\n // Create a settings menu item\n createMenuItem({ value, list, type, title, badge = null, checked = false }) {\n const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]);\n\n const menuItem = createElement(\n 'button',\n extend(attributes, {\n type: 'button',\n role: 'menuitemradio',\n class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(),\n 'aria-checked': checked,\n value,\n }),\n );\n\n const flex = createElement('span');\n\n // We have to set as HTML incase of special characters\n flex.innerHTML = title;\n\n if (is.element(badge)) {\n flex.appendChild(badge);\n }\n\n menuItem.appendChild(flex);\n\n // Replicate radio button behaviour\n Object.defineProperty(menuItem, 'checked', {\n enumerable: true,\n get() {\n return menuItem.getAttribute('aria-checked') === 'true';\n },\n set(check) {\n // Ensure exclusivity\n if (check) {\n Array.from(menuItem.parentNode.children)\n .filter((node) => matches(node, '[role=\"menuitemradio\"]'))\n .forEach((node) => node.setAttribute('aria-checked', 'false'));\n }\n\n menuItem.setAttribute('aria-checked', check ? 'true' : 'false');\n },\n });\n\n this.listeners.bind(\n menuItem,\n 'click keyup',\n (event) => {\n if (is.keyboardEvent(event) && event.which !== 32) {\n return;\n }\n\n event.preventDefault();\n event.stopPropagation();\n\n menuItem.checked = true;\n\n switch (type) {\n case 'language':\n this.currentTrack = Number(value);\n break;\n\n case 'quality':\n this.quality = value;\n break;\n\n case 'speed':\n this.speed = parseFloat(value);\n break;\n\n default:\n break;\n }\n\n controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event));\n },\n type,\n false,\n );\n\n controls.bindMenuItemShortcuts.call(this, menuItem, type);\n\n list.appendChild(menuItem);\n },\n\n // Format a time for display\n formatTime(time = 0, inverted = false) {\n // Bail if the value isn't a number\n if (!is.number(time)) {\n return time;\n }\n\n // Always display hours if duration is over an hour\n const forceHours = getHours(this.duration) > 0;\n\n return formatTime(time, forceHours, inverted);\n },\n\n // Update the displayed time\n updateTimeDisplay(target = null, time = 0, inverted = false) {\n // Bail if there's no element to display or the value isn't a number\n if (!is.element(target) || !is.number(time)) {\n return;\n }\n\n // eslint-disable-next-line no-param-reassign\n target.innerText = controls.formatTime(time, inverted);\n },\n\n // Update volume UI and storage\n updateVolume() {\n if (!this.supported.ui) {\n return;\n }\n\n // Update range\n if (is.element(this.elements.inputs.volume)) {\n controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);\n }\n\n // Update mute state\n if (is.element(this.elements.buttons.mute)) {\n this.elements.buttons.mute.pressed = this.muted || this.volume === 0;\n }\n },\n\n // Update seek value and lower fill\n setRange(target, value = 0) {\n if (!is.element(target)) {\n return;\n }\n\n // eslint-disable-next-line\n target.value = value;\n\n // Webkit range fill\n controls.updateRangeFill.call(this, target);\n },\n\n // Update <progress> elements\n updateProgress(event) {\n if (!this.supported.ui || !is.event(event)) {\n return;\n }\n\n let value = 0;\n\n const setProgress = (target, input) => {\n const val = is.number(input) ? input : 0;\n const progress = is.element(target) ? target : this.elements.display.buffer;\n\n // Update value and label\n if (is.element(progress)) {\n progress.value = val;\n\n // Update text label inside\n const label = progress.getElementsByTagName('span')[0];\n if (is.element(label)) {\n label.childNodes[0].nodeValue = val;\n }\n }\n };\n\n if (event) {\n switch (event.type) {\n // Video playing\n case 'timeupdate':\n case 'seeking':\n case 'seeked':\n value = getPercentage(this.currentTime, this.duration);\n\n // Set seek range value only if it's a 'natural' time event\n if (event.type === 'timeupdate') {\n controls.setRange.call(this, this.elements.inputs.seek, value);\n }\n\n break;\n\n // Check buffer status\n case 'playing':\n case 'progress':\n setProgress(this.elements.display.buffer, this.buffered * 100);\n\n break;\n\n default:\n break;\n }\n }\n },\n\n // Webkit polyfill for lower fill range\n updateRangeFill(target) {\n // Get range from event if event passed\n const range = is.event(target) ? target.target : target;\n\n // Needs to be a valid <input type='range'>\n if (!is.element(range) || range.getAttribute('type') !== 'range') {\n return;\n }\n\n // Set aria values for https://github.com/sampotts/plyr/issues/905\n if (matches(range, this.config.selectors.inputs.seek)) {\n range.setAttribute('aria-valuenow', this.currentTime);\n const currentTime = controls.formatTime(this.currentTime);\n const duration = controls.formatTime(this.duration);\n const format = i18n.get('seekLabel', this.config);\n range.setAttribute(\n 'aria-valuetext',\n format.replace('{currentTime}', currentTime).replace('{duration}', duration),\n );\n } else if (matches(range, this.config.selectors.inputs.volume)) {\n const percent = range.value * 100;\n range.setAttribute('aria-valuenow', percent);\n range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`);\n } else {\n range.setAttribute('aria-valuenow', range.value);\n }\n\n // WebKit only\n if (!browser.isWebkit) {\n return;\n }\n\n // Set CSS custom property\n range.style.setProperty('--value', `${(range.value / range.max) * 100}%`);\n },\n\n // Update hover tooltip for seeking\n updateSeekTooltip(event) {\n // Bail if setting not true\n if (\n !this.config.tooltips.seek ||\n !is.element(this.elements.inputs.seek) ||\n !is.element(this.elements.display.seekTooltip) ||\n this.duration === 0\n ) {\n return;\n }\n\n const visible = `${this.config.classNames.tooltip}--visible`;\n const toggle = (show) => toggleClass(this.elements.display.seekTooltip, visible, show);\n\n // Hide on touch\n if (this.touch) {\n toggle(false);\n return;\n }\n\n // Determine percentage, if already visible\n let percent = 0;\n const clientRect = this.elements.progress.getBoundingClientRect();\n\n if (is.event(event)) {\n percent = (100 / clientRect.width) * (event.pageX - clientRect.left);\n } else if (hasClass(this.elements.display.seekTooltip, visible)) {\n percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);\n } else {\n return;\n }\n\n // Set bounds\n if (percent < 0) {\n percent = 0;\n } else if (percent > 100) {\n percent = 100;\n }\n\n // Display the time a click would seek to\n controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, (this.duration / 100) * percent);\n\n // Set position\n this.elements.display.seekTooltip.style.left = `${percent}%`;\n\n // Show/hide the tooltip\n // If the event is a moues in/out and percentage is inside bounds\n if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) {\n toggle(event.type === 'mouseenter');\n }\n },\n\n // Handle time change event\n timeUpdate(event) {\n // Only invert if only one time element is displayed and used for both duration and currentTime\n const invert = !is.element(this.elements.display.duration) && this.config.invertTime;\n\n // Duration\n controls.updateTimeDisplay.call(\n this,\n this.elements.display.currentTime,\n invert ? this.duration - this.currentTime : this.currentTime,\n invert,\n );\n\n // Ignore updates while seeking\n if (event && event.type === 'timeupdate' && this.media.seeking) {\n return;\n }\n\n // Playing progress\n controls.updateProgress.call(this, event);\n },\n\n // Show the duration on metadataloaded or durationchange events\n durationUpdate() {\n // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false\n if (!this.supported.ui || (!this.config.invertTime && this.currentTime)) {\n return;\n }\n\n // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar.\n // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415\n // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062\n // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338\n if (this.duration >= 2 ** 32) {\n toggleHidden(this.elements.display.currentTime, true);\n toggleHidden(this.elements.progress, true);\n return;\n }\n\n // Update ARIA values\n if (is.element(this.elements.inputs.seek)) {\n this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration);\n }\n\n // If there's a spot to display duration\n const hasDuration = is.element(this.elements.display.duration);\n\n // If there's only one time display, display duration there\n if (!hasDuration && this.config.displayDuration && this.paused) {\n controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);\n }\n\n // If there's a duration element, update content\n if (hasDuration) {\n controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);\n }\n\n // Update the tooltip (if visible)\n controls.updateSeekTooltip.call(this);\n },\n\n // Hide/show a tab\n toggleMenuButton(setting, toggle) {\n toggleHidden(this.elements.settings.buttons[setting], !toggle);\n },\n\n // Update the selected setting\n updateSetting(setting, container, input) {\n const pane = this.elements.settings.panels[setting];\n let value = null;\n let list = container;\n\n if (setting === 'captions') {\n value = this.currentTrack;\n } else {\n value = !is.empty(input) ? input : this[setting];\n\n // Get default\n if (is.empty(value)) {\n value = this.config[setting].default;\n }\n\n // Unsupported value\n if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) {\n this.debug.warn(`Unsupported value of '${value}' for ${setting}`);\n return;\n }\n\n // Disabled value\n if (!this.config[setting].options.includes(value)) {\n this.debug.warn(`Disabled value of '${value}' for ${setting}`);\n return;\n }\n }\n\n // Get the list if we need to\n if (!is.element(list)) {\n list = pane && pane.querySelector('[role=\"menu\"]');\n }\n\n // If there's no list it means it's not been rendered...\n if (!is.element(list)) {\n return;\n }\n\n // Update the label\n const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`);\n label.innerHTML = controls.getLabel.call(this, setting, value);\n\n // Find the radio option and check it\n const target = list && list.querySelector(`[value=\"${value}\"]`);\n\n if (is.element(target)) {\n target.checked = true;\n }\n },\n\n // Translate a value into a nice label\n getLabel(setting, value) {\n switch (setting) {\n case 'speed':\n return value === 1 ? i18n.get('normal', this.config) : `${value}×`;\n\n case 'quality':\n if (is.number(value)) {\n const label = i18n.get(`qualityLabel.${value}`, this.config);\n\n if (!label.length) {\n return `${value}p`;\n }\n\n return label;\n }\n\n return toTitleCase(value);\n\n case 'captions':\n return captions.getLabel.call(this);\n\n default:\n return null;\n }\n },\n\n // Set the quality menu\n setQualityMenu(options) {\n // Menu required\n if (!is.element(this.elements.settings.panels.quality)) {\n return;\n }\n\n const type = 'quality';\n const list = this.elements.settings.panels.quality.querySelector('[role=\"menu\"]');\n\n // Set options if passed and filter based on uniqueness and config\n if (is.array(options)) {\n this.options.quality = dedupe(options).filter((quality) => this.config.quality.options.includes(quality));\n }\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1;\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If we're hiding, nothing more to do\n if (!toggle) {\n return;\n }\n\n // Get the badge HTML for HD, 4K etc\n const getBadge = (quality) => {\n const label = i18n.get(`qualityBadge.${quality}`, this.config);\n\n if (!label.length) {\n return null;\n }\n\n return controls.createBadge.call(this, label);\n };\n\n // Sort options by the config and then render options\n this.options.quality\n .sort((a, b) => {\n const sorting = this.config.quality.options;\n return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1;\n })\n .forEach((quality) => {\n controls.createMenuItem.call(this, {\n value: quality,\n list,\n type,\n title: controls.getLabel.call(this, 'quality', quality),\n badge: getBadge(quality),\n });\n });\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Set the looping options\n /* setLoopMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.loop)) {\n return;\n }\n\n const options = ['start', 'end', 'all', 'reset'];\n const list = this.elements.settings.panels.loop.querySelector('[role=\"menu\"]');\n\n // Show the pane and tab\n toggleHidden(this.elements.settings.buttons.loop, false);\n toggleHidden(this.elements.settings.panels.loop, false);\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.loop.options);\n controls.toggleMenuButton.call(this, 'loop', toggle);\n\n // Empty the menu\n emptyElement(list);\n\n options.forEach(option => {\n const item = createElement('li');\n\n const button = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.loop), {\n type: 'button',\n class: this.config.classNames.control,\n 'data-plyr-loop-action': option,\n }),\n i18n.get(option, this.config)\n );\n\n if (['start', 'end'].includes(option)) {\n const badge = controls.createBadge.call(this, '00:00');\n button.appendChild(badge);\n }\n\n item.appendChild(button);\n list.appendChild(item);\n });\n }, */\n\n // Get current selected caption language\n // TODO: rework this to user the getter in the API?\n\n // Set a list of available captions languages\n setCaptionsMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.captions)) {\n return;\n }\n\n // TODO: Captions or language? Currently it's mixed\n const type = 'captions';\n const list = this.elements.settings.panels.captions.querySelector('[role=\"menu\"]');\n const tracks = captions.getTracks.call(this);\n const toggle = Boolean(tracks.length);\n\n // Toggle the pane and tab\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If there's no captions, bail\n if (!toggle) {\n return;\n }\n\n // Generate options data\n const options = tracks.map((track, value) => ({\n value,\n checked: this.captions.toggled && this.currentTrack === value,\n title: captions.getLabel.call(this, track),\n badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()),\n list,\n type: 'language',\n }));\n\n // Add the \"Disabled\" option to turn off captions\n options.unshift({\n value: -1,\n checked: !this.captions.toggled,\n title: i18n.get('disabled', this.config),\n list,\n type: 'language',\n });\n\n // Generate options\n options.forEach(controls.createMenuItem.bind(this));\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Set a list of available captions languages\n setSpeedMenu() {\n // Menu required\n if (!is.element(this.elements.settings.panels.speed)) {\n return;\n }\n\n const type = 'speed';\n const list = this.elements.settings.panels.speed.querySelector('[role=\"menu\"]');\n\n // Filter out invalid speeds\n this.options.speed = this.options.speed.filter((o) => o >= this.minimumSpeed && o <= this.maximumSpeed);\n\n // Toggle the pane and tab\n const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1;\n controls.toggleMenuButton.call(this, type, toggle);\n\n // Empty the menu\n emptyElement(list);\n\n // Check if we need to toggle the parent\n controls.checkMenu.call(this);\n\n // If we're hiding, nothing more to do\n if (!toggle) {\n return;\n }\n\n // Create items\n this.options.speed.forEach((speed) => {\n controls.createMenuItem.call(this, {\n value: speed,\n list,\n type,\n title: controls.getLabel.call(this, 'speed', speed),\n });\n });\n\n controls.updateSetting.call(this, type, list);\n },\n\n // Check if we need to hide/show the settings menu\n checkMenu() {\n const { buttons } = this.elements.settings;\n const visible = !is.empty(buttons) && Object.values(buttons).some((button) => !button.hidden);\n\n toggleHidden(this.elements.settings.menu, !visible);\n },\n\n // Focus the first menu item in a given (or visible) menu\n focusFirstMenuItem(pane, tabFocus = false) {\n if (this.elements.settings.popup.hidden) {\n return;\n }\n\n let target = pane;\n\n if (!is.element(target)) {\n target = Object.values(this.elements.settings.panels).find((p) => !p.hidden);\n }\n\n const firstItem = target.querySelector('[role^=\"menuitem\"]');\n\n setFocus.call(this, firstItem, tabFocus);\n },\n\n // Show/hide menu\n toggleMenu(input) {\n const { popup } = this.elements.settings;\n const button = this.elements.buttons.settings;\n\n // Menu and button are required\n if (!is.element(popup) || !is.element(button)) {\n return;\n }\n\n // True toggle by default\n const { hidden } = popup;\n let show = hidden;\n\n if (is.boolean(input)) {\n show = input;\n } else if (is.keyboardEvent(input) && input.which === 27) {\n show = false;\n } else if (is.event(input)) {\n // If Plyr is in a shadowDOM, the event target is set to the component, instead of the\n // Element in the shadowDOM. The path, if available, is complete.\n const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target;\n const isMenuItem = popup.contains(target);\n\n // If the click was inside the menu or if the click\n // wasn't the button or menu item and we're trying to\n // show the menu (a doc click shouldn't show the menu)\n if (isMenuItem || (!isMenuItem && input.target !== button && show)) {\n return;\n }\n }\n\n // Set button attributes\n button.setAttribute('aria-expanded', show);\n\n // Show the actual popup\n toggleHidden(popup, !show);\n\n // Add class hook\n toggleClass(this.elements.container, this.config.classNames.menu.open, show);\n\n // Focus the first item if key interaction\n if (show && is.keyboardEvent(input)) {\n controls.focusFirstMenuItem.call(this, null, true);\n } else if (!show && !hidden) {\n // If closing, re-focus the button\n setFocus.call(this, button, is.keyboardEvent(input));\n }\n },\n\n // Get the natural size of a menu panel\n getMenuSize(tab) {\n const clone = tab.cloneNode(true);\n clone.style.position = 'absolute';\n clone.style.opacity = 0;\n clone.removeAttribute('hidden');\n\n // Append to parent so we get the \"real\" size\n tab.parentNode.appendChild(clone);\n\n // Get the sizes before we remove\n const width = clone.scrollWidth;\n const height = clone.scrollHeight;\n\n // Remove from the DOM\n removeElement(clone);\n\n return {\n width,\n height,\n };\n },\n\n // Show a panel in the menu\n showMenuPanel(type = '', tabFocus = false) {\n const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`);\n\n // Nothing to show, bail\n if (!is.element(target)) {\n return;\n }\n\n // Hide all other panels\n const container = target.parentNode;\n const current = Array.from(container.children).find((node) => !node.hidden);\n\n // If we can do fancy animations, we'll animate the height/width\n if (support.transitions && !support.reducedMotion) {\n // Set the current width as a base\n container.style.width = `${current.scrollWidth}px`;\n container.style.height = `${current.scrollHeight}px`;\n\n // Get potential sizes\n const size = controls.getMenuSize.call(this, target);\n\n // Restore auto height/width\n const restore = (event) => {\n // We're only bothered about height and width on the container\n if (event.target !== container || !['width', 'height'].includes(event.propertyName)) {\n return;\n }\n\n // Revert back to auto\n container.style.width = '';\n container.style.height = '';\n\n // Only listen once\n off.call(this, container, transitionEndEvent, restore);\n };\n\n // Listen for the transition finishing and restore auto height/width\n on.call(this, container, transitionEndEvent, restore);\n\n // Set dimensions to target\n container.style.width = `${size.width}px`;\n container.style.height = `${size.height}px`;\n }\n\n // Set attributes on current tab\n toggleHidden(current, true);\n\n // Set attributes on target\n toggleHidden(target, false);\n\n // Focus the first item\n controls.focusFirstMenuItem.call(this, target, tabFocus);\n },\n\n // Set the download URL\n setDownloadUrl() {\n const button = this.elements.buttons.download;\n\n // Bail if no button\n if (!is.element(button)) {\n return;\n }\n\n // Set attribute\n button.setAttribute('href', this.download);\n },\n\n // Build the default HTML\n create(data) {\n const {\n bindMenuItemShortcuts,\n createButton,\n createProgress,\n createRange,\n createTime,\n setQualityMenu,\n setSpeedMenu,\n showMenuPanel,\n } = controls;\n this.elements.controls = null;\n\n // Larger overlaid play button\n if (is.array(this.config.controls) && this.config.controls.includes('play-large')) {\n this.elements.container.appendChild(createButton.call(this, 'play-large'));\n }\n\n // Create the container\n const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper));\n this.elements.controls = container;\n\n // Default item attributes\n const defaultAttributes = { class: 'plyr__controls__item' };\n\n // Loop through controls in order\n dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach((control) => {\n // Restart button\n if (control === 'restart') {\n container.appendChild(createButton.call(this, 'restart', defaultAttributes));\n }\n\n // Rewind button\n if (control === 'rewind') {\n container.appendChild(createButton.call(this, 'rewind', defaultAttributes));\n }\n\n // Play/Pause button\n if (control === 'play') {\n container.appendChild(createButton.call(this, 'play', defaultAttributes));\n }\n\n // Fast forward button\n if (control === 'fast-forward') {\n container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes));\n }\n\n // Progress\n if (control === 'progress') {\n const progressContainer = createElement('div', {\n class: `${defaultAttributes.class} plyr__progress__container`,\n });\n\n const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress));\n\n // Seek range slider\n progress.appendChild(\n createRange.call(this, 'seek', {\n id: `plyr-seek-${data.id}`,\n }),\n );\n\n // Buffer progress\n progress.appendChild(createProgress.call(this, 'buffer'));\n\n // TODO: Add loop display indicator\n\n // Seek tooltip\n if (this.config.tooltips.seek) {\n const tooltip = createElement(\n 'span',\n {\n class: this.config.classNames.tooltip,\n },\n '00:00',\n );\n\n progress.appendChild(tooltip);\n this.elements.display.seekTooltip = tooltip;\n }\n\n this.elements.progress = progress;\n progressContainer.appendChild(this.elements.progress);\n container.appendChild(progressContainer);\n }\n\n // Media current time display\n if (control === 'current-time') {\n container.appendChild(createTime.call(this, 'currentTime', defaultAttributes));\n }\n\n // Media duration display\n if (control === 'duration') {\n container.appendChild(createTime.call(this, 'duration', defaultAttributes));\n }\n\n // Volume controls\n if (control === 'mute' || control === 'volume') {\n let { volume } = this.elements;\n\n // Create the volume container if needed\n if (!is.element(volume) || !container.contains(volume)) {\n volume = createElement(\n 'div',\n extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__volume`.trim(),\n }),\n );\n\n this.elements.volume = volume;\n\n container.appendChild(volume);\n }\n\n // Toggle mute button\n if (control === 'mute') {\n volume.appendChild(createButton.call(this, 'mute'));\n }\n\n // Volume range control\n // Ignored on iOS as it's handled globally\n // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html\n if (control === 'volume' && !browser.isIos) {\n // Set the attributes\n const attributes = {\n max: 1,\n step: 0.05,\n value: this.config.volume,\n };\n\n // Create the volume range slider\n volume.appendChild(\n createRange.call(\n this,\n 'volume',\n extend(attributes, {\n id: `plyr-volume-${data.id}`,\n }),\n ),\n );\n }\n }\n\n // Toggle captions button\n if (control === 'captions') {\n container.appendChild(createButton.call(this, 'captions', defaultAttributes));\n }\n\n // Settings button / menu\n if (control === 'settings' && !is.empty(this.config.settings)) {\n const wrapper = createElement(\n 'div',\n extend({}, defaultAttributes, {\n class: `${defaultAttributes.class} plyr__menu`.trim(),\n hidden: '',\n }),\n );\n\n wrapper.appendChild(\n createButton.call(this, 'settings', {\n 'aria-haspopup': true,\n 'aria-controls': `plyr-settings-${data.id}`,\n 'aria-expanded': false,\n }),\n );\n\n const popup = createElement('div', {\n class: 'plyr__menu__container',\n id: `plyr-settings-${data.id}`,\n hidden: '',\n });\n\n const inner = createElement('div');\n\n const home = createElement('div', {\n id: `plyr-settings-${data.id}-home`,\n });\n\n // Create the menu\n const menu = createElement('div', {\n role: 'menu',\n });\n\n home.appendChild(menu);\n inner.appendChild(home);\n this.elements.settings.panels.home = home;\n\n // Build the menu items\n this.config.settings.forEach((type) => {\n // TODO: bundle this with the createMenuItem helper and bindings\n const menuItem = createElement(\n 'button',\n extend(getAttributesFromSelector(this.config.selectors.buttons.settings), {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`,\n role: 'menuitem',\n 'aria-haspopup': true,\n hidden: '',\n }),\n );\n\n // Bind menu shortcuts for keyboard users\n bindMenuItemShortcuts.call(this, menuItem, type);\n\n // Show menu on click\n on.call(this, menuItem, 'click', () => {\n showMenuPanel.call(this, type, false);\n });\n\n const flex = createElement('span', null, i18n.get(type, this.config));\n\n const value = createElement('span', {\n class: this.config.classNames.menu.value,\n });\n\n // Speed contains HTML entities\n value.innerHTML = data[type];\n\n flex.appendChild(value);\n menuItem.appendChild(flex);\n menu.appendChild(menuItem);\n\n // Build the panes\n const pane = createElement('div', {\n id: `plyr-settings-${data.id}-${type}`,\n hidden: '',\n });\n\n // Back button\n const backButton = createElement('button', {\n type: 'button',\n class: `${this.config.classNames.control} ${this.config.classNames.control}--back`,\n });\n\n // Visible label\n backButton.appendChild(\n createElement(\n 'span',\n {\n 'aria-hidden': true,\n },\n i18n.get(type, this.config),\n ),\n );\n\n // Screen reader label\n backButton.appendChild(\n createElement(\n 'span',\n {\n class: this.config.classNames.hidden,\n },\n i18n.get('menuBack', this.config),\n ),\n );\n\n // Go back via keyboard\n on.call(\n this,\n pane,\n 'keydown',\n (event) => {\n // We only care about <-\n if (event.which !== 37) {\n return;\n }\n\n // Prevent seek\n event.preventDefault();\n event.stopPropagation();\n\n // Show the respective menu\n showMenuPanel.call(this, 'home', true);\n },\n false,\n );\n\n // Go back via button click\n on.call(this, backButton, 'click', () => {\n showMenuPanel.call(this, 'home', false);\n });\n\n // Add to pane\n pane.appendChild(backButton);\n\n // Menu\n pane.appendChild(\n createElement('div', {\n role: 'menu',\n }),\n );\n\n inner.appendChild(pane);\n\n this.elements.settings.buttons[type] = menuItem;\n this.elements.settings.panels[type] = pane;\n });\n\n popup.appendChild(inner);\n wrapper.appendChild(popup);\n container.appendChild(wrapper);\n\n this.elements.settings.popup = popup;\n this.elements.settings.menu = wrapper;\n }\n\n // Picture in picture button\n if (control === 'pip' && support.pip) {\n container.appendChild(createButton.call(this, 'pip', defaultAttributes));\n }\n\n // Airplay button\n if (control === 'airplay' && support.airplay) {\n container.appendChild(createButton.call(this, 'airplay', defaultAttributes));\n }\n\n // Download button\n if (control === 'download') {\n const attributes = extend({}, defaultAttributes, {\n element: 'a',\n href: this.download,\n target: '_blank',\n });\n\n // Set download attribute for HTML5 only\n if (this.isHTML5) {\n attributes.download = '';\n }\n\n const { download } = this.config.urls;\n\n if (!is.url(download) && this.isEmbed) {\n extend(attributes, {\n icon: `logo-${this.provider}`,\n label: this.provider,\n });\n }\n\n container.appendChild(createButton.call(this, 'download', attributes));\n }\n\n // Toggle fullscreen button\n if (control === 'fullscreen') {\n container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes));\n }\n });\n\n // Set available quality levels\n if (this.isHTML5) {\n setQualityMenu.call(this, html5.getQualityOptions.call(this));\n }\n\n setSpeedMenu.call(this);\n\n return container;\n },\n\n // Insert controls\n inject() {\n // Sprite\n if (this.config.loadSprite) {\n const icon = controls.getIconUrl.call(this);\n\n // Only load external sprite using AJAX\n if (icon.cors) {\n loadSprite(icon.url, 'sprite-plyr');\n }\n }\n\n // Create a unique ID\n this.id = Math.floor(Math.random() * 10000);\n\n // Null by default\n let container = null;\n this.elements.controls = null;\n\n // Set template properties\n const props = {\n id: this.id,\n seektime: this.config.seekTime,\n title: this.config.title,\n };\n let update = true;\n\n // If function, run it and use output\n if (is.function(this.config.controls)) {\n this.config.controls = this.config.controls.call(this, props);\n }\n\n // Convert falsy controls to empty array (primarily for empty strings)\n if (!this.config.controls) {\n this.config.controls = [];\n }\n\n if (is.element(this.config.controls) || is.string(this.config.controls)) {\n // HTMLElement or Non-empty string passed as the option\n container = this.config.controls;\n } else {\n // Create controls\n container = controls.create.call(this, {\n id: this.id,\n seektime: this.config.seekTime,\n speed: this.speed,\n quality: this.quality,\n captions: captions.getLabel.call(this),\n // TODO: Looping\n // loop: 'None',\n });\n update = false;\n }\n\n // Replace props with their value\n const replace = (input) => {\n let result = input;\n\n Object.entries(props).forEach(([key, value]) => {\n result = replaceAll(result, `{${key}}`, value);\n });\n\n return result;\n };\n\n // Update markup\n if (update) {\n if (is.string(this.config.controls)) {\n container = replace(container);\n }\n }\n\n // Controls container\n let target;\n\n // Inject to custom location\n if (is.string(this.config.selectors.controls.container)) {\n target = document.querySelector(this.config.selectors.controls.container);\n }\n\n // Inject into the container by default\n if (!is.element(target)) {\n target = this.elements.container;\n }\n\n // Inject controls HTML (needs to be before captions, hence \"afterbegin\")\n const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML';\n target[insertMethod]('afterbegin', container);\n\n // Find the elements if need be\n if (!is.element(this.elements.controls)) {\n controls.findElements.call(this);\n }\n\n // Add pressed property to buttons\n if (!is.empty(this.elements.buttons)) {\n const addProperty = (button) => {\n const className = this.config.classNames.controlPressed;\n Object.defineProperty(button, 'pressed', {\n enumerable: true,\n get() {\n return hasClass(button, className);\n },\n set(pressed = false) {\n toggleClass(button, className, pressed);\n },\n });\n };\n\n // Toggle classname when pressed property is set\n Object.values(this.elements.buttons)\n .filter(Boolean)\n .forEach((button) => {\n if (is.array(button) || is.nodeList(button)) {\n Array.from(button).filter(Boolean).forEach(addProperty);\n } else {\n addProperty(button);\n }\n });\n }\n\n // Edge sometimes doesn't finish the paint so force a repaint\n if (browser.isEdge) {\n repaint(target);\n }\n\n // Setup tooltips\n if (this.config.tooltips.controls) {\n const { classNames, selectors } = this.config;\n const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`;\n const labels = getElements.call(this, selector);\n\n Array.from(labels).forEach((label) => {\n toggleClass(label, this.config.classNames.hidden, false);\n toggleClass(label, this.config.classNames.tooltip, true);\n });\n }\n },\n};\n\nexport default controls;\n","// ==========================================================================\n// URL utils\n// ==========================================================================\n\nimport is from './is';\n\n/**\n * Parse a string to a URL object\n * @param {String} input - the URL to be parsed\n * @param {Boolean} safe - failsafe parsing\n */\nexport function parseUrl(input, safe = true) {\n let url = input;\n\n if (safe) {\n const parser = document.createElement('a');\n parser.href = url;\n url = parser.href;\n }\n\n try {\n return new URL(url);\n } catch (_) {\n return null;\n }\n}\n\n// Convert object to URLSearchParams\nexport function buildUrlParams(input) {\n const params = new URLSearchParams();\n\n if (is.object(input)) {\n Object.entries(input).forEach(([key, value]) => {\n params.set(key, value);\n });\n }\n\n return params;\n}\n","// ==========================================================================\n// Plyr Captions\n// TODO: Create as class\n// ==========================================================================\n\nimport controls from './controls';\nimport support from './support';\nimport { dedupe } from './utils/arrays';\nimport browser from './utils/browser';\nimport {\n createElement,\n emptyElement,\n getAttributesFromSelector,\n insertAfter,\n removeElement,\n toggleClass,\n} from './utils/elements';\nimport { on, triggerEvent } from './utils/events';\nimport fetch from './utils/fetch';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport { getHTML } from './utils/strings';\nimport { parseUrl } from './utils/urls';\n\nconst captions = {\n // Setup captions\n setup() {\n // Requires UI support\n if (!this.supported.ui) {\n return;\n }\n\n // Only Vimeo and HTML5 video supported at this point\n if (!this.isVideo || this.isYouTube || (this.isHTML5 && !support.textTracks)) {\n // Clear menu and hide\n if (\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n this.config.settings.includes('captions')\n ) {\n controls.setCaptionsMenu.call(this);\n }\n\n return;\n }\n\n // Inject the container\n if (!is.element(this.elements.captions)) {\n this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions));\n\n insertAfter(this.elements.captions, this.elements.wrapper);\n }\n\n // Fix IE captions if CORS is used\n // Fetch captions and inject as blobs instead (data URIs not supported!)\n if (browser.isIE && window.URL) {\n const elements = this.media.querySelectorAll('track');\n\n Array.from(elements).forEach((track) => {\n const src = track.getAttribute('src');\n const url = parseUrl(src);\n\n if (\n url !== null &&\n url.hostname !== window.location.href.hostname &&\n ['http:', 'https:'].includes(url.protocol)\n ) {\n fetch(src, 'blob')\n .then((blob) => {\n track.setAttribute('src', window.URL.createObjectURL(blob));\n })\n .catch(() => {\n removeElement(track);\n });\n }\n });\n }\n\n // Get and set initial data\n // The \"preferred\" options are not realized unless / until the wanted language has a match\n // * languages: Array of user's browser languages.\n // * language: The language preferred by user settings or config\n // * active: The state preferred by user settings or config\n // * toggled: The real captions state\n\n const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en'];\n const languages = dedupe(browserLanguages.map((language) => language.split('-')[0]));\n let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase();\n\n // Use first browser language when language is 'auto'\n if (language === 'auto') {\n [language] = languages;\n }\n\n let active = this.storage.get('captions');\n if (!is.boolean(active)) {\n ({ active } = this.config.captions);\n }\n\n Object.assign(this.captions, {\n toggled: false,\n active,\n language,\n languages,\n });\n\n // Watch changes to textTracks and update captions menu\n if (this.isHTML5) {\n const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack';\n on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this));\n }\n\n // Update available languages in list next tick (the event must not be triggered before the listeners)\n setTimeout(captions.update.bind(this), 0);\n },\n\n // Update available language options in settings based on tracks\n update() {\n const tracks = captions.getTracks.call(this, true);\n // Get the wanted language\n const { active, language, meta, currentTrackNode } = this.captions;\n const languageExists = Boolean(tracks.find((track) => track.language === language));\n\n // Handle tracks (add event listener and \"pseudo\"-default)\n if (this.isHTML5 && this.isVideo) {\n tracks\n .filter((track) => !meta.get(track))\n .forEach((track) => {\n this.debug.log('Track added', track);\n\n // Attempt to store if the original dom element was \"default\"\n meta.set(track, {\n default: track.mode === 'showing',\n });\n\n // Turn off native caption rendering to avoid double captions\n // Note: mode='hidden' forces a track to download. To ensure every track\n // isn't downloaded at once, only 'showing' tracks should be reassigned\n // eslint-disable-next-line no-param-reassign\n if (track.mode === 'showing') {\n // eslint-disable-next-line no-param-reassign\n track.mode = 'hidden';\n }\n\n // Add event listener for cue changes\n on.call(this, track, 'cuechange', () => captions.updateCues.call(this));\n });\n }\n\n // Update language first time it matches, or if the previous matching track was removed\n if ((languageExists && this.language !== language) || !tracks.includes(currentTrackNode)) {\n captions.setLanguage.call(this, language);\n captions.toggle.call(this, active && languageExists);\n }\n\n // Enable or disable captions based on track length\n if (this.elements) {\n toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks));\n }\n\n // Update available languages in list\n if (\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n this.config.settings.includes('captions')\n ) {\n controls.setCaptionsMenu.call(this);\n }\n },\n\n // Toggle captions display\n // Used internally for the toggleCaptions method, with the passive option forced to false\n toggle(input, passive = true) {\n // If there's no full support\n if (!this.supported.ui) {\n return;\n }\n\n const { toggled } = this.captions; // Current state\n const activeClass = this.config.classNames.captions.active;\n // Get the next state\n // If the method is called without parameter, toggle based on current value\n const active = is.nullOrUndefined(input) ? !toggled : input;\n\n // Update state and trigger event\n if (active !== toggled) {\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.active = active;\n this.storage.set({ captions: active });\n }\n\n // Force language if the call isn't passive and there is no matching language to toggle to\n if (!this.language && active && !passive) {\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true);\n\n // Override user preferences to avoid switching languages if a matching track is added\n this.captions.language = track.language;\n\n // Set caption, but don't store in localStorage as user preference\n captions.set.call(this, tracks.indexOf(track));\n return;\n }\n\n // Toggle button if it's enabled\n if (this.elements.buttons.captions) {\n this.elements.buttons.captions.pressed = active;\n }\n\n // Add class hook\n toggleClass(this.elements.container, activeClass, active);\n\n this.captions.toggled = active;\n\n // Update settings menu\n controls.updateSetting.call(this, 'captions');\n\n // Trigger event (not used internally)\n triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled');\n }\n\n // Wait for the call stack to clear before setting mode='hidden'\n // on the active track - forcing the browser to download it\n setTimeout(() => {\n if (active && this.captions.toggled) {\n this.captions.currentTrackNode.mode = 'hidden';\n }\n });\n },\n\n // Set captions by track index\n // Used internally for the currentTrack setter with the passive option forced to false\n set(index, passive = true) {\n const tracks = captions.getTracks.call(this);\n\n // Disable captions if setting to -1\n if (index === -1) {\n captions.toggle.call(this, false, passive);\n return;\n }\n\n if (!is.number(index)) {\n this.debug.warn('Invalid caption argument', index);\n return;\n }\n\n if (!(index in tracks)) {\n this.debug.warn('Track not found', index);\n return;\n }\n\n if (this.captions.currentTrack !== index) {\n this.captions.currentTrack = index;\n const track = tracks[index];\n const { language } = track || {};\n\n // Store reference to node for invalidation on remove\n this.captions.currentTrackNode = track;\n\n // Update settings menu\n controls.updateSetting.call(this, 'captions');\n\n // When passive, don't override user preferences\n if (!passive) {\n this.captions.language = language;\n this.storage.set({ language });\n }\n\n // Handle Vimeo captions\n if (this.isVimeo) {\n this.embed.enableTextTrack(language);\n }\n\n // Trigger event\n triggerEvent.call(this, this.media, 'languagechange');\n }\n\n // Show captions\n captions.toggle.call(this, true, passive);\n\n if (this.isHTML5 && this.isVideo) {\n // If we change the active track while a cue is already displayed we need to update it\n captions.updateCues.call(this);\n }\n },\n\n // Set captions by language\n // Used internally for the language setter with the passive option forced to false\n setLanguage(input, passive = true) {\n if (!is.string(input)) {\n this.debug.warn('Invalid language argument', input);\n return;\n }\n // Normalize\n const language = input.toLowerCase();\n this.captions.language = language;\n\n // Set currentTrack\n const tracks = captions.getTracks.call(this);\n const track = captions.findTrack.call(this, [language]);\n captions.set.call(this, tracks.indexOf(track), passive);\n },\n\n // Get current valid caption tracks\n // If update is false it will also ignore tracks without metadata\n // This is used to \"freeze\" the language options when captions.update is false\n getTracks(update = false) {\n // Handle media or textTracks missing or null\n const tracks = Array.from((this.media || {}).textTracks || []);\n // For HTML5, use cache instead of current tracks when it exists (if captions.update is false)\n // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata)\n return tracks\n .filter((track) => !this.isHTML5 || update || this.captions.meta.has(track))\n .filter((track) => ['captions', 'subtitles'].includes(track.kind));\n },\n\n // Match tracks based on languages and get the first\n findTrack(languages, force = false) {\n const tracks = captions.getTracks.call(this);\n const sortIsDefault = (track) => Number((this.captions.meta.get(track) || {}).default);\n const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a));\n let track;\n\n languages.every((language) => {\n track = sorted.find((t) => t.language === language);\n return !track; // Break iteration if there is a match\n });\n\n // If no match is found but is required, get first\n return track || (force ? sorted[0] : undefined);\n },\n\n // Get the current track\n getCurrentTrack() {\n return captions.getTracks.call(this)[this.currentTrack];\n },\n\n // Get UI label for track\n getLabel(track) {\n let currentTrack = track;\n\n if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) {\n currentTrack = captions.getCurrentTrack.call(this);\n }\n\n if (is.track(currentTrack)) {\n if (!is.empty(currentTrack.label)) {\n return currentTrack.label;\n }\n\n if (!is.empty(currentTrack.language)) {\n return track.language.toUpperCase();\n }\n\n return i18n.get('enabled', this.config);\n }\n\n return i18n.get('disabled', this.config);\n },\n\n // Update captions using current track's active cues\n // Also optional array argument in case there isn't any track (ex: vimeo)\n updateCues(input) {\n // Requires UI\n if (!this.supported.ui) {\n return;\n }\n\n if (!is.element(this.elements.captions)) {\n this.debug.warn('No captions element to render to');\n return;\n }\n\n // Only accept array or empty input\n if (!is.nullOrUndefined(input) && !Array.isArray(input)) {\n this.debug.warn('updateCues: Invalid input', input);\n return;\n }\n\n let cues = input;\n\n // Get cues from track\n if (!cues) {\n const track = captions.getCurrentTrack.call(this);\n\n cues = Array.from((track || {}).activeCues || [])\n .map((cue) => cue.getCueAsHTML())\n .map(getHTML);\n }\n\n // Set new caption text\n const content = cues.map((cueText) => cueText.trim()).join('\\n');\n const changed = content !== this.elements.captions.innerHTML;\n\n if (changed) {\n // Empty the container and create a new child element\n emptyElement(this.elements.captions);\n const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption));\n caption.innerHTML = content;\n this.elements.captions.appendChild(caption);\n\n // Trigger event\n triggerEvent.call(this, this.media, 'cuechange');\n }\n },\n};\n\nexport default captions;\n","// ==========================================================================\n// Plyr default config\n// ==========================================================================\n\nconst defaults = {\n // Disable\n enabled: true,\n\n // Custom media title\n title: '',\n\n // Logging to console\n debug: false,\n\n // Auto play (if supported)\n autoplay: false,\n\n // Only allow one media playing at once (vimeo only)\n autopause: true,\n\n // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present)\n // TODO: Remove iosNative fullscreen option in favour of this (logic needs work)\n playsinline: true,\n\n // Default time to skip when rewind/fast forward\n seekTime: 10,\n\n // Default volume\n volume: 1,\n muted: false,\n\n // Pass a custom duration\n duration: null,\n\n // Display the media duration on load in the current time position\n // If you have opted to display both duration and currentTime, this is ignored\n displayDuration: true,\n\n // Invert the current time to be a countdown\n invertTime: true,\n\n // Clicking the currentTime inverts it's value to show time left rather than elapsed\n toggleInvert: true,\n\n // Force an aspect ratio\n // The format must be `'w:h'` (e.g. `'16:9'`)\n ratio: null,\n\n // Click video container to play/pause\n clickToPlay: true,\n\n // Auto hide the controls\n hideControls: true,\n\n // Reset to start when playback ended\n resetOnEnd: false,\n\n // Disable the standard context menu\n disableContextMenu: true,\n\n // Sprite (for icons)\n loadSprite: true,\n iconPrefix: 'plyr',\n iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg',\n\n // Blank video (used to prevent errors on source change)\n blankVideo: 'https://cdn.plyr.io/static/blank.mp4',\n\n // Quality default\n quality: {\n default: 576,\n // The options to display in the UI, if available for the source media\n options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240],\n forced: false,\n onChange: null,\n },\n\n // Set loops\n loop: {\n active: false,\n // start: null,\n // end: null,\n },\n\n // Speed default and options to display\n speed: {\n selected: 1,\n // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x)\n options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4],\n },\n\n // Keyboard shortcut settings\n keyboard: {\n focused: true,\n global: false,\n },\n\n // Display tooltips\n tooltips: {\n controls: false,\n seek: true,\n },\n\n // Captions settings\n captions: {\n active: false,\n language: 'auto',\n // Listen to new tracks added after Plyr is initialized.\n // This is needed for streaming captions, but may result in unselectable options\n update: false,\n },\n\n // Fullscreen settings\n fullscreen: {\n enabled: true, // Allow fullscreen?\n fallback: true, // Fallback using full viewport/window\n iosNative: false, // Use the native fullscreen in iOS (disables custom controls)\n // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode\n // Non-ancestors of the player element will be ignored\n // container: null, // defaults to the player element\n },\n\n // Local storage\n storage: {\n enabled: true,\n key: 'plyr',\n },\n\n // Default controls\n controls: [\n 'play-large',\n // 'restart',\n // 'rewind',\n 'play',\n // 'fast-forward',\n 'progress',\n 'current-time',\n // 'duration',\n 'mute',\n 'volume',\n 'captions',\n 'settings',\n 'pip',\n 'airplay',\n // 'download',\n 'fullscreen',\n ],\n settings: ['captions', 'quality', 'speed'],\n\n // Localisation\n i18n: {\n restart: 'Restart',\n rewind: 'Rewind {seektime}s',\n play: 'Play',\n pause: 'Pause',\n fastForward: 'Forward {seektime}s',\n seek: 'Seek',\n seekLabel: '{currentTime} of {duration}',\n played: 'Played',\n buffered: 'Buffered',\n currentTime: 'Current time',\n duration: 'Duration',\n volume: 'Volume',\n mute: 'Mute',\n unmute: 'Unmute',\n enableCaptions: 'Enable captions',\n disableCaptions: 'Disable captions',\n download: 'Download',\n enterFullscreen: 'Enter fullscreen',\n exitFullscreen: 'Exit fullscreen',\n frameTitle: 'Player for {title}',\n captions: 'Captions',\n settings: 'Settings',\n pip: 'PIP',\n menuBack: 'Go back to previous menu',\n speed: 'Speed',\n normal: 'Normal',\n quality: 'Quality',\n loop: 'Loop',\n start: 'Start',\n end: 'End',\n all: 'All',\n reset: 'Reset',\n disabled: 'Disabled',\n enabled: 'Enabled',\n advertisement: 'Ad',\n qualityBadge: {\n 2160: '4K',\n 1440: 'HD',\n 1080: 'HD',\n 720: 'HD',\n 576: 'SD',\n 480: 'SD',\n },\n },\n\n // URLs\n urls: {\n download: null,\n vimeo: {\n sdk: 'https://player.vimeo.com/api/player.js',\n iframe: 'https://player.vimeo.com/video/{0}?{1}',\n api: 'https://vimeo.com/api/oembed.json?url={0}',\n },\n youtube: {\n sdk: 'https://www.youtube.com/iframe_api',\n api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}',\n },\n googleIMA: {\n sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js',\n },\n },\n\n // Custom control listeners\n listeners: {\n seek: null,\n play: null,\n pause: null,\n restart: null,\n rewind: null,\n fastForward: null,\n mute: null,\n volume: null,\n captions: null,\n download: null,\n fullscreen: null,\n pip: null,\n airplay: null,\n speed: null,\n quality: null,\n loop: null,\n language: null,\n },\n\n // Events to watch and bubble\n events: [\n // Events to watch on HTML5 media elements and bubble\n // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events\n 'ended',\n 'progress',\n 'stalled',\n 'playing',\n 'waiting',\n 'canplay',\n 'canplaythrough',\n 'loadstart',\n 'loadeddata',\n 'loadedmetadata',\n 'timeupdate',\n 'volumechange',\n 'play',\n 'pause',\n 'error',\n 'seeking',\n 'seeked',\n 'emptied',\n 'ratechange',\n 'cuechange',\n\n // Custom events\n 'download',\n 'enterfullscreen',\n 'exitfullscreen',\n 'captionsenabled',\n 'captionsdisabled',\n 'languagechange',\n 'controlshidden',\n 'controlsshown',\n 'ready',\n\n // YouTube\n 'statechange',\n\n // Quality\n 'qualitychange',\n\n // Ads\n 'adsloaded',\n 'adscontentpause',\n 'adscontentresume',\n 'adstarted',\n 'adsmidpoint',\n 'adscomplete',\n 'adsallcomplete',\n 'adsimpression',\n 'adsclick',\n ],\n\n // Selectors\n // Change these to match your template if using custom HTML\n selectors: {\n editable: 'input, textarea, select, [contenteditable]',\n container: '.plyr',\n controls: {\n container: null,\n wrapper: '.plyr__controls',\n },\n labels: '[data-plyr]',\n buttons: {\n play: '[data-plyr=\"play\"]',\n pause: '[data-plyr=\"pause\"]',\n restart: '[data-plyr=\"restart\"]',\n rewind: '[data-plyr=\"rewind\"]',\n fastForward: '[data-plyr=\"fast-forward\"]',\n mute: '[data-plyr=\"mute\"]',\n captions: '[data-plyr=\"captions\"]',\n download: '[data-plyr=\"download\"]',\n fullscreen: '[data-plyr=\"fullscreen\"]',\n pip: '[data-plyr=\"pip\"]',\n airplay: '[data-plyr=\"airplay\"]',\n settings: '[data-plyr=\"settings\"]',\n loop: '[data-plyr=\"loop\"]',\n },\n inputs: {\n seek: '[data-plyr=\"seek\"]',\n volume: '[data-plyr=\"volume\"]',\n speed: '[data-plyr=\"speed\"]',\n language: '[data-plyr=\"language\"]',\n quality: '[data-plyr=\"quality\"]',\n },\n display: {\n currentTime: '.plyr__time--current',\n duration: '.plyr__time--duration',\n buffer: '.plyr__progress__buffer',\n loop: '.plyr__progress__loop', // Used later\n volume: '.plyr__volume--display',\n },\n progress: '.plyr__progress',\n captions: '.plyr__captions',\n caption: '.plyr__caption',\n },\n\n // Class hooks added to the player in different states\n classNames: {\n type: 'plyr--{0}',\n provider: 'plyr--{0}',\n video: 'plyr__video-wrapper',\n embed: 'plyr__video-embed',\n videoFixedRatio: 'plyr__video-wrapper--fixed-ratio',\n embedContainer: 'plyr__video-embed__container',\n poster: 'plyr__poster',\n posterEnabled: 'plyr__poster-enabled',\n ads: 'plyr__ads',\n control: 'plyr__control',\n controlPressed: 'plyr__control--pressed',\n playing: 'plyr--playing',\n paused: 'plyr--paused',\n stopped: 'plyr--stopped',\n loading: 'plyr--loading',\n hover: 'plyr--hover',\n tooltip: 'plyr__tooltip',\n cues: 'plyr__cues',\n hidden: 'plyr__sr-only',\n hideControls: 'plyr--hide-controls',\n isIos: 'plyr--is-ios',\n isTouch: 'plyr--is-touch',\n uiSupported: 'plyr--full-ui',\n noTransition: 'plyr--no-transition',\n display: {\n time: 'plyr__time',\n },\n menu: {\n value: 'plyr__menu__value',\n badge: 'plyr__badge',\n open: 'plyr--menu-open',\n },\n captions: {\n enabled: 'plyr--captions-enabled',\n active: 'plyr--captions-active',\n },\n fullscreen: {\n enabled: 'plyr--fullscreen-enabled',\n fallback: 'plyr--fullscreen-fallback',\n },\n pip: {\n supported: 'plyr--pip-supported',\n active: 'plyr--pip-active',\n },\n airplay: {\n supported: 'plyr--airplay-supported',\n active: 'plyr--airplay-active',\n },\n tabFocus: 'plyr__tab-focus',\n previewThumbnails: {\n // Tooltip thumbs\n thumbContainer: 'plyr__preview-thumb',\n thumbContainerShown: 'plyr__preview-thumb--is-shown',\n imageContainer: 'plyr__preview-thumb__image-container',\n timeContainer: 'plyr__preview-thumb__time-container',\n // Scrubbing\n scrubbingContainer: 'plyr__preview-scrubbing',\n scrubbingContainerShown: 'plyr__preview-scrubbing--is-shown',\n },\n },\n\n // Embed attributes\n attributes: {\n embed: {\n provider: 'data-plyr-provider',\n id: 'data-plyr-embed-id',\n hash: 'data-plyr-embed-hash',\n },\n },\n\n // Advertisements plugin\n // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio\n ads: {\n enabled: false,\n publisherId: '',\n tagUrl: '',\n },\n\n // Preview Thumbnails plugin\n previewThumbnails: {\n enabled: false,\n src: '',\n },\n\n // Vimeo plugin\n vimeo: {\n byline: false,\n portrait: false,\n title: false,\n speed: true,\n transparent: false,\n // Custom settings from Plyr\n customControls: true,\n referrerPolicy: null, // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy\n // Whether the owner of the video has a Pro or Business account\n // (which allows us to properly hide controls without CSS hacks, etc)\n premium: false,\n },\n\n // YouTube plugin\n youtube: {\n rel: 0, // No related vids\n showinfo: 0, // Hide info\n iv_load_policy: 3, // Hide annotations\n modestbranding: 1, // Hide logos as much as possible (they still show one in the corner when paused)\n // Custom settings from Plyr\n customControls: true,\n noCookie: false, // Whether to use an alternative version of YouTube without cookies\n },\n};\n\nexport default defaults;\n","// ==========================================================================\n// Plyr states\n// ==========================================================================\n\nexport const pip = {\n active: 'picture-in-picture',\n inactive: 'inline',\n};\n\nexport default { pip };\n","// ==========================================================================\n// Plyr supported types and providers\n// ==========================================================================\n\nexport const providers = {\n html5: 'html5',\n youtube: 'youtube',\n vimeo: 'vimeo',\n};\n\nexport const types = {\n audio: 'audio',\n video: 'video',\n};\n\n/**\n * Get provider by URL\n * @param {String} url\n */\nexport function getProviderByUrl(url) {\n // YouTube\n if (/^(https?:\\/\\/)?(www\\.)?(youtube\\.com|youtube-nocookie\\.com|youtu\\.?be)\\/.+$/.test(url)) {\n return providers.youtube;\n }\n\n // Vimeo\n if (/^https?:\\/\\/player.vimeo.com\\/video\\/\\d{0,9}(?=\\b|\\/)/.test(url)) {\n return providers.vimeo;\n }\n\n return null;\n}\n\nexport default { providers, types };\n","// ==========================================================================\n// Console wrapper\n// ==========================================================================\n\nconst noop = () => {};\n\nexport default class Console {\n constructor(enabled = false) {\n this.enabled = window.console && enabled;\n\n if (this.enabled) {\n this.log('Debugging enabled');\n }\n }\n\n get log() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.log, console) : noop;\n }\n\n get warn() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop;\n }\n\n get error() {\n // eslint-disable-next-line no-console\n return this.enabled ? Function.prototype.bind.call(console.error, console) : noop;\n }\n}\n","// ==========================================================================\n// Fullscreen wrapper\n// https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API#prefixing\n// https://webkit.org/blog/7929/designing-websites-for-iphone-x/\n// ==========================================================================\n\nimport browser from './utils/browser';\nimport { closest, getElements, hasClass, toggleClass } from './utils/elements';\nimport { on, triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\n\nclass Fullscreen {\n constructor(player) {\n // Keep reference to parent\n this.player = player;\n\n // Get prefix\n this.prefix = Fullscreen.prefix;\n this.property = Fullscreen.property;\n\n // Scroll position\n this.scrollPosition = { x: 0, y: 0 };\n\n // Force the use of 'full window/browser' rather than fullscreen\n this.forceFallback = player.config.fullscreen.fallback === 'force';\n\n // Get the fullscreen element\n // Checks container is an ancestor, defaults to null\n this.player.elements.fullscreen =\n player.config.fullscreen.container && closest(this.player.elements.container, player.config.fullscreen.container);\n\n // Register event listeners\n // Handle event (incase user presses escape etc)\n on.call(\n this.player,\n document,\n this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`,\n () => {\n // TODO: Filter for target??\n this.onChange();\n },\n );\n\n // Fullscreen toggle on double click\n on.call(this.player, this.player.elements.container, 'dblclick', (event) => {\n // Ignore double click in controls\n if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) {\n return;\n }\n\n this.player.listeners.proxy(event, this.toggle, 'fullscreen');\n });\n\n // Tap focus when in fullscreen\n on.call(this, this.player.elements.container, 'keydown', (event) => this.trapFocus(event));\n\n // Update the UI\n this.update();\n\n // this.toggle = this.toggle.bind(this);\n }\n\n // Determine if native supported\n static get native() {\n return !!(\n document.fullscreenEnabled ||\n document.webkitFullscreenEnabled ||\n document.mozFullScreenEnabled ||\n document.msFullscreenEnabled\n );\n }\n\n // If we're actually using native\n get usingNative() {\n return Fullscreen.native && !this.forceFallback;\n }\n\n // Get the prefix for handlers\n static get prefix() {\n // No prefix\n if (is.function(document.exitFullscreen)) {\n return '';\n }\n\n // Check for fullscreen support by vendor prefix\n let value = '';\n const prefixes = ['webkit', 'moz', 'ms'];\n\n prefixes.some((pre) => {\n if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) {\n value = pre;\n return true;\n }\n\n return false;\n });\n\n return value;\n }\n\n static get property() {\n return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen';\n }\n\n // Determine if fullscreen is enabled\n get enabled() {\n return (\n (Fullscreen.native || this.player.config.fullscreen.fallback) &&\n this.player.config.fullscreen.enabled &&\n this.player.supported.ui &&\n this.player.isVideo\n );\n }\n\n // Get active state\n get active() {\n if (!this.enabled) {\n return false;\n }\n\n // Fallback using classname\n if (!Fullscreen.native || this.forceFallback) {\n return hasClass(this.target, this.player.config.classNames.fullscreen.fallback);\n }\n\n const element = !this.prefix\n ? this.target.getRootNode().fullscreenElement\n : this.target.getRootNode()[`${this.prefix}${this.property}Element`];\n\n return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target;\n }\n\n // Get target element\n get target() {\n return browser.isIos && this.player.config.fullscreen.iosNative\n ? this.player.media\n : this.player.elements.fullscreen || this.player.elements.container;\n }\n\n onChange = () => {\n if (!this.enabled) {\n return;\n }\n\n // Update toggle button\n const button = this.player.elements.buttons.fullscreen;\n if (is.element(button)) {\n button.pressed = this.active;\n }\n\n // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up\n const target = this.target === this.player.media ? this.target : this.player.elements.container;\n // Trigger an event\n triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true);\n };\n\n toggleFallback = (toggle = false) => {\n // Store or restore scroll position\n if (toggle) {\n this.scrollPosition = {\n x: window.scrollX || 0,\n y: window.scrollY || 0,\n };\n } else {\n window.scrollTo(this.scrollPosition.x, this.scrollPosition.y);\n }\n\n // Toggle scroll\n document.body.style.overflow = toggle ? 'hidden' : '';\n\n // Toggle class hook\n toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle);\n\n // Force full viewport on iPhone X+\n if (browser.isIos) {\n let viewport = document.head.querySelector('meta[name=\"viewport\"]');\n const property = 'viewport-fit=cover';\n\n // Inject the viewport meta if required\n if (!viewport) {\n viewport = document.createElement('meta');\n viewport.setAttribute('name', 'viewport');\n }\n\n // Check if the property already exists\n const hasProperty = is.string(viewport.content) && viewport.content.includes(property);\n\n if (toggle) {\n this.cleanupViewport = !hasProperty;\n\n if (!hasProperty) {\n viewport.content += `,${property}`;\n }\n } else if (this.cleanupViewport) {\n viewport.content = viewport.content\n .split(',')\n .filter((part) => part.trim() !== property)\n .join(',');\n }\n }\n\n // Toggle button and fire events\n this.onChange();\n };\n\n // Trap focus inside container\n trapFocus = (event) => {\n // Bail if iOS, not active, not the tab key\n if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) {\n return;\n }\n\n // Get the current focused element\n const focused = document.activeElement;\n const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]');\n const [first] = focusable;\n const last = focusable[focusable.length - 1];\n\n if (focused === last && !event.shiftKey) {\n // Move focus to first element that can be tabbed if Shift isn't used\n first.focus();\n event.preventDefault();\n } else if (focused === first && event.shiftKey) {\n // Move focus to last element that can be tabbed if Shift is used\n last.focus();\n event.preventDefault();\n }\n };\n\n // Update UI\n update = () => {\n if (this.enabled) {\n let mode;\n\n if (this.forceFallback) {\n mode = 'Fallback (forced)';\n } else if (Fullscreen.native) {\n mode = 'Native';\n } else {\n mode = 'Fallback';\n }\n\n this.player.debug.log(`${mode} fullscreen enabled`);\n } else {\n this.player.debug.log('Fullscreen not supported and fallback disabled');\n }\n\n // Add styling hook to show button\n toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled);\n };\n\n // Make an element fullscreen\n enter = () => {\n if (!this.enabled) {\n return;\n }\n\n // iOS native fullscreen doesn't need the request step\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n if (this.player.isVimeo) {\n this.player.embed.requestFullscreen();\n } else {\n this.target.webkitEnterFullscreen();\n }\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(true);\n } else if (!this.prefix) {\n this.target.requestFullscreen({ navigationUI: 'hide' });\n } else if (!is.empty(this.prefix)) {\n this.target[`${this.prefix}Request${this.property}`]();\n }\n };\n\n // Bail from fullscreen\n exit = () => {\n if (!this.enabled) {\n return;\n }\n\n // iOS native fullscreen\n if (browser.isIos && this.player.config.fullscreen.iosNative) {\n this.target.webkitExitFullscreen();\n silencePromise(this.player.play());\n } else if (!Fullscreen.native || this.forceFallback) {\n this.toggleFallback(false);\n } else if (!this.prefix) {\n (document.cancelFullScreen || document.exitFullscreen).call(document);\n } else if (!is.empty(this.prefix)) {\n const action = this.prefix === 'moz' ? 'Cancel' : 'Exit';\n document[`${this.prefix}${action}${this.property}`]();\n }\n };\n\n // Toggle state\n toggle = () => {\n if (!this.active) {\n this.enter();\n } else {\n this.exit();\n }\n };\n}\n\nexport default Fullscreen;\n","// ==========================================================================\n// Load image avoiding xhr/fetch CORS issues\n// Server status can't be obtained this way unfortunately, so this uses \"naturalWidth\" to determine if the image has loaded\n// By default it checks if it is at least 1px, but you can add a second argument to change this\n// ==========================================================================\n\nexport default function loadImage(src, minWidth = 1) {\n return new Promise((resolve, reject) => {\n const image = new Image();\n\n const handler = () => {\n delete image.onload;\n delete image.onerror;\n (image.naturalWidth >= minWidth ? resolve : reject)(image);\n };\n\n Object.assign(image, { onload: handler, onerror: handler, src });\n });\n}\n","// ==========================================================================\n// Plyr UI\n// ==========================================================================\n\nimport captions from './captions';\nimport controls from './controls';\nimport support from './support';\nimport browser from './utils/browser';\nimport { getElement, toggleClass } from './utils/elements';\nimport { ready, triggerEvent } from './utils/events';\nimport i18n from './utils/i18n';\nimport is from './utils/is';\nimport loadImage from './utils/load-image';\n\nconst ui = {\n addStyleHook() {\n toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);\n toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);\n },\n\n // Toggle native HTML5 media controls\n toggleNativeControls(toggle = false) {\n if (toggle && this.isHTML5) {\n this.media.setAttribute('controls', '');\n } else {\n this.media.removeAttribute('controls');\n }\n },\n\n // Setup the UI\n build() {\n // Re-attach media element listeners\n // TODO: Use event bubbling?\n this.listeners.media();\n\n // Don't setup interface if no support\n if (!this.supported.ui) {\n this.debug.warn(`Basic support only for ${this.provider} ${this.type}`);\n\n // Restore native controls\n ui.toggleNativeControls.call(this, true);\n\n // Bail\n return;\n }\n\n // Inject custom controls if not present\n if (!is.element(this.elements.controls)) {\n // Inject custom controls\n controls.inject.call(this);\n\n // Re-attach control listeners\n this.listeners.controls();\n }\n\n // Remove native controls\n ui.toggleNativeControls.call(this);\n\n // Setup captions for HTML5\n if (this.isHTML5) {\n captions.setup.call(this);\n }\n\n // Reset volume\n this.volume = null;\n\n // Reset mute state\n this.muted = null;\n\n // Reset loop state\n this.loop = null;\n\n // Reset quality setting\n this.quality = null;\n\n // Reset speed\n this.speed = null;\n\n // Reset volume display\n controls.updateVolume.call(this);\n\n // Reset time display\n controls.timeUpdate.call(this);\n\n // Reset duration display\n controls.durationUpdate.call(this);\n\n // Update the UI\n ui.checkPlaying.call(this);\n\n // Check for picture-in-picture support\n toggleClass(\n this.elements.container,\n this.config.classNames.pip.supported,\n support.pip && this.isHTML5 && this.isVideo,\n );\n\n // Check for airplay support\n toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5);\n\n // Add iOS class\n toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos);\n\n // Add touch class\n toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch);\n\n // Ready for API calls\n this.ready = true;\n\n // Ready event at end of execution stack\n setTimeout(() => {\n triggerEvent.call(this, this.media, 'ready');\n }, 0);\n\n // Set the title\n ui.setTitle.call(this);\n\n // Assure the poster image is set, if the property was added before the element was created\n if (this.poster) {\n ui.setPoster.call(this, this.poster, false).catch(() => {});\n }\n\n // Manually set the duration if user has overridden it.\n // The event listeners for it doesn't get called if preload is disabled (#701)\n if (this.config.duration) {\n controls.durationUpdate.call(this);\n }\n },\n\n // Setup aria attribute for play and iframe title\n setTitle() {\n // Find the current text\n let label = i18n.get('play', this.config);\n\n // If there's a media title set, use that for the label\n if (is.string(this.config.title) && !is.empty(this.config.title)) {\n label += `, ${this.config.title}`;\n }\n\n // If there's a play button, set label\n Array.from(this.elements.buttons.play || []).forEach((button) => {\n button.setAttribute('aria-label', label);\n });\n\n // Set iframe title\n // https://github.com/sampotts/plyr/issues/124\n if (this.isEmbed) {\n const iframe = getElement.call(this, 'iframe');\n\n if (!is.element(iframe)) {\n return;\n }\n\n // Default to media type\n const title = !is.empty(this.config.title) ? this.config.title : 'video';\n const format = i18n.get('frameTitle', this.config);\n\n iframe.setAttribute('title', format.replace('{title}', title));\n }\n },\n\n // Toggle poster\n togglePoster(enable) {\n toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);\n },\n\n // Set the poster image (async)\n // Used internally for the poster setter, with the passive option forced to false\n setPoster(poster, passive = true) {\n // Don't override if call is passive\n if (passive && this.poster) {\n return Promise.reject(new Error('Poster already set'));\n }\n\n // Set property synchronously to respect the call order\n this.media.setAttribute('data-poster', poster);\n\n // Show the poster\n this.elements.poster.removeAttribute('hidden');\n\n // Wait until ui is ready\n return (\n ready\n .call(this)\n // Load image\n .then(() => loadImage(poster))\n .catch((error) => {\n // Hide poster on error unless it's been set by another call\n if (poster === this.poster) {\n ui.togglePoster.call(this, false);\n }\n // Rethrow\n throw error;\n })\n .then(() => {\n // Prevent race conditions\n if (poster !== this.poster) {\n throw new Error('setPoster cancelled by later call to setPoster');\n }\n })\n .then(() => {\n Object.assign(this.elements.poster.style, {\n backgroundImage: `url('${poster}')`,\n // Reset backgroundSize as well (since it can be set to \"cover\" for padded thumbnails for youtube)\n backgroundSize: '',\n });\n\n ui.togglePoster.call(this, true);\n\n return poster;\n })\n );\n },\n\n // Check playing state\n checkPlaying(event) {\n // Class hooks\n toggleClass(this.elements.container, this.config.classNames.playing, this.playing);\n toggleClass(this.elements.container, this.config.classNames.paused, this.paused);\n toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped);\n\n // Set state\n Array.from(this.elements.buttons.play || []).forEach((target) => {\n Object.assign(target, { pressed: this.playing });\n target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config));\n });\n\n // Only update controls on non timeupdate events\n if (is.event(event) && event.type === 'timeupdate') {\n return;\n }\n\n // Toggle controls\n ui.toggleControls.call(this);\n },\n\n // Check if media is loading\n checkLoading(event) {\n this.loading = ['stalled', 'waiting'].includes(event.type);\n\n // Clear timer\n clearTimeout(this.timers.loading);\n\n // Timer to prevent flicker when seeking\n this.timers.loading = setTimeout(\n () => {\n // Update progress bar loading class state\n toggleClass(this.elements.container, this.config.classNames.loading, this.loading);\n\n // Update controls visibility\n ui.toggleControls.call(this);\n },\n this.loading ? 250 : 0,\n );\n },\n\n // Toggle controls based on state and `force` argument\n toggleControls(force) {\n const { controls: controlsElement } = this.elements;\n\n if (controlsElement && this.config.hideControls) {\n // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.)\n const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now();\n\n // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide\n this.toggleControls(\n Boolean(\n force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek,\n ),\n );\n }\n },\n\n // Migrate any custom properties from the media to the parent\n migrateStyles() {\n // Loop through values (as they are the keys when the object is spread 🤔)\n Object.values({ ...this.media.style })\n // We're only fussed about Plyr specific properties\n .filter((key) => !is.empty(key) && is.string(key) && key.startsWith('--plyr'))\n .forEach((key) => {\n // Set on the container\n this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key));\n\n // Clean up from media element\n this.media.style.removeProperty(key);\n });\n\n // Remove attribute if empty\n if (is.empty(this.media.style)) {\n this.media.removeAttribute('style');\n }\n },\n};\n\nexport default ui;\n","// ==========================================================================\n// Plyr Event Listeners\n// ==========================================================================\n\nimport controls from './controls';\nimport ui from './ui';\nimport { repaint } from './utils/animation';\nimport browser from './utils/browser';\nimport { getElement, getElements, matches, toggleClass } from './utils/elements';\nimport { off, on, once, toggleListener, triggerEvent } from './utils/events';\nimport is from './utils/is';\nimport { silencePromise } from './utils/promise';\nimport { getAspectRatio, getViewportSize, supportsCSS } from './utils/style';\n\nclass Listeners {\n constructor(player) {\n this.player = player;\n this.lastKey = null;\n this.focusTimer = null;\n this.lastKeyDown = null;\n\n this.handleKey = this.handleKey.bind(this);\n this.toggleMenu = this.toggleMenu.bind(this);\n this.setTabFocus = this.setTabFocus.bind(this);\n this.firstTouch = this.firstTouch.bind(this);\n }\n\n // Handle key presses\n handleKey(event) {\n const { player } = this;\n const { elements } = player;\n const code = event.keyCode ? event.keyCode : event.which;\n const pressed = event.type === 'keydown';\n const repeat = pressed && code === this.lastKey;\n\n // Bail if a modifier key is set\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {\n return;\n }\n\n // If the event is bubbled from the media element\n // Firefox doesn't get the keycode for whatever reason\n if (!is.number(code)) {\n return;\n }\n\n // Seek by the number keys\n const seekByKey = () => {\n // Divide the max duration into 10th's and times by the number value\n player.currentTime = (player.duration / 10) * (code - 48);\n };\n\n // Handle the key on keydown\n // Reset on keyup\n if (pressed) {\n // Check focused element\n // and if the focused element is not editable (e.g. text input)\n // and any that accept key input http://webaim.org/techniques/keyboard/\n const focused = document.activeElement;\n if (is.element(focused)) {\n const { editable } = player.config.selectors;\n const { seek } = elements.inputs;\n\n if (focused !== seek && matches(focused, editable)) {\n return;\n }\n\n if (event.which === 32 && matches(focused, 'button, [role^=\"menuitem\"]')) {\n return;\n }\n }\n\n // Which keycodes should we prevent default\n const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79];\n\n // If the code is found prevent default (e.g. prevent scrolling for arrows)\n if (preventDefault.includes(code)) {\n event.preventDefault();\n event.stopPropagation();\n }\n\n switch (code) {\n case 48:\n case 49:\n case 50:\n case 51:\n case 52:\n case 53:\n case 54:\n case 55:\n case 56:\n case 57:\n // 0-9\n if (!repeat) {\n seekByKey();\n }\n break;\n\n case 32:\n case 75:\n // Space and K key\n if (!repeat) {\n silencePromise(player.togglePlay());\n }\n break;\n\n case 38:\n // Arrow up\n player.increaseVolume(0.1);\n break;\n\n case 40:\n // Arrow down\n player.decreaseVolume(0.1);\n break;\n\n case 77:\n // M key\n if (!repeat) {\n player.muted = !player.muted;\n }\n break;\n\n case 39:\n // Arrow forward\n player.forward();\n break;\n\n case 37:\n // Arrow back\n player.rewind();\n break;\n\n case 70:\n // F key\n player.fullscreen.toggle();\n break;\n\n case 67:\n // C key\n if (!repeat) {\n player.toggleCaptions();\n }\n break;\n\n case 76:\n // L key\n player.loop = !player.loop;\n break;\n\n /* case 73:\n this.setLoop('start');\n break;\n\n case 76:\n this.setLoop();\n break;\n\n case 79:\n this.setLoop('end');\n break; */\n\n default:\n break;\n }\n\n // Escape is handle natively when in full screen\n // So we only need to worry about non native\n if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) {\n player.fullscreen.toggle();\n }\n\n // Store last code for next cycle\n this.lastKey = code;\n } else {\n this.lastKey = null;\n }\n }\n\n // Toggle menu\n toggleMenu(event) {\n controls.toggleMenu.call(this.player, event);\n }\n\n // Device is touch enabled\n firstTouch = () => {\n const { player } = this;\n const { elements } = player;\n\n player.touch = true;\n\n // Add touch class\n toggleClass(elements.container, player.config.classNames.isTouch, true);\n };\n\n setTabFocus = (event) => {\n const { player } = this;\n const { elements } = player;\n\n clearTimeout(this.focusTimer);\n\n // Ignore any key other than tab\n if (event.type === 'keydown' && event.which !== 9) {\n return;\n }\n\n // Store reference to event timeStamp\n if (event.type === 'keydown') {\n this.lastKeyDown = event.timeStamp;\n }\n\n // Remove current classes\n const removeCurrent = () => {\n const className = player.config.classNames.tabFocus;\n const current = getElements.call(player, `.${className}`);\n toggleClass(current, className, false);\n };\n\n // Determine if a key was pressed to trigger this event\n const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20;\n\n // Ignore focus events if a key was pressed prior\n if (event.type === 'focus' && !wasKeyDown) {\n return;\n }\n\n // Remove all current\n removeCurrent();\n\n // Delay the adding of classname until the focus has changed\n // This event fires before the focusin event\n if (event.type !== 'focusout') {\n this.focusTimer = setTimeout(() => {\n const focused = document.activeElement;\n\n // Ignore if current focus element isn't inside the player\n if (!elements.container.contains(focused)) {\n return;\n }\n\n toggleClass(document.activeElement, player.config.classNames.tabFocus, true);\n }, 10);\n }\n };\n\n // Global window & document listeners\n global = (toggle = true) => {\n const { player } = this;\n\n // Keyboard shortcuts\n if (player.config.keyboard.global) {\n toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false);\n }\n\n // Click anywhere closes menu\n toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle);\n\n // Detect touch by events\n once.call(player, document.body, 'touchstart', this.firstTouch);\n\n // Tab focus detection\n toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true);\n };\n\n // Container listeners\n container = () => {\n const { player } = this;\n const { config, elements, timers } = player;\n\n // Keyboard shortcuts\n if (!config.keyboard.global && config.keyboard.focused) {\n on.call(player, elements.container, 'keydown keyup', this.handleKey, false);\n }\n\n // Toggle controls on mouse events and entering fullscreen\n on.call(\n player,\n elements.container,\n 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen',\n (event) => {\n const { controls: controlsElement } = elements;\n\n // Remove button states for fullscreen\n if (controlsElement && event.type === 'enterfullscreen') {\n controlsElement.pressed = false;\n controlsElement.hover = false;\n }\n\n // Show, then hide after a timeout unless another control event occurs\n const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type);\n let delay = 0;\n\n if (show) {\n ui.toggleControls.call(player, true);\n // Use longer timeout for touch devices\n delay = player.touch ? 3000 : 2000;\n }\n\n // Clear timer\n clearTimeout(timers.controls);\n\n // Set new timer to prevent flicker when seeking\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n },\n );\n\n // Set a gutter for Vimeo\n const setGutter = () => {\n if (!player.isVimeo || player.config.vimeo.premium) {\n return;\n }\n\n const target = elements.wrapper;\n const { active } = player.fullscreen;\n const [videoWidth, videoHeight] = getAspectRatio.call(player);\n const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`);\n\n // If not active, remove styles\n if (!active) {\n if (useNativeAspectRatio) {\n target.style.width = null;\n target.style.height = null;\n } else {\n target.style.maxWidth = null;\n target.style.margin = null;\n }\n return;\n }\n\n // Determine which dimension will overflow and constrain view\n const [viewportWidth, viewportHeight] = getViewportSize();\n const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight;\n\n if (useNativeAspectRatio) {\n target.style.width = overflow ? 'auto' : '100%';\n target.style.height = overflow ? '100%' : 'auto';\n } else {\n target.style.maxWidth = overflow ? `${(viewportHeight / videoHeight) * videoWidth}px` : null;\n target.style.margin = overflow ? '0 auto' : null;\n }\n };\n\n // Handle resizing\n const resized = () => {\n clearTimeout(timers.resized);\n timers.resized = setTimeout(setGutter, 50);\n };\n\n on.call(player, elements.container, 'enterfullscreen exitfullscreen', (event) => {\n const { target } = player.fullscreen;\n\n // Ignore events not from target\n if (target !== elements.container) {\n return;\n }\n\n // If it's not an embed and no ratio specified\n if (!player.isEmbed && is.empty(player.config.ratio)) {\n return;\n }\n\n // Set Vimeo gutter\n setGutter();\n\n // Watch for resizes\n const method = event.type === 'enterfullscreen' ? on : off;\n method.call(player, window, 'resize', resized);\n });\n };\n\n // Listen for media events\n media = () => {\n const { player } = this;\n const { elements } = player;\n\n // Time change on media\n on.call(player, player.media, 'timeupdate seeking seeked', (event) => controls.timeUpdate.call(player, event));\n\n // Display duration\n on.call(player, player.media, 'durationchange loadeddata loadedmetadata', (event) =>\n controls.durationUpdate.call(player, event),\n );\n\n // Handle the media finishing\n on.call(player, player.media, 'ended', () => {\n // Show poster on end\n if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) {\n // Restart\n player.restart();\n\n // Call pause otherwise IE11 will start playing the video again\n player.pause();\n }\n });\n\n // Check for buffer progress\n on.call(player, player.media, 'progress playing seeking seeked', (event) =>\n controls.updateProgress.call(player, event),\n );\n\n // Handle volume changes\n on.call(player, player.media, 'volumechange', (event) => controls.updateVolume.call(player, event));\n\n // Handle play/pause\n on.call(player, player.media, 'playing play pause ended emptied timeupdate', (event) =>\n ui.checkPlaying.call(player, event),\n );\n\n // Loading state\n on.call(player, player.media, 'waiting canplay seeked playing', (event) => ui.checkLoading.call(player, event));\n\n // Click video\n if (player.supported.ui && player.config.clickToPlay && !player.isAudio) {\n // Re-fetch the wrapper\n const wrapper = getElement.call(player, `.${player.config.classNames.video}`);\n\n // Bail if there's no wrapper (this should never happen)\n if (!is.element(wrapper)) {\n return;\n }\n\n // On click play, pause or restart\n on.call(player, elements.container, 'click', (event) => {\n const targets = [elements.container, wrapper];\n\n // Ignore if click if not container or in video wrapper\n if (!targets.includes(event.target) && !wrapper.contains(event.target)) {\n return;\n }\n\n // Touch devices will just show controls (if hidden)\n if (player.touch && player.config.hideControls) {\n return;\n }\n\n if (player.ended) {\n this.proxy(event, player.restart, 'restart');\n this.proxy(\n event,\n () => {\n silencePromise(player.play());\n },\n 'play',\n );\n } else {\n this.proxy(\n event,\n () => {\n silencePromise(player.togglePlay());\n },\n 'play',\n );\n }\n });\n }\n\n // Disable right click\n if (player.supported.ui && player.config.disableContextMenu) {\n on.call(\n player,\n elements.wrapper,\n 'contextmenu',\n (event) => {\n event.preventDefault();\n },\n false,\n );\n }\n\n // Volume change\n on.call(player, player.media, 'volumechange', () => {\n // Save to storage\n player.storage.set({\n volume: player.volume,\n muted: player.muted,\n });\n });\n\n // Speed change\n on.call(player, player.media, 'ratechange', () => {\n // Update UI\n controls.updateSetting.call(player, 'speed');\n\n // Save to storage\n player.storage.set({ speed: player.speed });\n });\n\n // Quality change\n on.call(player, player.media, 'qualitychange', (event) => {\n // Update UI\n controls.updateSetting.call(player, 'quality', null, event.detail.quality);\n });\n\n // Update download link when ready and if quality changes\n on.call(player, player.media, 'ready qualitychange', () => {\n controls.setDownloadUrl.call(player);\n });\n\n // Proxy events to container\n // Bubble up key events for Edge\n const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' ');\n\n on.call(player, player.media, proxyEvents, (event) => {\n let { detail = {} } = event;\n\n // Get error details from media\n if (event.type === 'error') {\n detail = player.media.error;\n }\n\n triggerEvent.call(player, elements.container, event.type, true, detail);\n });\n };\n\n // Run default and custom handlers\n proxy = (event, defaultHandler, customHandlerKey) => {\n const { player } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n let returned = true;\n\n // Execute custom handler\n if (hasCustomHandler) {\n returned = customHandler.call(player, event);\n }\n\n // Only call default handler if not prevented in custom handler\n if (returned !== false && is.function(defaultHandler)) {\n defaultHandler.call(player, event);\n }\n };\n\n // Trigger custom and default handlers\n bind = (element, type, defaultHandler, customHandlerKey, passive = true) => {\n const { player } = this;\n const customHandler = player.config.listeners[customHandlerKey];\n const hasCustomHandler = is.function(customHandler);\n\n on.call(\n player,\n element,\n type,\n (event) => this.proxy(event, defaultHandler, customHandlerKey),\n passive && !hasCustomHandler,\n );\n };\n\n // Listen for control events\n controls = () => {\n const { player } = this;\n const { elements } = player;\n // IE doesn't support input event, so we fallback to change\n const inputEvent = browser.isIE ? 'change' : 'input';\n\n // Play/pause toggle\n if (elements.buttons.play) {\n Array.from(elements.buttons.play).forEach((button) => {\n this.bind(\n button,\n 'click',\n () => {\n silencePromise(player.togglePlay());\n },\n 'play',\n );\n });\n }\n\n // Pause\n this.bind(elements.buttons.restart, 'click', player.restart, 'restart');\n\n // Rewind\n this.bind(\n elements.buttons.rewind,\n 'click',\n () => {\n // Record seek time so we can prevent hiding controls for a few seconds after rewind\n player.lastSeekTime = Date.now();\n player.rewind();\n },\n 'rewind',\n );\n\n // Rewind\n this.bind(\n elements.buttons.fastForward,\n 'click',\n () => {\n // Record seek time so we can prevent hiding controls for a few seconds after fast forward\n player.lastSeekTime = Date.now();\n player.forward();\n },\n 'fastForward',\n );\n\n // Mute toggle\n this.bind(\n elements.buttons.mute,\n 'click',\n () => {\n player.muted = !player.muted;\n },\n 'mute',\n );\n\n // Captions toggle\n this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions());\n\n // Download\n this.bind(\n elements.buttons.download,\n 'click',\n () => {\n triggerEvent.call(player, player.media, 'download');\n },\n 'download',\n );\n\n // Fullscreen toggle\n this.bind(\n elements.buttons.fullscreen,\n 'click',\n () => {\n player.fullscreen.toggle();\n },\n 'fullscreen',\n );\n\n // Picture-in-Picture\n this.bind(\n elements.buttons.pip,\n 'click',\n () => {\n player.pip = 'toggle';\n },\n 'pip',\n );\n\n // Airplay\n this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay');\n\n // Settings menu - click toggle\n this.bind(\n elements.buttons.settings,\n 'click',\n (event) => {\n // Prevent the document click listener closing the menu\n event.stopPropagation();\n event.preventDefault();\n\n controls.toggleMenu.call(player, event);\n },\n null,\n false,\n ); // Can't be passive as we're preventing default\n\n // Settings menu - keyboard toggle\n // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143\n this.bind(\n elements.buttons.settings,\n 'keyup',\n (event) => {\n const code = event.which;\n\n // We only care about space and return\n if (![13, 32].includes(code)) {\n return;\n }\n\n // Because return triggers a click anyway, all we need to do is set focus\n if (code === 13) {\n controls.focusFirstMenuItem.call(player, null, true);\n return;\n }\n\n // Prevent scroll\n event.preventDefault();\n\n // Prevent playing video (Firefox)\n event.stopPropagation();\n\n // Toggle menu\n controls.toggleMenu.call(player, event);\n },\n null,\n false, // Can't be passive as we're preventing default\n );\n\n // Escape closes menu\n this.bind(elements.settings.menu, 'keydown', (event) => {\n if (event.which === 27) {\n controls.toggleMenu.call(player, event);\n }\n });\n\n // Set range input alternative \"value\", which matches the tooltip time (#954)\n this.bind(elements.inputs.seek, 'mousedown mousemove', (event) => {\n const rect = elements.progress.getBoundingClientRect();\n const percent = (100 / rect.width) * (event.pageX - rect.left);\n event.currentTarget.setAttribute('seek-value', percent);\n });\n\n // Pause while seeking\n this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', (event) => {\n const seek = event.currentTarget;\n const code = event.keyCode ? event.keyCode : event.which;\n const attribute = 'play-on-seeked';\n\n if (is.keyboardEvent(event) && code !== 39 && code !== 37) {\n return;\n }\n\n // Record seek time so we can prevent hiding controls for a few seconds after seek\n player.lastSeekTime = Date.now();\n\n // Was playing before?\n const play = seek.hasAttribute(attribute);\n // Done seeking\n const done = ['mouseup', 'touchend', 'keyup'].includes(event.type);\n\n // If we're done seeking and it was playing, resume playback\n if (play && done) {\n seek.removeAttribute(attribute);\n silencePromise(player.play());\n } else if (!done && player.playing) {\n seek.setAttribute(attribute, '');\n player.pause();\n }\n });\n\n // Fix range inputs on iOS\n // Super weird iOS bug where after you interact with an <input type=\"range\">,\n // it takes over further interactions on the page. This is a hack\n if (browser.isIos) {\n const inputs = getElements.call(player, 'input[type=\"range\"]');\n Array.from(inputs).forEach((input) => this.bind(input, inputEvent, (event) => repaint(event.target)));\n }\n\n // Seek\n this.bind(\n elements.inputs.seek,\n inputEvent,\n (event) => {\n const seek = event.currentTarget;\n // If it exists, use seek-value instead of \"value\" for consistency with tooltip time (#954)\n let seekTo = seek.getAttribute('seek-value');\n\n if (is.empty(seekTo)) {\n seekTo = seek.value;\n }\n\n seek.removeAttribute('seek-value');\n\n player.currentTime = (seekTo / seek.max) * player.duration;\n },\n 'seek',\n );\n\n // Seek tooltip\n this.bind(elements.progress, 'mouseenter mouseleave mousemove', (event) =>\n controls.updateSeekTooltip.call(player, event),\n );\n\n // Preview thumbnails plugin\n // TODO: Really need to work on some sort of plug-in wide event bus or pub-sub for this\n this.bind(elements.progress, 'mousemove touchmove', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startMove(event);\n }\n });\n\n // Hide thumbnail preview - on mouse click, mouse leave, and video play/seek. All four are required, e.g., for buffering\n this.bind(elements.progress, 'mouseleave touchend click', () => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endMove(false, true);\n }\n });\n\n // Show scrubbing preview\n this.bind(elements.progress, 'mousedown touchstart', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.startScrubbing(event);\n }\n });\n\n this.bind(elements.progress, 'mouseup touchend', (event) => {\n const { previewThumbnails } = player;\n\n if (previewThumbnails && previewThumbnails.loaded) {\n previewThumbnails.endScrubbing(event);\n }\n });\n\n // Polyfill for lower fill in <input type=\"range\"> for webkit\n if (browser.isWebkit) {\n Array.from(getElements.call(player, 'input[type=\"range\"]')).forEach((element) => {\n this.bind(element, 'input', (event) => controls.updateRangeFill.call(player, event.target));\n });\n }\n\n // Current time invert\n // Only if one time element is used for both currentTime and duration\n if (player.config.toggleInvert && !is.element(elements.display.duration)) {\n this.bind(elements.display.currentTime, 'click', () => {\n // Do nothing if we're at the start\n if (player.currentTime === 0) {\n return;\n }\n\n player.config.invertTime = !player.config.invertTime;\n\n controls.timeUpdate.call(player);\n });\n }\n\n // Volume\n this.bind(\n elements.inputs.volume,\n inputEvent,\n (event) => {\n player.volume = event.target.value;\n },\n 'volume',\n );\n\n // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting)\n this.bind(elements.controls, 'mouseenter mouseleave', (event) => {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n });\n\n // Also update controls.hover state for any non-player children of fullscreen element (as above)\n if (elements.fullscreen) {\n Array.from(elements.fullscreen.children)\n .filter((c) => !c.contains(elements.container))\n .forEach((child) => {\n this.bind(child, 'mouseenter mouseleave', (event) => {\n if (elements.controls) {\n elements.controls.hover = !player.touch && event.type === 'mouseenter';\n }\n });\n });\n }\n\n // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting)\n this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', (event) => {\n elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type);\n });\n\n // Show controls when they receive focus (e.g., when using keyboard tab key)\n this.bind(elements.controls, 'focusin', () => {\n const { config, timers } = player;\n\n // Skip transition to prevent focus from scrolling the parent element\n toggleClass(elements.controls, config.classNames.noTransition, true);\n\n // Toggle\n ui.toggleControls.call(player, true);\n\n // Restore transition\n setTimeout(() => {\n toggleClass(elements.controls, config.classNames.noTransition, false);\n }, 0);\n\n // Delay a little more for mouse users\n const delay = this.touch ? 3000 : 4000;\n\n // Clear timer\n clearTimeout(timers.controls);\n\n // Hide again after delay\n timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);\n });\n\n // Mouse wheel for volume\n this.bind(\n elements.inputs.volume,\n 'wheel',\n (event) => {\n // Detect \"natural\" scroll - suppored on OS X Safari only\n // Other browsers on OS X will be inverted until support improves\n const inverted = event.webkitDirectionInvertedFromDevice;\n // Get delta from event. Invert if `inverted` is true\n const [x, y] = [event.deltaX, -event.deltaY].map((value) => (inverted ? -value : value));\n // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta)\n const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y);\n\n // Change the volume by 2%\n player.increaseVolume(direction / 50);\n\n // Don't break page scrolling at max and min\n const { volume } = player.media;\n if ((direction === 1 && volume < 1) || (direction === -1 && volume > 0)) {\n event.preventDefault();\n }\n },\n 'volume',\n false,\n );\n };\n}\n\nexport default Listeners;\n","(function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n define([], factory);\n } else if (typeof exports === 'object') {\n module.exports = factory();\n } else {\n root.loadjs = factory();\n }\n}(this, function() {\n/**\n * Global dependencies.\n * @global {Object} document - DOM\n */\n\nvar devnull = function() {},\n bundleIdCache = {},\n bundleResultCache = {},\n bundleCallbackQueue = {};\n\n\n/**\n * Subscribe to bundle load event.\n * @param {string[]} bundleIds - Bundle ids\n * @param {Function} callbackFn - The callback function\n */\nfunction subscribe(bundleIds, callbackFn) {\n // listify\n bundleIds = bundleIds.push ? bundleIds : [bundleIds];\n\n var depsNotFound = [],\n i = bundleIds.length,\n numWaiting = i,\n fn,\n bundleId,\n r,\n q;\n\n // define callback function\n fn = function (bundleId, pathsNotFound) {\n if (pathsNotFound.length) depsNotFound.push(bundleId);\n\n numWaiting--;\n if (!numWaiting) callbackFn(depsNotFound);\n };\n\n // register callback\n while (i--) {\n bundleId = bundleIds[i];\n\n // execute callback if in result cache\n r = bundleResultCache[bundleId];\n if (r) {\n fn(bundleId, r);\n continue;\n }\n\n // add to callback queue\n q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];\n q.push(fn);\n }\n}\n\n\n/**\n * Publish bundle load event.\n * @param {string} bundleId - Bundle id\n * @param {string[]} pathsNotFound - List of files not found\n */\nfunction publish(bundleId, pathsNotFound) {\n // exit if id isn't defined\n if (!bundleId) return;\n\n var q = bundleCallbackQueue[bundleId];\n\n // cache result\n bundleResultCache[bundleId] = pathsNotFound;\n\n // exit if queue is empty\n if (!q) return;\n\n // empty callback queue\n while (q.length) {\n q[0](bundleId, pathsNotFound);\n q.splice(0, 1);\n }\n}\n\n\n/**\n * Execute callbacks.\n * @param {Object or Function} args - The callback args\n * @param {string[]} depsNotFound - List of dependencies not found\n */\nfunction executeCallbacks(args, depsNotFound) {\n // accept function as argument\n if (args.call) args = {success: args};\n\n // success and error callbacks\n if (depsNotFound.length) (args.error || devnull)(depsNotFound);\n else (args.success || devnull)(args);\n}\n\n\n/**\n * Load individual file.\n * @param {string} path - The file path\n * @param {Function} callbackFn - The callback function\n */\nfunction loadFile(path, callbackFn, args, numTries) {\n var doc = document,\n async = args.async,\n maxTries = (args.numRetries || 0) + 1,\n beforeCallbackFn = args.before || devnull,\n pathname = path.replace(/[\\?|#].*$/, ''),\n pathStripped = path.replace(/^(css|img)!/, ''),\n isLegacyIECss,\n e;\n\n numTries = numTries || 0;\n\n if (/(^css!|\\.css$)/.test(pathname)) {\n // css\n e = doc.createElement('link');\n e.rel = 'stylesheet';\n e.href = pathStripped;\n\n // tag IE9+\n isLegacyIECss = 'hideFocus' in e;\n\n // use preload in IE Edge (to detect load errors)\n if (isLegacyIECss && e.relList) {\n isLegacyIECss = 0;\n e.rel = 'preload';\n e.as = 'style';\n }\n } else if (/(^img!|\\.(png|gif|jpg|svg|webp)$)/.test(pathname)) {\n // image\n e = doc.createElement('img');\n e.src = pathStripped; \n } else {\n // javascript\n e = doc.createElement('script');\n e.src = path;\n e.async = async === undefined ? true : async;\n }\n\n e.onload = e.onerror = e.onbeforeload = function (ev) {\n var result = ev.type[0];\n\n // treat empty stylesheets as failures to get around lack of onerror\n // support in IE9-11\n if (isLegacyIECss) {\n try {\n if (!e.sheet.cssText.length) result = 'e';\n } catch (x) {\n // sheets objects created from load errors don't allow access to\n // `cssText` (unless error is Code:18 SecurityError)\n if (x.code != 18) result = 'e';\n }\n }\n\n // handle retries in case of load failure\n if (result == 'e') {\n // increment counter\n numTries += 1;\n\n // exit function and try again\n if (numTries < maxTries) {\n return loadFile(path, callbackFn, args, numTries);\n }\n } else if (e.rel == 'preload' && e.as == 'style') {\n // activate preloaded stylesheets\n return e.rel = 'stylesheet'; // jshint ignore:line\n }\n \n // execute callback\n callbackFn(path, result, ev.defaultPrevented);\n };\n\n // add to document (unless callback returns `false`)\n if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e);\n}\n\n\n/**\n * Load multiple files.\n * @param {string[]} paths - The file paths\n * @param {Function} callbackFn - The callback function\n */\nfunction loadFiles(paths, callbackFn, args) {\n // listify paths\n paths = paths.push ? paths : [paths];\n\n var numWaiting = paths.length,\n x = numWaiting,\n pathsNotFound = [],\n fn,\n i;\n\n // define callback function\n fn = function(path, result, defaultPrevented) {\n // handle error\n if (result == 'e') pathsNotFound.push(path);\n\n // handle beforeload event. If defaultPrevented then that means the load\n // will be blocked (ex. Ghostery/ABP on Safari)\n if (result == 'b') {\n if (defaultPrevented) pathsNotFound.push(path);\n else return;\n }\n\n numWaiting--;\n if (!numWaiting) callbackFn(pathsNotFound);\n };\n\n // load scripts\n for (i=0; i < x; i++) loadFile(paths[i], fn, args);\n}\n\n\n/**\n * Initiate script load and register bundle.\n * @param {(string|string[])} paths - The file paths\n * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success\n * callback or (3) object literal with success/error arguments, numRetries,\n * etc.\n * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object\n * literal with success/error arguments, numRetries, etc.\n */\nfunction loadjs(paths, arg1, arg2) {\n var bundleId,\n args;\n\n // bundleId (if string)\n if (arg1 && arg1.trim) bundleId = arg1;\n\n // args (default is {})\n args = (bundleId ? arg2 : arg1) || {};\n\n // throw error if bundle is already defined\n if (bundleId) {\n if (bundleId in bundleIdCache) {\n throw \"LoadJS\";\n } else {\n bundleIdCache[bundleId] = true;\n }\n }\n\n function loadFn(resolve, reject) {\n loadFiles(paths, function (pathsNotFound) {\n // execute callbacks\n executeCallbacks(args, pathsNotFound);\n \n // resolve Promise\n if (resolve) {\n executeCallbacks({success: resolve, error: reject}, pathsNotFound);\n }\n\n // publish bundle load event\n publish(bundleId, pathsNotFound);\n }, args);\n }\n \n if (args.returnPromise) return new Promise(loadFn);\n else loadFn();\n}\n\n\n/**\n * Execute callbacks when dependencies have been satisfied.\n * @param {(string|string[])} deps - List of bundle ids\n * @param {Object} args - success/error arguments\n */\nloadjs.ready = function ready(deps, args) {\n // subscribe to bundle load event\n subscribe(deps, function (depsNotFound) {\n // execute callbacks\n executeCallbacks(args, depsNotFound);\n });\n\n return loadjs;\n};\n\n\n/**\n * Manually satisfy bundle dependencies.\n * @param {string} bundleId - The bundle id\n */\nloadjs.done = function done(bundleId) {\n publish(bundleId, []);\n};\n\n\n/**\n * Reset loadjs dependencies statuses\n */\nloadjs.reset = function reset() {\n bundleIdCache = {};\n bundleResultCache = {};\n bundleCallbackQueue = {};\n};\n\n\n/**\n * Determine if bundle has already been defined\n * @param String} bundleId - The bundle id\n */\nloadjs.isDefined = function isDefined(bundleId) {\n return bundleId in bundleIdCache;\n};\n\n\n// export\nreturn loadjs;\n\n}));\n","// ==========================================================================\n// Load an external script\n// ==========================================================================\n\nimport loadjs from 'loadjs';\n\nexport default function loadScript(url) {\n return new Promise((resolve, reject) => {\n loadjs(url, {\n success: resolve,\n error: reject,\n });\n });\n}\n","// ==========================================================================\n// Vimeo plugin\n// ==========================================================================\n\nimport captions from '../captions';\nimport controls from '../controls';\nimport ui from '../ui';\nimport { createElement, replaceElement, toggleClass } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport loadScript from '../utils/load-script';\nimport { format, stripHTML } from '../utils/strings';\nimport { roundAspectRatio, setAspectRatio } from '../utils/style';\nimport { buildUrlParams } from '../utils/urls';\n\n// Parse Vimeo ID from URL\nfunction parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n if (is.number(Number(url))) {\n return url;\n }\n\n const regex = /^.*(vimeo.com\\/|video\\/)(\\d+).*/;\n return url.match(regex) ? RegExp.$2 : url;\n}\n\n// Try to extract a hash for private videos from the URL\nfunction parseHash(url) {\n /* This regex matches a hexadecimal hash if given in any of these forms:\n * - [https://player.]vimeo.com/video/{id}/{hash}[?params]\n * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms]\n * - [https://player.]vimeo.com/video/{id}?[params]&h={hash}\n * - video/{id}/{hash}\n * If matched, the hash is available in the named group `hash`\n */\n const regex = /^.*(?:vimeo.com\\/|video\\/)(?:\\d+)(?:\\?.*&*h=|\\/)+(?<hash>[\\d,a-f]+)/;\n const found = url.match(regex);\n\n return found ? found.groups.hash : null;\n}\n\n// Set playback state and trigger change (only on actual change)\nfunction assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nconst vimeo = {\n setup() {\n const player = this;\n\n // Add embed class for responsive\n toggleClass(player.elements.wrapper, player.config.classNames.embed, true);\n\n // Set speed options from config\n player.options.speed = player.config.speed.options;\n\n // Set intial ratio\n setAspectRatio.call(player);\n\n // Load the SDK if not already\n if (!is.object(window.Vimeo)) {\n loadScript(player.config.urls.vimeo.sdk)\n .then(() => {\n vimeo.ready.call(player);\n })\n .catch((error) => {\n player.debug.warn('Vimeo SDK (player.js) failed to load', error);\n });\n } else {\n vimeo.ready.call(player);\n }\n },\n\n // API Ready\n ready() {\n const player = this;\n const config = player.config.vimeo;\n const { premium, referrerPolicy, ...frameParams } = config;\n // Get the source URL or ID\n let source = player.media.getAttribute('src');\n let hash = '';\n // Get from <div> if needed\n if (is.empty(source)) {\n source = player.media.getAttribute(player.config.attributes.embed.id);\n // hash can also be set as attribute on the <div>\n hash = player.media.getAttribute(player.config.attributes.embed.hash);\n } else {\n hash = parseHash(source);\n }\n const hashParam = hash ? { h: hash } : {};\n\n // If the owner has a pro or premium account then we can hide controls etc\n if (premium) {\n Object.assign(frameParams, {\n controls: false,\n sidedock: false,\n });\n }\n\n // Get Vimeo params for the iframe\n const params = buildUrlParams({\n loop: player.config.loop.active,\n autoplay: player.autoplay,\n muted: player.muted,\n gesture: 'media',\n playsinline: !this.config.fullscreen.iosNative,\n // hash has to be added to iframe-URL\n ...hashParam,\n ...frameParams,\n });\n\n const id = parseId(source);\n // Build an iframe\n const iframe = createElement('iframe');\n const src = format(player.config.urls.vimeo.iframe, id, params);\n iframe.setAttribute('src', src);\n iframe.setAttribute('allowfullscreen', '');\n iframe.setAttribute(\n 'allow',\n ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; '),\n );\n\n // Set the referrer policy if required\n if (!is.empty(referrerPolicy)) {\n iframe.setAttribute('referrerPolicy', referrerPolicy);\n }\n\n // Inject the package\n if (premium || !config.customControls) {\n iframe.setAttribute('data-poster', player.poster);\n player.media = replaceElement(iframe, player.media);\n } else {\n const wrapper = createElement('div', {\n class: player.config.classNames.embedContainer,\n 'data-poster': player.poster,\n });\n wrapper.appendChild(iframe);\n player.media = replaceElement(wrapper, player.media);\n }\n\n // Get poster image\n if (!config.customControls) {\n fetch(format(player.config.urls.vimeo.api, src)).then((response) => {\n if (is.empty(response) || !response.thumbnail_url) {\n return;\n }\n\n // Set and show poster\n ui.setPoster.call(player, response.thumbnail_url).catch(() => {});\n });\n }\n\n // Setup instance\n // https://github.com/vimeo/player.js\n player.embed = new window.Vimeo.Player(iframe, {\n autopause: player.config.autopause,\n muted: player.muted,\n });\n\n player.media.paused = true;\n player.media.currentTime = 0;\n\n // Disable native text track rendering\n if (player.supported.ui) {\n player.embed.disableTextTrack();\n }\n\n // Create a faux HTML5 API using the Vimeo API\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n return player.embed.play();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n return player.embed.pause();\n };\n\n player.media.stop = () => {\n player.pause();\n player.currentTime = 0;\n };\n\n // Seeking\n let { currentTime } = player.media;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return currentTime;\n },\n set(time) {\n // Vimeo will automatically play on seek if the video hasn't been played before\n\n // Get current paused state and volume etc\n const { embed, media, paused, volume } = player;\n const restorePause = paused && !embed.hasPlayed;\n\n // Set seeking state and trigger event\n media.seeking = true;\n triggerEvent.call(player, media, 'seeking');\n\n // If paused, mute until seek is complete\n Promise.resolve(restorePause && embed.setVolume(0))\n // Seek\n .then(() => embed.setCurrentTime(time))\n // Restore paused\n .then(() => restorePause && embed.pause())\n // Restore volume\n .then(() => restorePause && embed.setVolume(volume))\n .catch(() => {\n // Do nothing\n });\n },\n });\n\n // Playback speed\n let speed = player.config.speed.selected;\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return speed;\n },\n set(input) {\n player.embed\n .setPlaybackRate(input)\n .then(() => {\n speed = input;\n triggerEvent.call(player, player.media, 'ratechange');\n })\n .catch(() => {\n // Cannot set Playback Rate, Video is probably not on Pro account\n player.options.speed = [1];\n });\n },\n });\n\n // Volume\n let { volume } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n set(input) {\n player.embed.setVolume(input).then(() => {\n volume = input;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n },\n });\n\n // Muted\n let { muted } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : false;\n\n player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => {\n muted = toggle;\n triggerEvent.call(player, player.media, 'volumechange');\n });\n },\n });\n\n // Loop\n let { loop } = player.config;\n Object.defineProperty(player.media, 'loop', {\n get() {\n return loop;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : player.config.loop.active;\n\n player.embed.setLoop(toggle).then(() => {\n loop = toggle;\n });\n },\n });\n\n // Source\n let currentSrc;\n player.embed\n .getVideoUrl()\n .then((value) => {\n currentSrc = value;\n controls.setDownloadUrl.call(player);\n })\n .catch((error) => {\n this.debug.warn(error);\n });\n\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return currentSrc;\n },\n });\n\n // Ended\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n },\n });\n\n // Set aspect ratio based on video size\n Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then((dimensions) => {\n const [width, height] = dimensions;\n player.embed.ratio = roundAspectRatio(width, height);\n setAspectRatio.call(this);\n });\n\n // Set autopause\n player.embed.setAutopause(player.config.autopause).then((state) => {\n player.config.autopause = state;\n });\n\n // Get title\n player.embed.getVideoTitle().then((title) => {\n player.config.title = title;\n ui.setTitle.call(this);\n });\n\n // Get current time\n player.embed.getCurrentTime().then((value) => {\n currentTime = value;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n\n // Get duration\n player.embed.getDuration().then((value) => {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n });\n\n // Get captions\n player.embed.getTextTracks().then((tracks) => {\n player.media.textTracks = tracks;\n captions.setup.call(player);\n });\n\n player.embed.on('cuechange', ({ cues = [] }) => {\n const strippedCues = cues.map((cue) => stripHTML(cue.text));\n captions.updateCues.call(player, strippedCues);\n });\n\n player.embed.on('loaded', () => {\n // Assure state and events are updated on autoplay\n player.embed.getPaused().then((paused) => {\n assurePlaybackState.call(player, !paused);\n if (!paused) {\n triggerEvent.call(player, player.media, 'playing');\n }\n });\n\n if (is.element(player.embed.element) && player.supported.ui) {\n const frame = player.embed.element;\n\n // Fix keyboard focus issues\n // https://github.com/sampotts/plyr/issues/317\n frame.setAttribute('tabindex', -1);\n }\n });\n\n player.embed.on('bufferstart', () => {\n triggerEvent.call(player, player.media, 'waiting');\n });\n\n player.embed.on('bufferend', () => {\n triggerEvent.call(player, player.media, 'playing');\n });\n\n player.embed.on('play', () => {\n assurePlaybackState.call(player, true);\n triggerEvent.call(player, player.media, 'playing');\n });\n\n player.embed.on('pause', () => {\n assurePlaybackState.call(player, false);\n });\n\n player.embed.on('timeupdate', (data) => {\n player.media.seeking = false;\n currentTime = data.seconds;\n triggerEvent.call(player, player.media, 'timeupdate');\n });\n\n player.embed.on('progress', (data) => {\n player.media.buffered = data.percent;\n triggerEvent.call(player, player.media, 'progress');\n\n // Check all loaded\n if (parseInt(data.percent, 10) === 1) {\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n\n // Get duration as if we do it before load, it gives an incorrect value\n // https://github.com/sampotts/plyr/issues/891\n player.embed.getDuration().then((value) => {\n if (value !== player.media.duration) {\n player.media.duration = value;\n triggerEvent.call(player, player.media, 'durationchange');\n }\n });\n });\n\n player.embed.on('seeked', () => {\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n });\n\n player.embed.on('ended', () => {\n player.media.paused = true;\n triggerEvent.call(player, player.media, 'ended');\n });\n\n player.embed.on('error', (detail) => {\n player.media.error = detail;\n triggerEvent.call(player, player.media, 'error');\n });\n\n // Rebuild UI\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 0);\n }\n },\n};\n\nexport default vimeo;\n","// ==========================================================================\n// YouTube plugin\n// ==========================================================================\n\nimport ui from '../ui';\nimport { createElement, replaceElement, toggleClass } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport loadImage from '../utils/load-image';\nimport loadScript from '../utils/load-script';\nimport { extend } from '../utils/objects';\nimport { format, generateId } from '../utils/strings';\nimport { roundAspectRatio, setAspectRatio } from '../utils/style';\n\n// Parse YouTube ID from URL\nfunction parseId(url) {\n if (is.empty(url)) {\n return null;\n }\n\n const regex = /^.*(youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=|&v=)([^#&?]*).*/;\n return url.match(regex) ? RegExp.$2 : url;\n}\n\n// Set playback state and trigger change (only on actual change)\nfunction assurePlaybackState(play) {\n if (play && !this.embed.hasPlayed) {\n this.embed.hasPlayed = true;\n }\n if (this.media.paused === play) {\n this.media.paused = !play;\n triggerEvent.call(this, this.media, play ? 'play' : 'pause');\n }\n}\n\nfunction getHost(config) {\n if (config.noCookie) {\n return 'https://www.youtube-nocookie.com';\n }\n\n if (window.location.protocol === 'http:') {\n return 'http://www.youtube.com';\n }\n\n // Use YouTube's default\n return undefined;\n}\n\nconst youtube = {\n setup() {\n // Add embed class for responsive\n toggleClass(this.elements.wrapper, this.config.classNames.embed, true);\n\n // Setup API\n if (is.object(window.YT) && is.function(window.YT.Player)) {\n youtube.ready.call(this);\n } else {\n // Reference current global callback\n const callback = window.onYouTubeIframeAPIReady;\n\n // Set callback to process queue\n window.onYouTubeIframeAPIReady = () => {\n // Call global callback if set\n if (is.function(callback)) {\n callback();\n }\n\n youtube.ready.call(this);\n };\n\n // Load the SDK\n loadScript(this.config.urls.youtube.sdk).catch((error) => {\n this.debug.warn('YouTube API failed to load', error);\n });\n }\n },\n\n // Get the media title\n getTitle(videoId) {\n const url = format(this.config.urls.youtube.api, videoId);\n\n fetch(url)\n .then((data) => {\n if (is.object(data)) {\n const { title, height, width } = data;\n\n // Set title\n this.config.title = title;\n ui.setTitle.call(this);\n\n // Set aspect ratio\n this.embed.ratio = roundAspectRatio(width, height);\n }\n\n setAspectRatio.call(this);\n })\n .catch(() => {\n // Set aspect ratio\n setAspectRatio.call(this);\n });\n },\n\n // API ready\n ready() {\n const player = this;\n const config = player.config.youtube;\n // Ignore already setup (race condition)\n const currentId = player.media && player.media.getAttribute('id');\n if (!is.empty(currentId) && currentId.startsWith('youtube-')) {\n return;\n }\n\n // Get the source URL or ID\n let source = player.media.getAttribute('src');\n\n // Get from <div> if needed\n if (is.empty(source)) {\n source = player.media.getAttribute(this.config.attributes.embed.id);\n }\n\n // Replace the <iframe> with a <div> due to YouTube API issues\n const videoId = parseId(source);\n const id = generateId(player.provider);\n // Replace media element\n const container = createElement('div', { id, 'data-poster': config.customControls ? player.poster : undefined });\n player.media = replaceElement(container, player.media);\n\n // Only load the poster when using custom controls\n if (config.customControls) {\n const posterSrc = (s) => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`;\n\n // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide)\n loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded\n .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3\n .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists\n .then((image) => ui.setPoster.call(player, image.src))\n .then((src) => {\n // If the image is padded, use background-size \"cover\" instead (like youtube does too with their posters)\n if (!src.includes('maxres')) {\n player.elements.poster.style.backgroundSize = 'cover';\n }\n })\n .catch(() => {});\n }\n\n // Setup instance\n // https://developers.google.com/youtube/iframe_api_reference\n player.embed = new window.YT.Player(player.media, {\n videoId,\n host: getHost(config),\n playerVars: extend(\n {},\n {\n // Autoplay\n autoplay: player.config.autoplay ? 1 : 0,\n // iframe interface language\n hl: player.config.hl,\n // Only show controls if not fully supported or opted out\n controls: player.supported.ui && config.customControls ? 0 : 1,\n // Disable keyboard as we handle it\n disablekb: 1,\n // Allow iOS inline playback\n playsinline: !player.config.fullscreen.iosNative ? 1 : 0,\n // Captions are flaky on YouTube\n cc_load_policy: player.captions.active ? 1 : 0,\n cc_lang_pref: player.config.captions.language,\n // Tracking for stats\n widget_referrer: window ? window.location.href : null,\n },\n config,\n ),\n events: {\n onError(event) {\n // YouTube may fire onError twice, so only handle it once\n if (!player.media.error) {\n const code = event.data;\n // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError\n const message =\n {\n 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.',\n 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.',\n 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.',\n 101: 'The owner of the requested video does not allow it to be played in embedded players.',\n 150: 'The owner of the requested video does not allow it to be played in embedded players.',\n }[code] || 'An unknown error occured';\n\n player.media.error = { code, message };\n\n triggerEvent.call(player, player.media, 'error');\n }\n },\n onPlaybackRateChange(event) {\n // Get the instance\n const instance = event.target;\n\n // Get current speed\n player.media.playbackRate = instance.getPlaybackRate();\n\n triggerEvent.call(player, player.media, 'ratechange');\n },\n onReady(event) {\n // Bail if onReady has already been called. See issue #1108\n if (is.function(player.media.play)) {\n return;\n }\n // Get the instance\n const instance = event.target;\n\n // Get the title\n youtube.getTitle.call(player, videoId);\n\n // Create a faux HTML5 API using the YouTube API\n player.media.play = () => {\n assurePlaybackState.call(player, true);\n instance.playVideo();\n };\n\n player.media.pause = () => {\n assurePlaybackState.call(player, false);\n instance.pauseVideo();\n };\n\n player.media.stop = () => {\n instance.stopVideo();\n };\n\n player.media.duration = instance.getDuration();\n player.media.paused = true;\n\n // Seeking\n player.media.currentTime = 0;\n Object.defineProperty(player.media, 'currentTime', {\n get() {\n return Number(instance.getCurrentTime());\n },\n set(time) {\n // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet).\n if (player.paused && !player.embed.hasPlayed) {\n player.embed.mute();\n }\n\n // Set seeking state and trigger event\n player.media.seeking = true;\n triggerEvent.call(player, player.media, 'seeking');\n\n // Seek after events sent\n instance.seekTo(time);\n },\n });\n\n // Playback speed\n Object.defineProperty(player.media, 'playbackRate', {\n get() {\n return instance.getPlaybackRate();\n },\n set(input) {\n instance.setPlaybackRate(input);\n },\n });\n\n // Volume\n let { volume } = player.config;\n Object.defineProperty(player.media, 'volume', {\n get() {\n return volume;\n },\n set(input) {\n volume = input;\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n },\n });\n\n // Muted\n let { muted } = player.config;\n Object.defineProperty(player.media, 'muted', {\n get() {\n return muted;\n },\n set(input) {\n const toggle = is.boolean(input) ? input : muted;\n muted = toggle;\n instance[toggle ? 'mute' : 'unMute']();\n instance.setVolume(volume * 100);\n triggerEvent.call(player, player.media, 'volumechange');\n },\n });\n\n // Source\n Object.defineProperty(player.media, 'currentSrc', {\n get() {\n return instance.getVideoUrl();\n },\n });\n\n // Ended\n Object.defineProperty(player.media, 'ended', {\n get() {\n return player.currentTime === player.duration;\n },\n });\n\n // Get available speeds\n const speeds = instance.getAvailablePlaybackRates();\n // Filter based on config\n player.options.speed = speeds.filter((s) => player.config.speed.options.includes(s));\n\n // Set the tabindex to avoid focus entering iframe\n if (player.supported.ui && config.customControls) {\n player.media.setAttribute('tabindex', -1);\n }\n\n triggerEvent.call(player, player.media, 'timeupdate');\n triggerEvent.call(player, player.media, 'durationchange');\n\n // Reset timer\n clearInterval(player.timers.buffering);\n\n // Setup buffering\n player.timers.buffering = setInterval(() => {\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction();\n\n // Trigger progress only when we actually buffer something\n if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) {\n triggerEvent.call(player, player.media, 'progress');\n }\n\n // Set last buffer point\n player.media.lastBuffered = player.media.buffered;\n\n // Bail if we're at 100%\n if (player.media.buffered === 1) {\n clearInterval(player.timers.buffering);\n\n // Trigger event\n triggerEvent.call(player, player.media, 'canplaythrough');\n }\n }, 200);\n\n // Rebuild UI\n if (config.customControls) {\n setTimeout(() => ui.build.call(player), 50);\n }\n },\n onStateChange(event) {\n // Get the instance\n const instance = event.target;\n\n // Reset timer\n clearInterval(player.timers.playing);\n\n const seeked = player.media.seeking && [1, 2].includes(event.data);\n\n if (seeked) {\n // Unset seeking and fire seeked event\n player.media.seeking = false;\n triggerEvent.call(player, player.media, 'seeked');\n }\n\n // Handle events\n // -1 Unstarted\n // 0 Ended\n // 1 Playing\n // 2 Paused\n // 3 Buffering\n // 5 Video cued\n switch (event.data) {\n case -1:\n // Update scrubber\n triggerEvent.call(player, player.media, 'timeupdate');\n\n // Get loaded % from YouTube\n player.media.buffered = instance.getVideoLoadedFraction();\n triggerEvent.call(player, player.media, 'progress');\n\n break;\n\n case 0:\n assurePlaybackState.call(player, false);\n\n // YouTube doesn't support loop for a single video, so mimick it.\n if (player.media.loop) {\n // YouTube needs a call to `stopVideo` before playing again\n instance.stopVideo();\n instance.playVideo();\n } else {\n triggerEvent.call(player, player.media, 'ended');\n }\n\n break;\n\n case 1:\n // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet)\n if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) {\n player.media.pause();\n } else {\n assurePlaybackState.call(player, true);\n\n triggerEvent.call(player, player.media, 'playing');\n\n // Poll to get playback progress\n player.timers.playing = setInterval(() => {\n triggerEvent.call(player, player.media, 'timeupdate');\n }, 50);\n\n // Check duration again due to YouTube bug\n // https://github.com/sampotts/plyr/issues/374\n // https://code.google.com/p/gdata-issues/issues/detail?id=8690\n if (player.media.duration !== instance.getDuration()) {\n player.media.duration = instance.getDuration();\n triggerEvent.call(player, player.media, 'durationchange');\n }\n }\n\n break;\n\n case 2:\n // Restore audio (YouTube starts playing on seek if the video hasn't been played yet)\n if (!player.muted) {\n player.embed.unMute();\n }\n assurePlaybackState.call(player, false);\n\n break;\n\n case 3:\n // Trigger waiting event to add loading classes to container as the video buffers.\n triggerEvent.call(player, player.media, 'waiting');\n\n break;\n\n default:\n break;\n }\n\n triggerEvent.call(player, player.elements.container, 'statechange', false, {\n code: event.data,\n });\n },\n },\n });\n },\n};\n\nexport default youtube;\n","// ==========================================================================\n// Plyr Media\n// ==========================================================================\n\nimport html5 from './html5';\nimport vimeo from './plugins/vimeo';\nimport youtube from './plugins/youtube';\nimport { createElement, toggleClass, wrap } from './utils/elements';\n\nconst media = {\n // Setup media\n setup() {\n // If there's no media, bail\n if (!this.media) {\n this.debug.warn('No media element found!');\n return;\n }\n\n // Add type class\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true);\n\n // Add provider class\n toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true);\n\n // Add video class for embeds\n // This will require changes if audio embeds are added\n if (this.isEmbed) {\n toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true);\n }\n\n // Inject the player wrapper\n if (this.isVideo) {\n // Create the wrapper div\n this.elements.wrapper = createElement('div', {\n class: this.config.classNames.video,\n });\n\n // Wrap the video in a container\n wrap(this.media, this.elements.wrapper);\n\n // Poster image container\n this.elements.poster = createElement('div', {\n class: this.config.classNames.poster,\n });\n\n this.elements.wrapper.appendChild(this.elements.poster);\n }\n\n if (this.isHTML5) {\n html5.setup.call(this);\n } else if (this.isYouTube) {\n youtube.setup.call(this);\n } else if (this.isVimeo) {\n vimeo.setup.call(this);\n }\n },\n};\n\nexport default media;\n","// ==========================================================================\n// Advertisement plugin using Google IMA HTML5 SDK\n// Create an account with our ad partner, vi here:\n// https://www.vi.ai/publisher-video-monetization/\n// ==========================================================================\n\n/* global google */\n\nimport { createElement } from '../utils/elements';\nimport { triggerEvent } from '../utils/events';\nimport i18n from '../utils/i18n';\nimport is from '../utils/is';\nimport loadScript from '../utils/load-script';\nimport { silencePromise } from '../utils/promise';\nimport { formatTime } from '../utils/time';\nimport { buildUrlParams } from '../utils/urls';\n\nconst destroy = (instance) => {\n // Destroy our adsManager\n if (instance.manager) {\n instance.manager.destroy();\n }\n\n // Destroy our adsManager\n if (instance.elements.displayContainer) {\n instance.elements.displayContainer.destroy();\n }\n\n instance.elements.container.remove();\n};\n\nclass Ads {\n /**\n * Ads constructor.\n * @param {Object} player\n * @return {Ads}\n */\n constructor(player) {\n this.player = player;\n this.config = player.config.ads;\n this.playing = false;\n this.initialized = false;\n this.elements = {\n container: null,\n displayContainer: null,\n };\n this.manager = null;\n this.loader = null;\n this.cuePoints = null;\n this.events = {};\n this.safetyTimer = null;\n this.countdownTimer = null;\n\n // Setup a promise to resolve when the IMA manager is ready\n this.managerPromise = new Promise((resolve, reject) => {\n // The ad is loaded and ready\n this.on('loaded', resolve);\n\n // Ads failed\n this.on('error', reject);\n });\n\n this.load();\n }\n\n get enabled() {\n const { config } = this;\n\n return (\n this.player.isHTML5 &&\n this.player.isVideo &&\n config.enabled &&\n (!is.empty(config.publisherId) || is.url(config.tagUrl))\n );\n }\n\n /**\n * Load the IMA SDK\n */\n load = () => {\n if (!this.enabled) {\n return;\n }\n\n // Check if the Google IMA3 SDK is loaded or load it ourselves\n if (!is.object(window.google) || !is.object(window.google.ima)) {\n loadScript(this.player.config.urls.googleIMA.sdk)\n .then(() => {\n this.ready();\n })\n .catch(() => {\n // Script failed to load or is blocked\n this.trigger('error', new Error('Google IMA SDK failed to load'));\n });\n } else {\n this.ready();\n }\n };\n\n /**\n * Get the ads instance ready\n */\n ready = () => {\n // Double check we're enabled\n if (!this.enabled) {\n destroy(this);\n }\n\n // Start ticking our safety timer. If the whole advertisement\n // thing doesn't resolve within our set time; we bail\n this.startSafetyTimer(12000, 'ready()');\n\n // Clear the safety timer\n this.managerPromise.then(() => {\n this.clearSafetyTimer('onAdsManagerLoaded()');\n });\n\n // Set listeners on the Plyr instance\n this.listeners();\n\n // Setup the IMA SDK\n this.setupIMA();\n };\n\n // Build the tag URL\n get tagUrl() {\n const { config } = this;\n\n if (is.url(config.tagUrl)) {\n return config.tagUrl;\n }\n\n const params = {\n AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',\n AV_CHANNELID: '5a0458dc28a06145e4519d21',\n AV_URL: window.location.hostname,\n cb: Date.now(),\n AV_WIDTH: 640,\n AV_HEIGHT: 480,\n AV_CDIM2: config.publisherId,\n };\n\n const base = 'https://go.aniview.com/api/adserver6/vast/';\n\n return `${base}?${buildUrlParams(params)}`;\n }\n\n /**\n * In order for the SDK to display ads for our video, we need to tell it where to put them,\n * so here we define our ad container. This div is set up to render on top of the video player.\n * Using the code below, we tell the SDK to render ads within that div. We also provide a\n * handle to the content video player - the SDK will poll the current time of our player to\n * properly place mid-rolls. After we create the ad display container, we initialize it. On\n * mobile devices, this initialization is done as the result of a user action.\n */\n setupIMA = () => {\n // Create the container for our advertisements\n this.elements.container = createElement('div', {\n class: this.player.config.classNames.ads,\n });\n\n this.player.elements.container.appendChild(this.elements.container);\n\n // So we can run VPAID2\n google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);\n\n // Set language\n google.ima.settings.setLocale(this.player.config.ads.language);\n\n // Set playback for iOS10+\n google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline);\n\n // We assume the adContainer is the video container of the plyr element that will house the ads\n this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container, this.player.media);\n\n // Create ads loader\n this.loader = new google.ima.AdsLoader(this.elements.displayContainer);\n\n // Listen and respond to ads loaded and error events\n this.loader.addEventListener(\n google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,\n (event) => this.onAdsManagerLoaded(event),\n false,\n );\n this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, (error) => this.onAdError(error), false);\n\n // Request video ads to be pre-loaded\n this.requestAds();\n };\n\n /**\n * Request advertisements\n */\n requestAds = () => {\n const { container } = this.player.elements;\n\n try {\n // Request video ads\n const request = new google.ima.AdsRequest();\n request.adTagUrl = this.tagUrl;\n\n // Specify the linear and nonlinear slot sizes. This helps the SDK\n // to select the correct creative if multiple are returned\n request.linearAdSlotWidth = container.offsetWidth;\n request.linearAdSlotHeight = container.offsetHeight;\n request.nonLinearAdSlotWidth = container.offsetWidth;\n request.nonLinearAdSlotHeight = container.offsetHeight;\n\n // We only overlay ads as we only support video.\n request.forceNonLinearFullSlot = false;\n\n // Mute based on current state\n request.setAdWillPlayMuted(!this.player.muted);\n\n this.loader.requestAds(request);\n } catch (error) {\n this.onAdError(error);\n }\n };\n\n /**\n * Update the ad countdown\n * @param {Boolean} start\n */\n pollCountdown = (start = false) => {\n if (!start) {\n clearInterval(this.countdownTimer);\n this.elements.container.removeAttribute('data-badge-text');\n return;\n }\n\n const update = () => {\n const time = formatTime(Math.max(this.manager.getRemainingTime(), 0));\n const label = `${i18n.get('advertisement', this.player.config)} - ${time}`;\n this.elements.container.setAttribute('data-badge-text', label);\n };\n\n this.countdownTimer = setInterval(update, 100);\n };\n\n /**\n * This method is called whenever the ads are ready inside the AdDisplayContainer\n * @param {Event} adsManagerLoadedEvent\n */\n onAdsManagerLoaded = (event) => {\n // Load could occur after a source change (race condition)\n if (!this.enabled) {\n return;\n }\n\n // Get the ads manager\n const settings = new google.ima.AdsRenderingSettings();\n\n // Tell the SDK to save and restore content video state on our behalf\n settings.restoreCustomPlaybackStateOnAdBreakComplete = true;\n settings.enablePreloading = true;\n\n // The SDK is polling currentTime on the contentPlayback. And needs a duration\n // so it can determine when to start the mid- and post-roll\n this.manager = event.getAdsManager(this.player, settings);\n\n // Get the cue points for any mid-rolls by filtering out the pre- and post-roll\n this.cuePoints = this.manager.getCuePoints();\n\n // Add listeners to the required events\n // Advertisement error events\n this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, (error) => this.onAdError(error));\n\n // Advertisement regular events\n Object.keys(google.ima.AdEvent.Type).forEach((type) => {\n this.manager.addEventListener(google.ima.AdEvent.Type[type], (e) => this.onAdEvent(e));\n });\n\n // Resolve our adsManager\n this.trigger('loaded');\n };\n\n addCuePoints = () => {\n // Add advertisement cue's within the time line if available\n if (!is.empty(this.cuePoints)) {\n this.cuePoints.forEach((cuePoint) => {\n if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {\n const seekElement = this.player.elements.progress;\n\n if (is.element(seekElement)) {\n const cuePercentage = (100 / this.player.duration) * cuePoint;\n const cue = createElement('span', {\n class: this.player.config.classNames.cues,\n });\n\n cue.style.left = `${cuePercentage.toString()}%`;\n seekElement.appendChild(cue);\n }\n }\n });\n }\n };\n\n /**\n * This is where all the event handling takes place. Retrieve the ad from the event. Some\n * events (e.g. ALL_ADS_COMPLETED) don't have the ad object associated\n * https://developers.google.com/interactive-media-ads/docs/sdks/html5/v3/apis#ima.AdEvent.Type\n * @param {Event} event\n */\n onAdEvent = (event) => {\n const { container } = this.player.elements;\n // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)\n // don't have ad object associated\n const ad = event.getAd();\n const adData = event.getAdData();\n\n // Proxy event\n const dispatchEvent = (type) => {\n triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`);\n };\n\n // Bubble the event\n dispatchEvent(event.type);\n\n switch (event.type) {\n case google.ima.AdEvent.Type.LOADED:\n // This is the first event sent for an ad - it is possible to determine whether the\n // ad is a video ad or an overlay\n this.trigger('loaded');\n\n // Start countdown\n this.pollCountdown(true);\n\n if (!ad.isLinear()) {\n // Position AdDisplayContainer correctly for overlay\n ad.width = container.offsetWidth;\n ad.height = container.offsetHeight;\n }\n\n // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex());\n // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset());\n\n break;\n\n case google.ima.AdEvent.Type.STARTED:\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n\n break;\n\n case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:\n // All ads for the current videos are done. We can now request new advertisements\n // in case the video is re-played\n\n // TODO: Example for what happens when a next video in a playlist would be loaded.\n // So here we load a new video when all ads are done.\n // Then we load new ads within a new adsManager. When the video\n // Is started - after - the ads are loaded, then we get ads.\n // You can also easily test cancelling and reloading by running\n // player.ads.cancel() and player.ads.play from the console I guess.\n // this.player.source = {\n // type: 'video',\n // title: 'View From A Blue Moon',\n // sources: [{\n // src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type:\n // 'video/mp4', }], poster:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks:\n // [ { kind: 'captions', label: 'English', srclang: 'en', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',\n // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src:\n // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ],\n // };\n\n // TODO: So there is still this thing where a video should only be allowed to start\n // playing when the IMA SDK is ready or has failed\n\n if (this.player.ended) {\n this.loadAds();\n } else {\n // The SDK won't allow new ads to be called without receiving a contentComplete()\n this.loader.contentComplete();\n }\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:\n // This event indicates the ad has started - the video player can adjust the UI,\n // for example display a pause button and remaining time. Fired when content should\n // be paused. This usually happens right before an ad is about to cover the content\n\n this.pauseContent();\n\n break;\n\n case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:\n // This event indicates the ad has finished - the video player can perform\n // appropriate UI actions, such as removing the timer for remaining time detection.\n // Fired when content should be resumed. This usually happens when an ad finishes\n // or collapses\n\n this.pollCountdown();\n\n this.resumeContent();\n\n break;\n\n case google.ima.AdEvent.Type.LOG:\n if (adData.adError) {\n this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);\n }\n\n break;\n\n default:\n break;\n }\n };\n\n /**\n * Any ad error handling comes through here\n * @param {Event} event\n */\n onAdError = (event) => {\n this.cancel();\n this.player.debug.warn('Ads error', event);\n };\n\n /**\n * Setup hooks for Plyr and window events. This ensures\n * the mid- and post-roll launch at the correct time. And\n * resize the advertisement when the player resizes\n */\n listeners = () => {\n const { container } = this.player.elements;\n let time;\n\n this.player.on('canplay', () => {\n this.addCuePoints();\n });\n\n this.player.on('ended', () => {\n this.loader.contentComplete();\n });\n\n this.player.on('timeupdate', () => {\n time = this.player.currentTime;\n });\n\n this.player.on('seeked', () => {\n const seekedTime = this.player.currentTime;\n\n if (is.empty(this.cuePoints)) {\n return;\n }\n\n this.cuePoints.forEach((cuePoint, index) => {\n if (time < cuePoint && cuePoint < seekedTime) {\n this.manager.discardAdBreak();\n this.cuePoints.splice(index, 1);\n }\n });\n });\n\n // Listen to the resizing of the window. And resize ad accordingly\n // TODO: eventually implement ResizeObserver\n window.addEventListener('resize', () => {\n if (this.manager) {\n this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n }\n });\n };\n\n /**\n * Initialize the adsManager and start playing advertisements\n */\n play = () => {\n const { container } = this.player.elements;\n\n if (!this.managerPromise) {\n this.resumeContent();\n }\n\n // Play the requested advertisement whenever the adsManager is ready\n this.managerPromise\n .then(() => {\n // Set volume to match player\n this.manager.setVolume(this.player.volume);\n\n // Initialize the container. Must be done via a user action on mobile devices\n this.elements.displayContainer.initialize();\n\n try {\n if (!this.initialized) {\n // Initialize the ads manager. Ad rules playlist will start at this time\n this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);\n\n // Call play to start showing the ad. Single video and overlay ads will\n // start at this time; the call will be ignored for ad rules\n this.manager.start();\n }\n\n this.initialized = true;\n } catch (adError) {\n // An error may be thrown if there was a problem with the\n // VAST response\n this.onAdError(adError);\n }\n })\n .catch(() => {});\n };\n\n /**\n * Resume our video\n */\n resumeContent = () => {\n // Hide the advertisement container\n this.elements.container.style.zIndex = '';\n\n // Ad is stopped\n this.playing = false;\n\n // Play video\n silencePromise(this.player.media.play());\n };\n\n /**\n * Pause our video\n */\n pauseContent = () => {\n // Show the advertisement container\n this.elements.container.style.zIndex = 3;\n\n // Ad is playing\n this.playing = true;\n\n // Pause our video.\n this.player.media.pause();\n };\n\n /**\n * Destroy the adsManager so we can grab new ads after this. If we don't then we're not\n * allowed to call new ads based on google policies, as they interpret this as an accidental\n * video requests. https://developers.google.com/interactive-\n * media-ads/docs/sdks/android/faq#8\n */\n cancel = () => {\n // Pause our video\n if (this.initialized) {\n this.resumeContent();\n }\n\n // Tell our instance that we're done for now\n this.trigger('error');\n\n // Re-create our adsManager\n this.loadAds();\n };\n\n /**\n * Re-create our adsManager\n */\n loadAds = () => {\n // Tell our adsManager to go bye bye\n this.managerPromise\n .then(() => {\n // Destroy our adsManager\n if (this.manager) {\n this.manager.destroy();\n }\n\n // Re-set our adsManager promises\n this.managerPromise = new Promise((resolve) => {\n this.on('loaded', resolve);\n this.player.debug.log(this.manager);\n });\n // Now that the manager has been destroyed set it to also be un-initialized\n this.initialized = false;\n\n // Now request some new advertisements\n this.requestAds();\n })\n .catch(() => {});\n };\n\n /**\n * Handles callbacks after an ad event was invoked\n * @param {String} event - Event type\n */\n trigger = (event, ...args) => {\n const handlers = this.events[event];\n\n if (is.array(handlers)) {\n handlers.forEach((handler) => {\n if (is.function(handler)) {\n handler.apply(this, args);\n }\n });\n }\n };\n\n /**\n * Add event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n * @return {Ads}\n */\n on = (event, callback) => {\n if (!is.array(this.events[event])) {\n this.events[event] = [];\n }\n\n this.events[event].push(callback);\n\n return this;\n };\n\n /**\n * Setup a safety timer for when the ad network doesn't respond for whatever reason.\n * The advertisement has 12 seconds to get its things together. We stop this timer when the\n * advertisement is playing, or when a user action is required to start, then we clear the\n * timer on ad ready\n * @param {Number} time\n * @param {String} from\n */\n startSafetyTimer = (time, from) => {\n this.player.debug.log(`Safety timer invoked from: ${from}`);\n\n this.safetyTimer = setTimeout(() => {\n this.cancel();\n this.clearSafetyTimer('startSafetyTimer()');\n }, time);\n };\n\n /**\n * Clear our safety timer(s)\n * @param {String} from\n */\n clearSafetyTimer = (from) => {\n if (!is.nullOrUndefined(this.safetyTimer)) {\n this.player.debug.log(`Safety timer cleared from: ${from}`);\n\n clearTimeout(this.safetyTimer);\n this.safetyTimer = null;\n }\n };\n}\n\nexport default Ads;\n","import { createElement } from '../utils/elements';\nimport { once } from '../utils/events';\nimport fetch from '../utils/fetch';\nimport is from '../utils/is';\nimport { formatTime } from '../utils/time';\n\n// Arg: vttDataString example: \"WEBVTT\\n\\n1\\n00:00:05.000 --> 00:00:10.000\\n1080p-00001.jpg\"\nconst parseVtt = (vttDataString) => {\n const processedList = [];\n const frames = vttDataString.split(/\\r\\n\\r\\n|\\n\\n|\\r\\r/);\n\n frames.forEach((frame) => {\n const result = {};\n const lines = frame.split(/\\r\\n|\\n|\\r/);\n\n lines.forEach((line) => {\n if (!is.number(result.startTime)) {\n // The line with start and end times on it is the first line of interest\n const matchTimes = line.match(\n /([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})/,\n ); // Note that this currently ignores caption formatting directives that are optionally on the end of this line - fine for non-captions VTT\n\n if (matchTimes) {\n result.startTime =\n Number(matchTimes[1] || 0) * 60 * 60 +\n Number(matchTimes[2]) * 60 +\n Number(matchTimes[3]) +\n Number(`0.${matchTimes[4]}`);\n result.endTime =\n Number(matchTimes[6] || 0) * 60 * 60 +\n Number(matchTimes[7]) * 60 +\n Number(matchTimes[8]) +\n Number(`0.${matchTimes[9]}`);\n }\n } else if (!is.empty(line.trim()) && is.empty(result.text)) {\n // If we already have the startTime, then we're definitely up to the text line(s)\n const lineSplit = line.trim().split('#xywh=');\n [result.text] = lineSplit;\n\n // If there's content in lineSplit[1], then we have sprites. If not, then it's just one frame per image\n if (lineSplit[1]) {\n [result.x, result.y, result.w, result.h] = lineSplit[1].split(',');\n }\n }\n });\n\n if (result.text) {\n processedList.push(result);\n }\n });\n\n return processedList;\n};\n\n/**\n * Preview thumbnails for seek hover and scrubbing\n * Seeking: Hover over the seek bar (desktop only): shows a small preview container above the seek bar\n * 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\n *\n * Notes:\n * - 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\n * - 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\n * - 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\n */\n\nconst fitRatio = (ratio, outer) => {\n const targetRatio = outer.width / outer.height;\n const result = {};\n if (ratio > targetRatio) {\n result.width = outer.width;\n result.height = (1 / ratio) * outer.width;\n } else {\n result.height = outer.height;\n result.width = ratio * outer.height;\n }\n\n return result;\n};\n\nclass PreviewThumbnails {\n /**\n * PreviewThumbnails constructor.\n * @param {Plyr} player\n * @return {PreviewThumbnails}\n */\n constructor(player) {\n this.player = player;\n this.thumbnails = [];\n this.loaded = false;\n this.lastMouseMoveTime = Date.now();\n this.mouseDown = false;\n this.loadedImages = [];\n\n this.elements = {\n thumb: {},\n scrubbing: {},\n };\n\n this.load();\n }\n\n get enabled() {\n return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;\n }\n\n load = () => {\n // Toggle the regular seek tooltip\n if (this.player.elements.display.seekTooltip) {\n this.player.elements.display.seekTooltip.hidden = this.enabled;\n }\n\n if (!this.enabled) {\n return;\n }\n\n this.getThumbnails().then(() => {\n if (!this.enabled) {\n return;\n }\n\n // Render DOM elements\n this.render();\n\n // Check to see if thumb container size was specified manually in CSS\n this.determineContainerAutoSizing();\n\n this.loaded = true;\n });\n };\n\n // Download VTT files and parse them\n getThumbnails = () => {\n return new Promise((resolve) => {\n const { src } = this.player.config.previewThumbnails;\n\n if (is.empty(src)) {\n throw new Error('Missing previewThumbnails.src config attribute');\n }\n\n // Resolve promise\n const sortAndResolve = () => {\n // Sort smallest to biggest (e.g., [120p, 480p, 1080p])\n this.thumbnails.sort((x, y) => x.height - y.height);\n\n this.player.debug.log('Preview thumbnails', this.thumbnails);\n\n resolve();\n };\n\n // Via callback()\n if (is.function(src)) {\n src((thumbnails) => {\n this.thumbnails = thumbnails;\n sortAndResolve();\n });\n }\n // VTT urls\n else {\n // If string, convert into single-element list\n const urls = is.string(src) ? [src] : src;\n // Loop through each src URL. Download and process the VTT file, storing the resulting data in this.thumbnails\n const promises = urls.map((u) => this.getThumbnail(u));\n // Resolve\n Promise.all(promises).then(sortAndResolve);\n }\n });\n };\n\n // Process individual VTT file\n getThumbnail = (url) => {\n return new Promise((resolve) => {\n fetch(url).then((response) => {\n const thumbnail = {\n frames: parseVtt(response),\n height: null,\n urlPrefix: '',\n };\n\n // If the URLs don't start with '/', then we need to set their relative path to be the location of the VTT file\n // If the URLs do start with '/', then they obviously don't need a prefix, so it will remain blank\n // If the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file\n if (\n !thumbnail.frames[0].text.startsWith('/') &&\n !thumbnail.frames[0].text.startsWith('http://') &&\n !thumbnail.frames[0].text.startsWith('https://')\n ) {\n thumbnail.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1);\n }\n\n // Download the first frame, so that we can determine/set the height of this thumbnailsDef\n const tempImage = new Image();\n\n tempImage.onload = () => {\n thumbnail.height = tempImage.naturalHeight;\n thumbnail.width = tempImage.naturalWidth;\n\n this.thumbnails.push(thumbnail);\n\n resolve();\n };\n\n tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;\n });\n });\n };\n\n startMove = (event) => {\n if (!this.loaded) {\n return;\n }\n\n if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {\n return;\n }\n\n // Wait until media has a duration\n if (!this.player.media.duration) {\n return;\n }\n\n if (event.type === 'touchmove') {\n // Calculate seek hover position as approx video seconds\n this.seekTime = this.player.media.duration * (this.player.elements.inputs.seek.value / 100);\n } else {\n // Calculate seek hover position as approx video seconds\n const clientRect = this.player.elements.progress.getBoundingClientRect();\n const percentage = (100 / clientRect.width) * (event.pageX - clientRect.left);\n this.seekTime = this.player.media.duration * (percentage / 100);\n\n if (this.seekTime < 0) {\n // The mousemove fires for 10+px out to the left\n this.seekTime = 0;\n }\n\n if (this.seekTime > this.player.media.duration - 1) {\n // Took 1 second off the duration for safety, because different players can disagree on the real duration of a video\n this.seekTime = this.player.media.duration - 1;\n }\n\n this.mousePosX = event.pageX;\n\n // Set time text inside image container\n this.elements.thumb.time.innerText = formatTime(this.seekTime);\n }\n\n // Download and show image\n this.showImageAtCurrentTime();\n };\n\n endMove = () => {\n this.toggleThumbContainer(false, true);\n };\n\n startScrubbing = (event) => {\n // Only act on left mouse button (0), or touch device (event.button does not exist or is false)\n if (is.nullOrUndefined(event.button) || event.button === false || event.button === 0) {\n this.mouseDown = true;\n\n // Wait until media has a duration\n if (this.player.media.duration) {\n this.toggleScrubbingContainer(true);\n this.toggleThumbContainer(false, true);\n\n // Download and show image\n this.showImageAtCurrentTime();\n }\n }\n };\n\n endScrubbing = () => {\n this.mouseDown = false;\n\n // Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview\n if (Math.ceil(this.lastTime) === Math.ceil(this.player.media.currentTime)) {\n // The video was already seeked/loaded at the chosen time - hide immediately\n this.toggleScrubbingContainer(false);\n } else {\n // The video hasn't seeked yet. Wait for that\n once.call(this.player, this.player.media, 'timeupdate', () => {\n // Re-check mousedown - we might have already started scrubbing again\n if (!this.mouseDown) {\n this.toggleScrubbingContainer(false);\n }\n });\n }\n };\n\n /**\n * Setup hooks for Plyr and window events\n */\n listeners = () => {\n // 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\n this.player.on('play', () => {\n this.toggleThumbContainer(false, true);\n });\n\n this.player.on('seeked', () => {\n this.toggleThumbContainer(false);\n });\n\n this.player.on('timeupdate', () => {\n this.lastTime = this.player.media.currentTime;\n });\n };\n\n /**\n * Create HTML elements for image containers\n */\n render = () => {\n // Create HTML element: plyr__preview-thumbnail-container\n this.elements.thumb.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.thumbContainer,\n });\n\n // Wrapper for the image for styling\n this.elements.thumb.imageContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.imageContainer,\n });\n this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer);\n\n // Create HTML element, parent+span: time text (e.g., 01:32:00)\n const timeContainer = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.timeContainer,\n });\n\n this.elements.thumb.time = createElement('span', {}, '00:00');\n timeContainer.appendChild(this.elements.thumb.time);\n\n this.elements.thumb.container.appendChild(timeContainer);\n\n // Inject the whole thumb\n if (is.element(this.player.elements.progress)) {\n this.player.elements.progress.appendChild(this.elements.thumb.container);\n }\n\n // Create HTML element: plyr__preview-scrubbing-container\n this.elements.scrubbing.container = createElement('div', {\n class: this.player.config.classNames.previewThumbnails.scrubbingContainer,\n });\n\n this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);\n };\n\n destroy = () => {\n if (this.elements.thumb.container) {\n this.elements.thumb.container.remove();\n }\n if (this.elements.scrubbing.container) {\n this.elements.scrubbing.container.remove();\n }\n };\n\n showImageAtCurrentTime = () => {\n if (this.mouseDown) {\n this.setScrubbingContainerSize();\n } else {\n this.setThumbContainerSizeAndPos();\n }\n\n // Find the desired thumbnail index\n // TODO: Handle a video longer than the thumbs where thumbNum is null\n const thumbNum = this.thumbnails[0].frames.findIndex(\n (frame) => this.seekTime >= frame.startTime && this.seekTime <= frame.endTime,\n );\n const hasThumb = thumbNum >= 0;\n let qualityIndex = 0;\n\n // Show the thumb container if we're not scrubbing\n if (!this.mouseDown) {\n this.toggleThumbContainer(hasThumb);\n }\n\n // No matching thumb found\n if (!hasThumb) {\n return;\n }\n\n // Check to see if we've already downloaded higher quality versions of this image\n this.thumbnails.forEach((thumbnail, index) => {\n if (this.loadedImages.includes(thumbnail.frames[thumbNum].text)) {\n qualityIndex = index;\n }\n });\n\n // Only proceed if either thumbnum or thumbfilename has changed\n if (thumbNum !== this.showingThumb) {\n this.showingThumb = thumbNum;\n this.loadImage(qualityIndex);\n }\n };\n\n // Show the image that's currently specified in this.showingThumb\n loadImage = (qualityIndex = 0) => {\n const thumbNum = this.showingThumb;\n const thumbnail = this.thumbnails[qualityIndex];\n const { urlPrefix } = thumbnail;\n const frame = thumbnail.frames[thumbNum];\n const thumbFilename = thumbnail.frames[thumbNum].text;\n const thumbUrl = urlPrefix + thumbFilename;\n\n if (!this.currentImageElement || this.currentImageElement.dataset.filename !== thumbFilename) {\n // If we're already loading a previous image, remove its onload handler - we don't want it to load after this one\n // Only do this if not using sprites. Without sprites we really want to show as many images as possible, as a best-effort\n if (this.loadingImage && this.usingSprites) {\n this.loadingImage.onload = null;\n }\n\n // We're building and adding a new image. In other implementations of similar functionality (YouTube), background image\n // is instead used. But this causes issues with larger images in Firefox and Safari - switching between background\n // images causes a flicker. Putting a new image over the top does not\n const previewImage = new Image();\n previewImage.src = thumbUrl;\n previewImage.dataset.index = thumbNum;\n previewImage.dataset.filename = thumbFilename;\n this.showingThumbFilename = thumbFilename;\n\n this.player.debug.log(`Loading image: ${thumbUrl}`);\n\n // For some reason, passing the named function directly causes it to execute immediately. So I've wrapped it in an anonymous function...\n previewImage.onload = () => this.showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, true);\n this.loadingImage = previewImage;\n this.removeOldImages(previewImage);\n } else {\n // Update the existing image\n this.showImage(this.currentImageElement, frame, qualityIndex, thumbNum, thumbFilename, false);\n this.currentImageElement.dataset.index = thumbNum;\n this.removeOldImages(this.currentImageElement);\n }\n };\n\n showImage = (previewImage, frame, qualityIndex, thumbNum, thumbFilename, newImage = true) => {\n this.player.debug.log(\n `Showing thumb: ${thumbFilename}. num: ${thumbNum}. qual: ${qualityIndex}. newimg: ${newImage}`,\n );\n this.setImageSizeAndOffset(previewImage, frame);\n\n if (newImage) {\n this.currentImageContainer.appendChild(previewImage);\n this.currentImageElement = previewImage;\n\n if (!this.loadedImages.includes(thumbFilename)) {\n this.loadedImages.push(thumbFilename);\n }\n }\n\n // Preload images before and after the current one\n // Show higher quality of the same frame\n // 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\n this.preloadNearby(thumbNum, true)\n .then(this.preloadNearby(thumbNum, false))\n .then(this.getHigherQuality(qualityIndex, previewImage, frame, thumbFilename));\n };\n\n // Remove all preview images that aren't the designated current image\n removeOldImages = (currentImage) => {\n // Get a list of all images, convert it from a DOM list to an array\n Array.from(this.currentImageContainer.children).forEach((image) => {\n if (image.tagName.toLowerCase() !== 'img') {\n return;\n }\n\n const removeDelay = this.usingSprites ? 500 : 1000;\n\n if (image.dataset.index !== currentImage.dataset.index && !image.dataset.deleting) {\n // 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\n // First set attribute 'deleting' to prevent multi-handling of this on repeat firing of this function\n // eslint-disable-next-line no-param-reassign\n image.dataset.deleting = true;\n\n // This has to be set before the timeout - to prevent issues switching between hover and scrub\n const { currentImageContainer } = this;\n\n setTimeout(() => {\n currentImageContainer.removeChild(image);\n this.player.debug.log(`Removing thumb: ${image.dataset.filename}`);\n }, removeDelay);\n }\n });\n };\n\n // Preload images before and after the current one. Only if the user is still hovering/seeking the same frame\n // This will only preload the lowest quality\n preloadNearby = (thumbNum, forward = true) => {\n return new Promise((resolve) => {\n setTimeout(() => {\n const oldThumbFilename = this.thumbnails[0].frames[thumbNum].text;\n\n if (this.showingThumbFilename === oldThumbFilename) {\n // 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\n let thumbnailsClone;\n if (forward) {\n thumbnailsClone = this.thumbnails[0].frames.slice(thumbNum);\n } else {\n thumbnailsClone = this.thumbnails[0].frames.slice(0, thumbNum).reverse();\n }\n\n let foundOne = false;\n\n thumbnailsClone.forEach((frame) => {\n const newThumbFilename = frame.text;\n\n if (newThumbFilename !== oldThumbFilename) {\n // Found one with a different filename. Make sure it hasn't already been loaded on this page visit\n if (!this.loadedImages.includes(newThumbFilename)) {\n foundOne = true;\n this.player.debug.log(`Preloading thumb filename: ${newThumbFilename}`);\n\n const { urlPrefix } = this.thumbnails[0];\n const thumbURL = urlPrefix + newThumbFilename;\n const previewImage = new Image();\n previewImage.src = thumbURL;\n previewImage.onload = () => {\n this.player.debug.log(`Preloaded thumb filename: ${newThumbFilename}`);\n if (!this.loadedImages.includes(newThumbFilename)) this.loadedImages.push(newThumbFilename);\n\n // We don't resolve until the thumb is loaded\n resolve();\n };\n }\n }\n });\n\n // If there are none to preload then we want to resolve immediately\n if (!foundOne) {\n resolve();\n }\n }\n }, 300);\n });\n };\n\n // If user has been hovering current image for half a second, look for a higher quality one\n getHigherQuality = (currentQualityIndex, previewImage, frame, thumbFilename) => {\n if (currentQualityIndex < this.thumbnails.length - 1) {\n // 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\n let previewImageHeight = previewImage.naturalHeight;\n\n if (this.usingSprites) {\n previewImageHeight = frame.h;\n }\n\n if (previewImageHeight < this.thumbContainerHeight) {\n // Recurse back to the loadImage function - show a higher quality one, but only if the viewer is on this frame for a while\n setTimeout(() => {\n // Make sure the mouse hasn't already moved on and started hovering at another image\n if (this.showingThumbFilename === thumbFilename) {\n this.player.debug.log(`Showing higher quality thumb for: ${thumbFilename}`);\n this.loadImage(currentQualityIndex + 1);\n }\n }, 300);\n }\n }\n };\n\n get currentImageContainer() {\n if (this.mouseDown) {\n return this.elements.scrubbing.container;\n }\n\n return this.elements.thumb.imageContainer;\n }\n\n get usingSprites() {\n return Object.keys(this.thumbnails[0].frames[0]).includes('w');\n }\n\n get thumbAspectRatio() {\n if (this.usingSprites) {\n return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;\n }\n\n return this.thumbnails[0].width / this.thumbnails[0].height;\n }\n\n get thumbContainerHeight() {\n if (this.mouseDown) {\n const { height } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight,\n });\n return height;\n }\n\n // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset)\n if (this.sizeSpecifiedInCSS) {\n return this.elements.thumb.imageContainer.clientHeight;\n }\n\n return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);\n }\n\n get currentImageElement() {\n if (this.mouseDown) {\n return this.currentScrubbingImageElement;\n }\n\n return this.currentThumbnailImageElement;\n }\n\n set currentImageElement(element) {\n if (this.mouseDown) {\n this.currentScrubbingImageElement = element;\n } else {\n this.currentThumbnailImageElement = element;\n }\n }\n\n toggleThumbContainer = (toggle = false, clearShowing = false) => {\n const className = this.player.config.classNames.previewThumbnails.thumbContainerShown;\n this.elements.thumb.container.classList.toggle(className, toggle);\n\n if (!toggle && clearShowing) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n };\n\n toggleScrubbingContainer = (toggle = false) => {\n const className = this.player.config.classNames.previewThumbnails.scrubbingContainerShown;\n this.elements.scrubbing.container.classList.toggle(className, toggle);\n\n if (!toggle) {\n this.showingThumb = null;\n this.showingThumbFilename = null;\n }\n };\n\n determineContainerAutoSizing = () => {\n if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) {\n // This will prevent auto sizing in this.setThumbContainerSizeAndPos()\n this.sizeSpecifiedInCSS = true;\n }\n };\n\n // 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\n setThumbContainerSizeAndPos = () => {\n if (!this.sizeSpecifiedInCSS) {\n const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${this.thumbContainerHeight}px`;\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (\n this.elements.thumb.imageContainer.clientHeight > 20 &&\n this.elements.thumb.imageContainer.clientWidth < 20\n ) {\n const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;\n } else if (\n this.elements.thumb.imageContainer.clientHeight < 20 &&\n this.elements.thumb.imageContainer.clientWidth > 20\n ) {\n const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio);\n this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`;\n }\n\n this.setThumbContainerPos();\n };\n\n setThumbContainerPos = () => {\n const seekbarRect = this.player.elements.progress.getBoundingClientRect();\n const plyrRect = this.player.elements.container.getBoundingClientRect();\n const { container } = this.elements.thumb;\n // Find the lowest and highest desired left-position, so we don't slide out the side of the video container\n const minVal = plyrRect.left - seekbarRect.left + 10;\n const maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10;\n // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth\n let previewPos = this.mousePosX - seekbarRect.left - container.clientWidth / 2;\n\n if (previewPos < minVal) {\n previewPos = minVal;\n }\n\n if (previewPos > maxVal) {\n previewPos = maxVal;\n }\n\n container.style.left = `${previewPos}px`;\n };\n\n // Can't use 100% width, in case the video is a different aspect ratio to the video container\n setScrubbingContainerSize = () => {\n const { width, height } = fitRatio(this.thumbAspectRatio, {\n width: this.player.media.clientWidth,\n height: this.player.media.clientHeight,\n });\n this.elements.scrubbing.container.style.width = `${width}px`;\n this.elements.scrubbing.container.style.height = `${height}px`;\n };\n\n // Sprites need to be offset to the correct location\n setImageSizeAndOffset = (previewImage, frame) => {\n if (!this.usingSprites) {\n return;\n }\n\n // Find difference between height and preview container height\n const multiplier = this.thumbContainerHeight / frame.h;\n\n // eslint-disable-next-line no-param-reassign\n previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.left = `-${frame.x * multiplier}px`;\n // eslint-disable-next-line no-param-reassign\n previewImage.style.top = `-${frame.y * multiplier}px`;\n };\n}\n\nexport default PreviewThumbnails;\n","// ==========================================================================\n// Plyr source update\n// ==========================================================================\n\nimport { providers } from './config/types';\nimport html5 from './html5';\nimport media from './media';\nimport PreviewThumbnails from './plugins/preview-thumbnails';\nimport support from './support';\nimport ui from './ui';\nimport { createElement, insertElement, removeElement } from './utils/elements';\nimport is from './utils/is';\nimport { getDeep } from './utils/objects';\n\nconst source = {\n // Add elements to HTML5 media (source, tracks, etc)\n insertElements(type, attributes) {\n if (is.string(attributes)) {\n insertElement(type, this.media, {\n src: attributes,\n });\n } else if (is.array(attributes)) {\n attributes.forEach((attribute) => {\n insertElement(type, this.media, attribute);\n });\n }\n },\n\n // Update source\n // Sources are not checked for support so be careful\n change(input) {\n if (!getDeep(input, 'sources.length')) {\n this.debug.warn('Invalid source format');\n return;\n }\n\n // Cancel current network requests\n html5.cancelRequests.call(this);\n\n // Destroy instance and re-setup\n this.destroy.call(\n this,\n () => {\n // Reset quality options\n this.options.quality = [];\n\n // Remove elements\n removeElement(this.media);\n this.media = null;\n\n // Reset class name\n if (is.element(this.elements.container)) {\n this.elements.container.removeAttribute('class');\n }\n\n // Set the type and provider\n const { sources, type } = input;\n const [{ provider = providers.html5, src }] = sources;\n const tagName = provider === 'html5' ? type : 'div';\n const attributes = provider === 'html5' ? {} : { src };\n\n Object.assign(this, {\n provider,\n type,\n // Check for support\n supported: support.check(type, provider, this.config.playsinline),\n // Create new element\n media: createElement(tagName, attributes),\n });\n\n // Inject the new element\n this.elements.container.appendChild(this.media);\n\n // Autoplay the new source?\n if (is.boolean(input.autoplay)) {\n this.config.autoplay = input.autoplay;\n }\n\n // Set attributes for audio and video\n if (this.isHTML5) {\n if (this.config.crossorigin) {\n this.media.setAttribute('crossorigin', '');\n }\n if (this.config.autoplay) {\n this.media.setAttribute('autoplay', '');\n }\n if (!is.empty(input.poster)) {\n this.poster = input.poster;\n }\n if (this.config.loop.active) {\n this.media.setAttribute('loop', '');\n }\n if (this.config.muted) {\n this.media.setAttribute('muted', '');\n }\n if (this.config.playsinline) {\n this.media.setAttribute('playsinline', '');\n }\n }\n\n // Restore class hook\n ui.addStyleHook.call(this);\n\n // Set new sources for html5\n if (this.isHTML5) {\n source.insertElements.call(this, 'source', sources);\n }\n\n // Set video title\n this.config.title = input.title;\n\n // Set up from scratch\n media.setup.call(this);\n\n // HTML5 stuff\n if (this.isHTML5) {\n // Setup captions\n if (Object.keys(input).includes('tracks')) {\n source.insertElements.call(this, 'track', input.tracks);\n }\n }\n\n // If HTML5 or embed but not fully supported, setupInterface and call ready now\n if (this.isHTML5 || (this.isEmbed && !this.supported.ui)) {\n // Setup interface\n ui.build.call(this);\n }\n\n // Load HTML5 sources\n if (this.isHTML5) {\n this.media.load();\n }\n\n // Update previewThumbnails config & reload plugin\n if (!is.empty(input.previewThumbnails)) {\n Object.assign(this.config.previewThumbnails, input.previewThumbnails);\n\n // Cleanup previewThumbnails plugin if it was loaded\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n // Create new instance if it is still enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n // Update the fullscreen support\n this.fullscreen.update();\n },\n true,\n );\n },\n};\n\nexport default source;\n","/**\n * Returns a number whose value is limited to the given range.\n *\n * Example: limit the output of this computation to between 0 and 255\n * (x * 255).clamp(0, 255)\n *\n * @param {Number} input\n * @param {Number} min The lower boundary of the output range\n * @param {Number} max The upper boundary of the output range\n * @returns A number in the range [min, max]\n * @type Number\n */\nexport function clamp(input = 0, min = 0, max = 255) {\n return Math.min(Math.max(input, min), max);\n}\n\nexport default { clamp };\n","// ==========================================================================\n// Plyr\n// plyr.js v3.6.12\n// https://github.com/sampotts/plyr\n// License: The MIT License (MIT)\n// ==========================================================================\n\nimport captions from './captions';\nimport defaults from './config/defaults';\nimport { pip } from './config/states';\nimport { getProviderByUrl, providers, types } from './config/types';\nimport Console from './console';\nimport controls from './controls';\nimport Fullscreen from './fullscreen';\nimport html5 from './html5';\nimport Listeners from './listeners';\nimport media from './media';\nimport Ads from './plugins/ads';\nimport PreviewThumbnails from './plugins/preview-thumbnails';\nimport source from './source';\nimport Storage from './storage';\nimport support from './support';\nimport ui from './ui';\nimport { closest } from './utils/arrays';\nimport { createElement, hasClass, removeElement, replaceElement, toggleClass, wrap } from './utils/elements';\nimport { off, on, once, triggerEvent, unbindListeners } from './utils/events';\nimport is from './utils/is';\nimport loadSprite from './utils/load-sprite';\nimport { clamp } from './utils/numbers';\nimport { cloneDeep, extend } from './utils/objects';\nimport { silencePromise } from './utils/promise';\nimport { getAspectRatio, reduceAspectRatio, setAspectRatio, validateAspectRatio } from './utils/style';\nimport { parseUrl } from './utils/urls';\n\n// Private properties\n// TODO: Use a WeakMap for private globals\n// const globals = new WeakMap();\n\n// Plyr instance\nclass Plyr {\n constructor(target, options) {\n this.timers = {};\n\n // State\n this.ready = false;\n this.loading = false;\n this.failed = false;\n\n // Touch device\n this.touch = support.touch;\n\n // Set the media element\n this.media = target;\n\n // String selector passed\n if (is.string(this.media)) {\n this.media = document.querySelectorAll(this.media);\n }\n\n // jQuery, NodeList or Array passed, use first element\n if ((window.jQuery && this.media instanceof jQuery) || is.nodeList(this.media) || is.array(this.media)) {\n // eslint-disable-next-line\n this.media = this.media[0];\n }\n\n // Set config\n this.config = extend(\n {},\n defaults,\n Plyr.defaults,\n options || {},\n (() => {\n try {\n return JSON.parse(this.media.getAttribute('data-plyr-config'));\n } catch (_) {\n return {};\n }\n })(),\n );\n\n // Elements cache\n this.elements = {\n container: null,\n fullscreen: null,\n captions: null,\n buttons: {},\n display: {},\n progress: {},\n inputs: {},\n settings: {\n popup: null,\n menu: null,\n panels: {},\n buttons: {},\n },\n };\n\n // Captions\n this.captions = {\n active: null,\n currentTrack: -1,\n meta: new WeakMap(),\n };\n\n // Fullscreen\n this.fullscreen = {\n active: false,\n };\n\n // Options\n this.options = {\n speed: [],\n quality: [],\n };\n\n // Debugging\n // TODO: move to globals\n this.debug = new Console(this.config.debug);\n\n // Log config options and support\n this.debug.log('Config', this.config);\n this.debug.log('Support', support);\n\n // We need an element to setup\n if (is.nullOrUndefined(this.media) || !is.element(this.media)) {\n this.debug.error('Setup failed: no suitable element passed');\n return;\n }\n\n // Bail if the element is initialized\n if (this.media.plyr) {\n this.debug.warn('Target already setup');\n return;\n }\n\n // Bail if not enabled\n if (!this.config.enabled) {\n this.debug.error('Setup failed: disabled by config');\n return;\n }\n\n // Bail if disabled or no basic support\n // You may want to disable certain UAs etc\n if (!support.check().api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n // Cache original element state for .destroy()\n const clone = this.media.cloneNode(true);\n clone.autoplay = false;\n this.elements.original = clone;\n\n // Set media type based on tag or data attribute\n // Supported: video, audio, vimeo, youtube\n const type = this.media.tagName.toLowerCase();\n // Embed properties\n let iframe = null;\n let url = null;\n\n // Different setup based on type\n switch (type) {\n case 'div':\n // Find the frame\n iframe = this.media.querySelector('iframe');\n\n // <iframe> type\n if (is.element(iframe)) {\n // Detect provider\n url = parseUrl(iframe.getAttribute('src'));\n this.provider = getProviderByUrl(url.toString());\n\n // Rework elements\n this.elements.container = this.media;\n this.media = iframe;\n\n // Reset classname\n this.elements.container.className = '';\n\n // Get attributes from URL and set config\n if (url.search.length) {\n const truthy = ['1', 'true'];\n\n if (truthy.includes(url.searchParams.get('autoplay'))) {\n this.config.autoplay = true;\n }\n if (truthy.includes(url.searchParams.get('loop'))) {\n this.config.loop.active = true;\n }\n\n // TODO: replace fullscreen.iosNative with this playsinline config option\n // YouTube requires the playsinline in the URL\n if (this.isYouTube) {\n this.config.playsinline = truthy.includes(url.searchParams.get('playsinline'));\n this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language?\n } else {\n this.config.playsinline = true;\n }\n }\n } else {\n // <div> with attributes\n this.provider = this.media.getAttribute(this.config.attributes.embed.provider);\n\n // Remove attribute\n this.media.removeAttribute(this.config.attributes.embed.provider);\n }\n\n // Unsupported or missing provider\n if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) {\n this.debug.error('Setup failed: Invalid provider');\n return;\n }\n\n // Audio will come later for external providers\n this.type = types.video;\n\n break;\n\n case 'video':\n case 'audio':\n this.type = type;\n this.provider = providers.html5;\n\n // Get config from attributes\n if (this.media.hasAttribute('crossorigin')) {\n this.config.crossorigin = true;\n }\n if (this.media.hasAttribute('autoplay')) {\n this.config.autoplay = true;\n }\n if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) {\n this.config.playsinline = true;\n }\n if (this.media.hasAttribute('muted')) {\n this.config.muted = true;\n }\n if (this.media.hasAttribute('loop')) {\n this.config.loop.active = true;\n }\n\n break;\n\n default:\n this.debug.error('Setup failed: unsupported type');\n return;\n }\n\n // Check for support again but with type\n this.supported = support.check(this.type, this.provider, this.config.playsinline);\n\n // If no support for even API, bail\n if (!this.supported.api) {\n this.debug.error('Setup failed: no support');\n return;\n }\n\n this.eventListeners = [];\n\n // Create listeners\n this.listeners = new Listeners(this);\n\n // Setup local storage for user settings\n this.storage = new Storage(this);\n\n // Store reference\n this.media.plyr = this;\n\n // Wrap media\n if (!is.element(this.elements.container)) {\n this.elements.container = createElement('div', { tabindex: 0 });\n wrap(this.media, this.elements.container);\n }\n\n // Migrate custom properties from media to container (so they work 😉)\n ui.migrateStyles.call(this);\n\n // Add style hook\n ui.addStyleHook.call(this);\n\n // Setup media\n media.setup.call(this);\n\n // Listen for events if debugging\n if (this.config.debug) {\n on.call(this, this.elements.container, this.config.events.join(' '), (event) => {\n this.debug.log(`event: ${event.type}`);\n });\n }\n\n // Setup fullscreen\n this.fullscreen = new Fullscreen(this);\n\n // Setup interface\n // If embed but not fully supported, build interface now to avoid flash of controls\n if (this.isHTML5 || (this.isEmbed && !this.supported.ui)) {\n ui.build.call(this);\n }\n\n // Container listeners\n this.listeners.container();\n\n // Global listeners\n this.listeners.global();\n\n // Setup ads if provided\n if (this.config.ads.enabled) {\n this.ads = new Ads(this);\n }\n\n // Autoplay if required\n if (this.isHTML5 && this.config.autoplay) {\n this.once('canplay', () => silencePromise(this.play()));\n }\n\n // Seek time will be recorded (in listeners.js) so we can prevent hiding controls for a few seconds after seek\n this.lastSeekTime = 0;\n\n // Setup preview thumbnails if enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n // ---------------------------------------\n // API\n // ---------------------------------------\n\n /**\n * Types and provider helpers\n */\n get isHTML5() {\n return this.provider === providers.html5;\n }\n\n get isEmbed() {\n return this.isYouTube || this.isVimeo;\n }\n\n get isYouTube() {\n return this.provider === providers.youtube;\n }\n\n get isVimeo() {\n return this.provider === providers.vimeo;\n }\n\n get isVideo() {\n return this.type === types.video;\n }\n\n get isAudio() {\n return this.type === types.audio;\n }\n\n /**\n * Play the media, or play the advertisement (if they are not blocked)\n */\n play = () => {\n if (!is.function(this.media.play)) {\n return null;\n }\n\n // Intecept play with ads\n if (this.ads && this.ads.enabled) {\n this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play()));\n }\n\n // Return the promise (for HTML5)\n return this.media.play();\n };\n\n /**\n * Pause the media\n */\n pause = () => {\n if (!this.playing || !is.function(this.media.pause)) {\n return null;\n }\n\n return this.media.pause();\n };\n\n /**\n * Get playing state\n */\n get playing() {\n return Boolean(this.ready && !this.paused && !this.ended);\n }\n\n /**\n * Get paused state\n */\n get paused() {\n return Boolean(this.media.paused);\n }\n\n /**\n * Get stopped state\n */\n get stopped() {\n return Boolean(this.paused && this.currentTime === 0);\n }\n\n /**\n * Get ended state\n */\n get ended() {\n return Boolean(this.media.ended);\n }\n\n /**\n * Toggle playback based on current status\n * @param {Boolean} input\n */\n togglePlay = (input) => {\n // Toggle based on current state if nothing passed\n const toggle = is.boolean(input) ? input : !this.playing;\n\n if (toggle) {\n return this.play();\n }\n\n return this.pause();\n };\n\n /**\n * Stop playback\n */\n stop = () => {\n if (this.isHTML5) {\n this.pause();\n this.restart();\n } else if (is.function(this.media.stop)) {\n this.media.stop();\n }\n };\n\n /**\n * Restart playback\n */\n restart = () => {\n this.currentTime = 0;\n };\n\n /**\n * Rewind\n * @param {Number} seekTime - how far to rewind in seconds. Defaults to the config.seekTime\n */\n rewind = (seekTime) => {\n this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime;\n };\n\n /**\n * Fast forward\n * @param {Number} seekTime - how far to fast forward in seconds. Defaults to the config.seekTime\n */\n forward = (seekTime) => {\n this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime;\n };\n\n /**\n * Seek to a time\n * @param {Number} input - where to seek to in seconds. Defaults to 0 (the start)\n */\n set currentTime(input) {\n // Bail if media duration isn't available yet\n if (!this.duration) {\n return;\n }\n\n // Validate input\n const inputIsValid = is.number(input) && input > 0;\n\n // Set\n this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0;\n\n // Logging\n this.debug.log(`Seeking to ${this.currentTime} seconds`);\n }\n\n /**\n * Get current time\n */\n get currentTime() {\n return Number(this.media.currentTime);\n }\n\n /**\n * Get buffered\n */\n get buffered() {\n const { buffered } = this.media;\n\n // YouTube / Vimeo return a float between 0-1\n if (is.number(buffered)) {\n return buffered;\n }\n\n // HTML5\n // TODO: Handle buffered chunks of the media\n // (i.e. seek to another section buffers only that section)\n if (buffered && buffered.length && this.duration > 0) {\n return buffered.end(0) / this.duration;\n }\n\n return 0;\n }\n\n /**\n * Get seeking status\n */\n get seeking() {\n return Boolean(this.media.seeking);\n }\n\n /**\n * Get the duration of the current media\n */\n get duration() {\n // Faux duration set via config\n const fauxDuration = parseFloat(this.config.duration);\n // Media duration can be NaN or Infinity before the media has loaded\n const realDuration = (this.media || {}).duration;\n const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration;\n\n // If config duration is funky, use regular duration\n return fauxDuration || duration;\n }\n\n /**\n * Set the player volume\n * @param {Number} value - must be between 0 and 1. Defaults to the value from local storage and config.volume if not set in storage\n */\n set volume(value) {\n let volume = value;\n const max = 1;\n const min = 0;\n\n if (is.string(volume)) {\n volume = Number(volume);\n }\n\n // Load volume from storage if no value specified\n if (!is.number(volume)) {\n volume = this.storage.get('volume');\n }\n\n // Use config if all else fails\n if (!is.number(volume)) {\n ({ volume } = this.config);\n }\n\n // Maximum is volumeMax\n if (volume > max) {\n volume = max;\n }\n // Minimum is volumeMin\n if (volume < min) {\n volume = min;\n }\n\n // Update config\n this.config.volume = volume;\n\n // Set the player volume\n this.media.volume = volume;\n\n // If muted, and we're increasing volume manually, reset muted state\n if (!is.empty(value) && this.muted && volume > 0) {\n this.muted = false;\n }\n }\n\n /**\n * Get the current player volume\n */\n get volume() {\n return Number(this.media.volume);\n }\n\n /**\n * Increase volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n increaseVolume = (step) => {\n const volume = this.media.muted ? 0 : this.volume;\n this.volume = volume + (is.number(step) ? step : 0);\n };\n\n /**\n * Decrease volume\n * @param {Boolean} step - How much to decrease by (between 0 and 1)\n */\n decreaseVolume = (step) => {\n this.increaseVolume(-step);\n };\n\n /**\n * Set muted state\n * @param {Boolean} mute\n */\n set muted(mute) {\n let toggle = mute;\n\n // Load muted state from storage\n if (!is.boolean(toggle)) {\n toggle = this.storage.get('muted');\n }\n\n // Use config if all else fails\n if (!is.boolean(toggle)) {\n toggle = this.config.muted;\n }\n\n // Update config\n this.config.muted = toggle;\n\n // Set mute on the player\n this.media.muted = toggle;\n }\n\n /**\n * Get current muted state\n */\n get muted() {\n return Boolean(this.media.muted);\n }\n\n /**\n * Check if the media has audio\n */\n get hasAudio() {\n // Assume yes for all non HTML5 (as we can't tell...)\n if (!this.isHTML5) {\n return true;\n }\n\n if (this.isAudio) {\n return true;\n }\n\n // Get audio tracks\n return (\n Boolean(this.media.mozHasAudio) ||\n Boolean(this.media.webkitAudioDecodedByteCount) ||\n Boolean(this.media.audioTracks && this.media.audioTracks.length)\n );\n }\n\n /**\n * Set playback speed\n * @param {Number} speed - the speed of playback (0.5-2.0)\n */\n set speed(input) {\n let speed = null;\n\n if (is.number(input)) {\n speed = input;\n }\n\n if (!is.number(speed)) {\n speed = this.storage.get('speed');\n }\n\n if (!is.number(speed)) {\n speed = this.config.speed.selected;\n }\n\n // Clamp to min/max\n const { minimumSpeed: min, maximumSpeed: max } = this;\n speed = clamp(speed, min, max);\n\n // Update config\n this.config.speed.selected = speed;\n\n // Set media speed\n setTimeout(() => {\n if (this.media) {\n this.media.playbackRate = speed;\n }\n }, 0);\n }\n\n /**\n * Get current playback speed\n */\n get speed() {\n return Number(this.media.playbackRate);\n }\n\n /**\n * Get the minimum allowed speed\n */\n get minimumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.min(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 0.5;\n }\n\n // https://stackoverflow.com/a/32320020/1191319\n return 0.0625;\n }\n\n /**\n * Get the maximum allowed speed\n */\n get maximumSpeed() {\n if (this.isYouTube) {\n // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate\n return Math.max(...this.options.speed);\n }\n\n if (this.isVimeo) {\n // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror\n return 2;\n }\n\n // https://stackoverflow.com/a/32320020/1191319\n return 16;\n }\n\n /**\n * Set playback quality\n * Currently HTML5 & YouTube only\n * @param {Number} input - Quality level\n */\n set quality(input) {\n const config = this.config.quality;\n const options = this.options.quality;\n\n if (!options.length) {\n return;\n }\n\n let quality = [\n !is.empty(input) && Number(input),\n this.storage.get('quality'),\n config.selected,\n config.default,\n ].find(is.number);\n\n let updateStorage = true;\n\n if (!options.includes(quality)) {\n const value = closest(options, quality);\n this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`);\n quality = value;\n\n // Don't update storage if quality is not supported\n updateStorage = false;\n }\n\n // Update config\n config.selected = quality;\n\n // Set quality\n this.media.quality = quality;\n\n // Save to storage\n if (updateStorage) {\n this.storage.set({ quality });\n }\n }\n\n /**\n * Get current quality level\n */\n get quality() {\n return this.media.quality;\n }\n\n /**\n * Toggle loop\n * TODO: Finish fancy new logic. Set the indicator on load as user may pass loop as config\n * @param {Boolean} input - Whether to loop or not\n */\n set loop(input) {\n const toggle = is.boolean(input) ? input : this.config.loop.active;\n this.config.loop.active = toggle;\n this.media.loop = toggle;\n\n // Set default to be a true toggle\n /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle';\n\n switch (type) {\n case 'start':\n if (this.config.loop.end && this.config.loop.end <= this.currentTime) {\n this.config.loop.end = null;\n }\n this.config.loop.start = this.currentTime;\n // this.config.loop.indicator.start = this.elements.display.played.value;\n break;\n\n case 'end':\n if (this.config.loop.start >= this.currentTime) {\n return this;\n }\n this.config.loop.end = this.currentTime;\n // this.config.loop.indicator.end = this.elements.display.played.value;\n break;\n\n case 'all':\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n this.config.loop.indicator.start = 0;\n this.config.loop.indicator.end = 100;\n break;\n\n case 'toggle':\n if (this.config.loop.active) {\n this.config.loop.start = 0;\n this.config.loop.end = null;\n } else {\n this.config.loop.start = 0;\n this.config.loop.end = this.duration - 2;\n }\n break;\n\n default:\n this.config.loop.start = 0;\n this.config.loop.end = null;\n break;\n } */\n }\n\n /**\n * Get current loop state\n */\n get loop() {\n return Boolean(this.media.loop);\n }\n\n /**\n * Set new media source\n * @param {Object} input - The new source object (see docs)\n */\n set source(input) {\n source.change.call(this, input);\n }\n\n /**\n * Get current source\n */\n get source() {\n return this.media.currentSrc;\n }\n\n /**\n * Get a download URL (either source or custom)\n */\n get download() {\n const { download } = this.config.urls;\n\n return is.url(download) ? download : this.source;\n }\n\n /**\n * Set the download URL\n */\n set download(input) {\n if (!is.url(input)) {\n return;\n }\n\n this.config.urls.download = input;\n\n controls.setDownloadUrl.call(this);\n }\n\n /**\n * Set the poster image for a video\n * @param {String} input - the URL for the new poster image\n */\n set poster(input) {\n if (!this.isVideo) {\n this.debug.warn('Poster can only be set for video');\n return;\n }\n\n ui.setPoster.call(this, input, false).catch(() => {});\n }\n\n /**\n * Get the current poster image\n */\n get poster() {\n if (!this.isVideo) {\n return null;\n }\n\n return this.media.getAttribute('poster') || this.media.getAttribute('data-poster');\n }\n\n /**\n * Get the current aspect ratio in use\n */\n get ratio() {\n if (!this.isVideo) {\n return null;\n }\n\n const ratio = reduceAspectRatio(getAspectRatio.call(this));\n\n return is.array(ratio) ? ratio.join(':') : ratio;\n }\n\n /**\n * Set video aspect ratio\n */\n set ratio(input) {\n if (!this.isVideo) {\n this.debug.warn('Aspect ratio can only be set for video');\n return;\n }\n\n if (!is.string(input) || !validateAspectRatio(input)) {\n this.debug.error(`Invalid aspect ratio specified (${input})`);\n return;\n }\n\n this.config.ratio = reduceAspectRatio(input);\n\n setAspectRatio.call(this);\n }\n\n /**\n * Set the autoplay state\n * @param {Boolean} input - Whether to autoplay or not\n */\n set autoplay(input) {\n const toggle = is.boolean(input) ? input : this.config.autoplay;\n this.config.autoplay = toggle;\n }\n\n /**\n * Get the current autoplay state\n */\n get autoplay() {\n return Boolean(this.config.autoplay);\n }\n\n /**\n * Toggle captions\n * @param {Boolean} input - Whether to enable captions\n */\n toggleCaptions(input) {\n captions.toggle.call(this, input, false);\n }\n\n /**\n * Set the caption track by index\n * @param {Number} - Caption index\n */\n set currentTrack(input) {\n captions.set.call(this, input, false);\n captions.setup();\n }\n\n /**\n * Get the current caption track index (-1 if disabled)\n */\n get currentTrack() {\n const { toggled, currentTrack } = this.captions;\n return toggled ? currentTrack : -1;\n }\n\n /**\n * Set the wanted language for captions\n * Since tracks can be added later it won't update the actual caption track until there is a matching track\n * @param {String} - Two character ISO language code (e.g. EN, FR, PT, etc)\n */\n set language(input) {\n captions.setLanguage.call(this, input, false);\n }\n\n /**\n * Get the current track's language\n */\n get language() {\n return (captions.getCurrentTrack.call(this) || {}).language;\n }\n\n /**\n * Toggle picture-in-picture playback on WebKit/MacOS\n * TODO: update player with state, support, enabled\n * TODO: detect outside changes\n */\n set pip(input) {\n // Bail if no support\n if (!support.pip) {\n return;\n }\n\n // Toggle based on current state if not passed\n const toggle = is.boolean(input) ? input : !this.pip;\n\n // Toggle based on current state\n // Safari\n if (is.function(this.media.webkitSetPresentationMode)) {\n this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive);\n }\n\n // Chrome\n if (is.function(this.media.requestPictureInPicture)) {\n if (!this.pip && toggle) {\n this.media.requestPictureInPicture();\n } else if (this.pip && !toggle) {\n document.exitPictureInPicture();\n }\n }\n }\n\n /**\n * Get the current picture-in-picture state\n */\n get pip() {\n if (!support.pip) {\n return null;\n }\n\n // Safari\n if (!is.empty(this.media.webkitPresentationMode)) {\n return this.media.webkitPresentationMode === pip.active;\n }\n\n // Chrome\n return this.media === document.pictureInPictureElement;\n }\n\n /**\n * Sets the preview thubmnails for the current source\n */\n setPreviewThumbnails(thumbnailSource) {\n if (this.previewThumbnails && this.previewThumbnails.loaded) {\n this.previewThumbnails.destroy();\n this.previewThumbnails = null;\n }\n\n Object.assign(this.config.previewThumbnails, thumbnailSource);\n\n // Create new instance if it is still enabled\n if (this.config.previewThumbnails.enabled) {\n this.previewThumbnails = new PreviewThumbnails(this);\n }\n }\n\n /**\n * Trigger the airplay dialog\n * TODO: update player with state, support, enabled\n */\n airplay = () => {\n // Show dialog if supported\n if (support.airplay) {\n this.media.webkitShowPlaybackTargetPicker();\n }\n };\n\n /**\n * Toggle the player controls\n * @param {Boolean} [toggle] - Whether to show the controls\n */\n toggleControls = (toggle) => {\n // Don't toggle if missing UI support or if it's audio\n if (this.supported.ui && !this.isAudio) {\n // Get state before change\n const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls);\n // Negate the argument if not undefined since adding the class to hides the controls\n const force = typeof toggle === 'undefined' ? undefined : !toggle;\n // Apply and get updated state\n const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force);\n\n // Close menu\n if (\n hiding &&\n is.array(this.config.controls) &&\n this.config.controls.includes('settings') &&\n !is.empty(this.config.settings)\n ) {\n controls.toggleMenu.call(this, false);\n }\n\n // Trigger event on change\n if (hiding !== isHidden) {\n const eventName = hiding ? 'controlshidden' : 'controlsshown';\n triggerEvent.call(this, this.media, eventName);\n }\n\n return !hiding;\n }\n\n return false;\n };\n\n /**\n * Add event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n on = (event, callback) => {\n on.call(this, this.elements.container, event, callback);\n };\n\n /**\n * Add event listeners once\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n once = (event, callback) => {\n once.call(this, this.elements.container, event, callback);\n };\n\n /**\n * Remove event listeners\n * @param {String} event - Event type\n * @param {Function} callback - Callback for when event occurs\n */\n off = (event, callback) => {\n off(this.elements.container, event, callback);\n };\n\n /**\n * Destroy an instance\n * Event listeners are removed when elements are removed\n * http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory\n * @param {Function} callback - Callback for when destroy is complete\n * @param {Boolean} soft - Whether it's a soft destroy (for source changes etc)\n */\n destroy = (callback, soft = false) => {\n if (!this.ready) {\n return;\n }\n\n const done = () => {\n // Reset overflow (incase destroyed while in fullscreen)\n document.body.style.overflow = '';\n\n // GC for embed\n this.embed = null;\n\n // If it's a soft destroy, make minimal changes\n if (soft) {\n if (Object.keys(this.elements).length) {\n // Remove elements\n removeElement(this.elements.buttons.play);\n removeElement(this.elements.captions);\n removeElement(this.elements.controls);\n removeElement(this.elements.wrapper);\n\n // Clear for GC\n this.elements.buttons.play = null;\n this.elements.captions = null;\n this.elements.controls = null;\n this.elements.wrapper = null;\n }\n\n // Callback\n if (is.function(callback)) {\n callback();\n }\n } else {\n // Unbind listeners\n unbindListeners.call(this);\n\n // Cancel current network requests\n html5.cancelRequests.call(this);\n\n // Replace the container with the original element provided\n replaceElement(this.elements.original, this.elements.container);\n\n // Event\n triggerEvent.call(this, this.elements.original, 'destroyed', true);\n\n // Callback\n if (is.function(callback)) {\n callback.call(this.elements.original);\n }\n\n // Reset state\n this.ready = false;\n\n // Clear for garbage collection\n setTimeout(() => {\n this.elements = null;\n this.media = null;\n }, 200);\n }\n };\n\n // Stop playback\n this.stop();\n\n // Clear timeouts\n clearTimeout(this.timers.loading);\n clearTimeout(this.timers.controls);\n clearTimeout(this.timers.resized);\n\n // Provider specific stuff\n if (this.isHTML5) {\n // Restore native video controls\n ui.toggleNativeControls.call(this, true);\n\n // Clean up\n done();\n } else if (this.isYouTube) {\n // Clear timers\n clearInterval(this.timers.buffering);\n clearInterval(this.timers.playing);\n\n // Destroy YouTube API\n if (this.embed !== null && is.function(this.embed.destroy)) {\n this.embed.destroy();\n }\n\n // Clean up\n done();\n } else if (this.isVimeo) {\n // Destroy Vimeo API\n // then clean up (wait, to prevent postmessage errors)\n if (this.embed !== null) {\n this.embed.unload().then(done);\n }\n\n // Vimeo does not always return\n setTimeout(done, 200);\n }\n };\n\n /**\n * Check for support for a mime type (HTML5 only)\n * @param {String} type - Mime type\n */\n supports = (type) => support.mime.call(this, type);\n\n /**\n * Check for support\n * @param {String} type - Player type (audio/video)\n * @param {String} provider - Provider (html5/youtube/vimeo)\n * @param {Boolean} inline - Where player has `playsinline` sttribute\n */\n static supported(type, provider, inline) {\n return support.check(type, provider, inline);\n }\n\n /**\n * Load an SVG sprite into the page\n * @param {String} url - URL for the SVG sprite\n * @param {String} [id] - Unique ID\n */\n static loadSprite(url, id) {\n return loadSprite(url, id);\n }\n\n /**\n * Setup multiple instances\n * @param {*} selector\n * @param {Object} options\n */\n static setup(selector, options = {}) {\n let targets = null;\n\n if (is.string(selector)) {\n targets = Array.from(document.querySelectorAll(selector));\n } else if (is.nodeList(selector)) {\n targets = Array.from(selector);\n } else if (is.array(selector)) {\n targets = selector.filter(is.element);\n }\n\n if (is.empty(targets)) {\n return null;\n }\n\n return targets.map((t) => new Plyr(t, options));\n }\n}\n\nPlyr.defaults = cloneDeep(defaults);\n\nexport default Plyr;\n"]}
\ No newline at end of file diff --git a/extlib/plyr/plyr.polyfilled.mjs b/extlib/plyr/plyr.polyfilled.mjs new file mode 100644 index 00000000..34fb204d --- /dev/null +++ b/extlib/plyr/plyr.polyfilled.mjs @@ -0,0 +1,9207 @@ +// Polyfill for creating CustomEvents on IE9/10/11 +// code pulled from: +// https://github.com/d4tocchini/customevent-polyfill +// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill +(function () { + if (typeof window === 'undefined') { + return; + } + + try { + var ce = new window.CustomEvent('test', { + cancelable: true + }); + ce.preventDefault(); + + if (ce.defaultPrevented !== true) { + // IE has problems with .preventDefault() on custom events + // http://stackoverflow.com/questions/23349191 + throw new Error('Could not prevent default'); + } + } catch (e) { + var CustomEvent = function (event, params) { + var evt, origPrevent; + params = params || {}; + params.bubbles = !!params.bubbles; + params.cancelable = !!params.cancelable; + evt = document.createEvent('CustomEvent'); + evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); + origPrevent = evt.preventDefault; + + evt.preventDefault = function () { + origPrevent.call(this); + + try { + Object.defineProperty(this, 'defaultPrevented', { + get: function () { + return true; + } + }); + } catch (e) { + this.defaultPrevented = true; + } + }; + + return evt; + }; + + CustomEvent.prototype = window.Event.prototype; + window.CustomEvent = CustomEvent; // expose definition to window + } +})(); + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +(function (global) { + /**
+ * Polyfill URLSearchParams
+ *
+ * Inspired from : https://github.com/WebReflection/url-search-params/blob/master/src/url-search-params.js
+ */ + var checkIfIteratorIsSupported = function () { + try { + return !!Symbol.iterator; + } catch (error) { + return false; + } + }; + + var iteratorSupported = checkIfIteratorIsSupported(); + + var createIterator = function (items) { + var iterator = { + next: function () { + var value = items.shift(); + return { + done: value === void 0, + value: value + }; + } + }; + + if (iteratorSupported) { + iterator[Symbol.iterator] = function () { + return iterator; + }; + } + + return iterator; + }; + /**
+ * Search param name and values should be encoded according to https://url.spec.whatwg.org/#urlencoded-serializing
+ * encodeURIComponent() produces the same result except encoding spaces as `%20` instead of `+`.
+ */ + + + var serializeParam = function (value) { + return encodeURIComponent(value).replace(/%20/g, '+'); + }; + + var deserializeParam = function (value) { + return decodeURIComponent(String(value).replace(/\+/g, ' ')); + }; + + var polyfillURLSearchParams = function () { + var URLSearchParams = function (searchString) { + Object.defineProperty(this, '_entries', { + writable: true, + value: {} + }); + var typeofSearchString = typeof searchString; + + if (typeofSearchString === 'undefined') ; else if (typeofSearchString === 'string') { + if (searchString !== '') { + this._fromString(searchString); + } + } else if (searchString instanceof URLSearchParams) { + var _this = this; + + searchString.forEach(function (value, name) { + _this.append(name, value); + }); + } else if (searchString !== null && typeofSearchString === 'object') { + if (Object.prototype.toString.call(searchString) === '[object Array]') { + for (var i = 0; i < searchString.length; i++) { + var entry = searchString[i]; + + if (Object.prototype.toString.call(entry) === '[object Array]' || entry.length !== 2) { + this.append(entry[0], entry[1]); + } else { + throw new TypeError('Expected [string, any] as entry at index ' + i + ' of URLSearchParams\'s input'); + } + } + } else { + for (var key in searchString) { + if (searchString.hasOwnProperty(key)) { + this.append(key, searchString[key]); + } + } + } + } else { + throw new TypeError('Unsupported input\'s type for URLSearchParams'); + } + }; + + var proto = URLSearchParams.prototype; + + proto.append = function (name, value) { + if (name in this._entries) { + this._entries[name].push(String(value)); + } else { + this._entries[name] = [String(value)]; + } + }; + + proto.delete = function (name) { + delete this._entries[name]; + }; + + proto.get = function (name) { + return name in this._entries ? this._entries[name][0] : null; + }; + + proto.getAll = function (name) { + return name in this._entries ? this._entries[name].slice(0) : []; + }; + + proto.has = function (name) { + return name in this._entries; + }; + + proto.set = function (name, value) { + this._entries[name] = [String(value)]; + }; + + proto.forEach = function (callback, thisArg) { + var entries; + + for (var name in this._entries) { + if (this._entries.hasOwnProperty(name)) { + entries = this._entries[name]; + + for (var i = 0; i < entries.length; i++) { + callback.call(thisArg, entries[i], name, this); + } + } + } + }; + + proto.keys = function () { + var items = []; + this.forEach(function (value, name) { + items.push(name); + }); + return createIterator(items); + }; + + proto.values = function () { + var items = []; + this.forEach(function (value) { + items.push(value); + }); + return createIterator(items); + }; + + proto.entries = function () { + var items = []; + this.forEach(function (value, name) { + items.push([name, value]); + }); + return createIterator(items); + }; + + if (iteratorSupported) { + proto[Symbol.iterator] = proto.entries; + } + + proto.toString = function () { + var searchArray = []; + this.forEach(function (value, name) { + searchArray.push(serializeParam(name) + '=' + serializeParam(value)); + }); + return searchArray.join('&'); + }; + + global.URLSearchParams = URLSearchParams; + }; + + var checkIfURLSearchParamsSupported = function () { + try { + var URLSearchParams = global.URLSearchParams; + return new URLSearchParams('?a=1').toString() === 'a=1' && typeof URLSearchParams.prototype.set === 'function' && typeof URLSearchParams.prototype.entries === 'function'; + } catch (e) { + return false; + } + }; + + if (!checkIfURLSearchParamsSupported()) { + polyfillURLSearchParams(); + } + + var proto = global.URLSearchParams.prototype; + + if (typeof proto.sort !== 'function') { + proto.sort = function () { + var _this = this; + + var items = []; + this.forEach(function (value, name) { + items.push([name, value]); + + if (!_this._entries) { + _this.delete(name); + } + }); + items.sort(function (a, b) { + if (a[0] < b[0]) { + return -1; + } else if (a[0] > b[0]) { + return +1; + } else { + return 0; + } + }); + + if (_this._entries) { + // force reset because IE keeps keys index + _this._entries = {}; + } + + for (var i = 0; i < items.length; i++) { + this.append(items[i][0], items[i][1]); + } + }; + } + + if (typeof proto._fromString !== 'function') { + Object.defineProperty(proto, '_fromString', { + enumerable: false, + configurable: false, + writable: false, + value: function (searchString) { + if (this._entries) { + this._entries = {}; + } else { + var keys = []; + this.forEach(function (value, name) { + keys.push(name); + }); + + for (var i = 0; i < keys.length; i++) { + this.delete(keys[i]); + } + } + + searchString = searchString.replace(/^\?/, ''); + var attributes = searchString.split('&'); + var attribute; + + for (var i = 0; i < attributes.length; i++) { + attribute = attributes[i].split('='); + this.append(deserializeParam(attribute[0]), attribute.length > 1 ? deserializeParam(attribute[1]) : ''); + } + } + }); + } // HTMLAnchorElement + +})(typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal); + +(function (global) { + /**
+ * Polyfill URL
+ *
+ * Inspired from : https://github.com/arv/DOM-URL-Polyfill/blob/master/src/url.js
+ */ + var checkIfURLIsSupported = function () { + try { + var u = new global.URL('b', 'http://a'); + u.pathname = 'c d'; + return u.href === 'http://a/c%20d' && u.searchParams; + } catch (e) { + return false; + } + }; + + var polyfillURL = function () { + var _URL = global.URL; + + var URL = function (url, base) { + if (typeof url !== 'string') url = String(url); + if (base && typeof base !== 'string') base = String(base); // Only create another document if the base is different from current location. + + var doc = document, + baseElement; + + if (base && (global.location === void 0 || base !== global.location.href)) { + base = base.toLowerCase(); + doc = document.implementation.createHTMLDocument(''); + baseElement = doc.createElement('base'); + baseElement.href = base; + doc.head.appendChild(baseElement); + + try { + if (baseElement.href.indexOf(base) !== 0) throw new Error(baseElement.href); + } catch (err) { + throw new Error('URL unable to set base ' + base + ' due to ' + err); + } + } + + var anchorElement = doc.createElement('a'); + anchorElement.href = url; + + if (baseElement) { + doc.body.appendChild(anchorElement); + anchorElement.href = anchorElement.href; // force href to refresh + } + + var inputElement = doc.createElement('input'); + inputElement.type = 'url'; + inputElement.value = url; + + if (anchorElement.protocol === ':' || !/:/.test(anchorElement.href) || !inputElement.checkValidity() && !base) { + throw new TypeError('Invalid URL'); + } + + Object.defineProperty(this, '_anchorElement', { + value: anchorElement + }); // create a linked searchParams which reflect its changes on URL + + var searchParams = new global.URLSearchParams(this.search); + var enableSearchUpdate = true; + var enableSearchParamsUpdate = true; + + var _this = this; + + ['append', 'delete', 'set'].forEach(function (methodName) { + var method = searchParams[methodName]; + + searchParams[methodName] = function () { + method.apply(searchParams, arguments); + + if (enableSearchUpdate) { + enableSearchParamsUpdate = false; + _this.search = searchParams.toString(); + enableSearchParamsUpdate = true; + } + }; + }); + Object.defineProperty(this, 'searchParams', { + value: searchParams, + enumerable: true + }); + var search = void 0; + Object.defineProperty(this, '_updateSearchParams', { + enumerable: false, + configurable: false, + writable: false, + value: function () { + if (this.search !== search) { + search = this.search; + + if (enableSearchParamsUpdate) { + enableSearchUpdate = false; + + this.searchParams._fromString(this.search); + + enableSearchUpdate = true; + } + } + } + }); + }; + + var proto = URL.prototype; + + var linkURLWithAnchorAttribute = function (attributeName) { + Object.defineProperty(proto, attributeName, { + get: function () { + return this._anchorElement[attributeName]; + }, + set: function (value) { + this._anchorElement[attributeName] = value; + }, + enumerable: true + }); + }; + + ['hash', 'host', 'hostname', 'port', 'protocol'].forEach(function (attributeName) { + linkURLWithAnchorAttribute(attributeName); + }); + Object.defineProperty(proto, 'search', { + get: function () { + return this._anchorElement['search']; + }, + set: function (value) { + this._anchorElement['search'] = value; + + this._updateSearchParams(); + }, + enumerable: true + }); + Object.defineProperties(proto, { + 'toString': { + get: function () { + var _this = this; + + return function () { + return _this.href; + }; + } + }, + 'href': { + get: function () { + return this._anchorElement.href.replace(/\?$/, ''); + }, + set: function (value) { + this._anchorElement.href = value; + + this._updateSearchParams(); + }, + enumerable: true + }, + 'pathname': { + get: function () { + return this._anchorElement.pathname.replace(/(^\/?)/, '/'); + }, + set: function (value) { + this._anchorElement.pathname = value; + }, + enumerable: true + }, + 'origin': { + get: function () { + // get expected port from protocol + var expectedPort = { + 'http:': 80, + 'https:': 443, + 'ftp:': 21 + }[this._anchorElement.protocol]; // add port to origin if, expected port is different than actual port + // and it is not empty f.e http://foo:8080 + // 8080 != 80 && 8080 != '' + + var addPortToOrigin = this._anchorElement.port != expectedPort && this._anchorElement.port !== ''; + return this._anchorElement.protocol + '//' + this._anchorElement.hostname + (addPortToOrigin ? ':' + this._anchorElement.port : ''); + }, + enumerable: true + }, + 'password': { + // TODO + get: function () { + return ''; + }, + set: function (value) {}, + enumerable: true + }, + 'username': { + // TODO + get: function () { + return ''; + }, + set: function (value) {}, + enumerable: true + } + }); + + URL.createObjectURL = function (blob) { + return _URL.createObjectURL.apply(_URL, arguments); + }; + + URL.revokeObjectURL = function (url) { + return _URL.revokeObjectURL.apply(_URL, arguments); + }; + + global.URL = URL; + }; + + if (!checkIfURLIsSupported()) { + polyfillURL(); + } + + if (global.location !== void 0 && !('origin' in global.location)) { + var getOrigin = function () { + return global.location.protocol + '//' + global.location.hostname + (global.location.port ? ':' + global.location.port : ''); + }; + + try { + Object.defineProperty(global.location, 'origin', { + get: getOrigin, + enumerable: true + }); + } catch (e) { + setInterval(function () { + global.location.origin = getOrigin(); + }, 100); + } + } +})(typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : commonjsGlobal); + +function _defineProperty$1(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +function _classCallCheck(e, t) { + if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function"); +} + +function _defineProperties(e, t) { + for (var n = 0; n < t.length; n++) { + var r = t[n]; + r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r); + } +} + +function _createClass(e, t, n) { + return t && _defineProperties(e.prototype, t), n && _defineProperties(e, n), e; +} + +function _defineProperty(e, t, n) { + return t in e ? Object.defineProperty(e, t, { + value: n, + enumerable: !0, + configurable: !0, + writable: !0 + }) : e[t] = n, e; +} + +function ownKeys(e, t) { + var n = Object.keys(e); + + if (Object.getOwnPropertySymbols) { + var r = Object.getOwnPropertySymbols(e); + t && (r = r.filter(function (t) { + return Object.getOwnPropertyDescriptor(e, t).enumerable; + })), n.push.apply(n, r); + } + + return n; +} + +function _objectSpread2(e) { + for (var t = 1; t < arguments.length; t++) { + var n = null != arguments[t] ? arguments[t] : {}; + t % 2 ? ownKeys(Object(n), !0).forEach(function (t) { + _defineProperty(e, t, n[t]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : ownKeys(Object(n)).forEach(function (t) { + Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)); + }); + } + + return e; +} + +var defaults$1 = { + addCSS: !0, + thumbWidth: 15, + watch: !0 +}; + +function matches$1(e, t) { + return function () { + return Array.from(document.querySelectorAll(t)).includes(this); + }.call(e, t); +} + +function trigger(e, t) { + if (e && t) { + var n = new Event(t, { + bubbles: !0 + }); + e.dispatchEvent(n); + } +} + +var getConstructor$1 = function (e) { + return null != e ? e.constructor : null; +}, + instanceOf$1 = function (e, t) { + return !!(e && t && e instanceof t); +}, + isNullOrUndefined$1 = function (e) { + return null == e; +}, + isObject$1 = function (e) { + return getConstructor$1(e) === Object; +}, + isNumber$1 = function (e) { + return getConstructor$1(e) === Number && !Number.isNaN(e); +}, + isString$1 = function (e) { + return getConstructor$1(e) === String; +}, + isBoolean$1 = function (e) { + return getConstructor$1(e) === Boolean; +}, + isFunction$1 = function (e) { + return getConstructor$1(e) === Function; +}, + isArray$1 = function (e) { + return Array.isArray(e); +}, + isNodeList$1 = function (e) { + return instanceOf$1(e, NodeList); +}, + isElement$1 = function (e) { + return instanceOf$1(e, Element); +}, + isEvent$1 = function (e) { + return instanceOf$1(e, Event); +}, + isEmpty$1 = function (e) { + return isNullOrUndefined$1(e) || (isString$1(e) || isArray$1(e) || isNodeList$1(e)) && !e.length || isObject$1(e) && !Object.keys(e).length; +}, + is$1 = { + nullOrUndefined: isNullOrUndefined$1, + object: isObject$1, + number: isNumber$1, + string: isString$1, + boolean: isBoolean$1, + function: isFunction$1, + array: isArray$1, + nodeList: isNodeList$1, + element: isElement$1, + event: isEvent$1, + empty: isEmpty$1 +}; + +function getDecimalPlaces(e) { + var t = "".concat(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); + return t ? Math.max(0, (t[1] ? t[1].length : 0) - (t[2] ? +t[2] : 0)) : 0; +} + +function round(e, t) { + if (1 > t) { + var n = getDecimalPlaces(t); + return parseFloat(e.toFixed(n)); + } + + return Math.round(e / t) * t; +} + +var RangeTouch = function () { + function e(t, n) { + _classCallCheck(this, e), is$1.element(t) ? this.element = t : is$1.string(t) && (this.element = document.querySelector(t)), is$1.element(this.element) && is$1.empty(this.element.rangeTouch) && (this.config = _objectSpread2({}, defaults$1, {}, n), this.init()); + } + + return _createClass(e, [{ + key: "init", + value: function () { + e.enabled && (this.config.addCSS && (this.element.style.userSelect = "none", this.element.style.webKitUserSelect = "none", this.element.style.touchAction = "manipulation"), this.listeners(!0), this.element.rangeTouch = this); + } + }, { + key: "destroy", + value: function () { + e.enabled && (this.config.addCSS && (this.element.style.userSelect = "", this.element.style.webKitUserSelect = "", this.element.style.touchAction = ""), this.listeners(!1), this.element.rangeTouch = null); + } + }, { + key: "listeners", + value: function (e) { + var t = this, + n = e ? "addEventListener" : "removeEventListener"; + ["touchstart", "touchmove", "touchend"].forEach(function (e) { + t.element[n](e, function (e) { + return t.set(e); + }, !1); + }); + } + }, { + key: "get", + value: function (t) { + if (!e.enabled || !is$1.event(t)) return null; + var n, + r = t.target, + i = t.changedTouches[0], + o = parseFloat(r.getAttribute("min")) || 0, + s = parseFloat(r.getAttribute("max")) || 100, + u = parseFloat(r.getAttribute("step")) || 1, + c = r.getBoundingClientRect(), + a = 100 / c.width * (this.config.thumbWidth / 2) / 100; + return 0 > (n = 100 / c.width * (i.clientX - c.left)) ? n = 0 : 100 < n && (n = 100), 50 > n ? n -= (100 - 2 * n) * a : 50 < n && (n += 2 * (n - 50) * a), o + round(n / 100 * (s - o), u); + } + }, { + key: "set", + value: function (t) { + e.enabled && is$1.event(t) && !t.target.disabled && (t.preventDefault(), t.target.value = this.get(t), trigger(t.target, "touchend" === t.type ? "change" : "input")); + } + }], [{ + key: "setup", + value: function (t) { + var n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}, + r = null; + if (is$1.empty(t) || is$1.string(t) ? r = Array.from(document.querySelectorAll(is$1.string(t) ? t : 'input[type="range"]')) : is$1.element(t) ? r = [t] : is$1.nodeList(t) ? r = Array.from(t) : is$1.array(t) && (r = t.filter(is$1.element)), is$1.empty(r)) return null; + + var i = _objectSpread2({}, defaults$1, {}, n); + + if (is$1.string(t) && i.watch) { + var o = new MutationObserver(function (n) { + Array.from(n).forEach(function (n) { + Array.from(n.addedNodes).forEach(function (n) { + is$1.element(n) && matches$1(n, t) && new e(n, i); + }); + }); + }); + o.observe(document.body, { + childList: !0, + subtree: !0 + }); + } + + return r.map(function (t) { + return new e(t, n); + }); + } + }, { + key: "enabled", + get: function () { + return "ontouchstart" in document.documentElement; + } + }]), e; +}(); + +// ========================================================================== +// Type checking utils +// ========================================================================== +const getConstructor = input => input !== null && typeof input !== 'undefined' ? input.constructor : null; + +const instanceOf = (input, constructor) => Boolean(input && constructor && input instanceof constructor); + +const isNullOrUndefined = input => input === null || typeof input === 'undefined'; + +const isObject = input => getConstructor(input) === Object; + +const isNumber = input => getConstructor(input) === Number && !Number.isNaN(input); + +const isString = input => getConstructor(input) === String; + +const isBoolean = input => getConstructor(input) === Boolean; + +const isFunction = input => getConstructor(input) === Function; + +const isArray = input => Array.isArray(input); + +const isWeakMap = input => instanceOf(input, WeakMap); + +const isNodeList = input => instanceOf(input, NodeList); + +const isTextNode = input => getConstructor(input) === Text; + +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) && isFunction(input.then); + +const isElement = input => input !== null && typeof input === 'object' && input.nodeType === 1 && typeof input.style === 'object' && typeof input.ownerDocument === 'object'; + +const isEmpty = input => isNullOrUndefined(input) || (isString(input) || isArray(input) || isNodeList(input)) && !input.length || isObject(input) && !Object.keys(input).length; + +const isUrl = input => { + // Accept a URL object + if (instanceOf(input, window.URL)) { + return true; + } // Must be string from here + + + if (!isString(input)) { + return false; + } // Add the protocol if required + + + let string = input; + + if (!input.startsWith('http://') || !input.startsWith('https://')) { + string = `http://${input}`; + } + + try { + return !isEmpty(new URL(string).hostname); + } catch (_) { + return false; + } +}; + +var is = { + nullOrUndefined: isNullOrUndefined, + object: isObject, + number: isNumber, + string: isString, + boolean: isBoolean, + function: isFunction, + array: isArray, + weakMap: isWeakMap, + nodeList: isNodeList, + element: isElement, + textNode: isTextNode, + event: isEvent, + keyboardEvent: isKeyboardEvent, + cue: isCue, + track: isTrack, + promise: isPromise, + url: isUrl, + empty: isEmpty +}; + +// ========================================================================== +const transitionEndEvent = (() => { + const element = document.createElement('span'); + const events = { + WebkitTransition: 'webkitTransitionEnd', + MozTransition: 'transitionend', + OTransition: 'oTransitionEnd otransitionend', + transition: 'transitionend' + }; + const type = Object.keys(events).find(event => element.style[event] !== undefined); + return is.string(type) ? events[type] : false; +})(); // Force repaint of element + +function repaint(element, delay) { + setTimeout(() => { + try { + // eslint-disable-next-line no-param-reassign + element.hidden = true; // eslint-disable-next-line no-unused-expressions + + element.offsetHeight; // eslint-disable-next-line no-param-reassign + + element.hidden = false; + } catch (_) {// Do nothing + } + }, delay); +} + +// ========================================================================== +// Browser sniffing +// Unfortunately, due to mixed support, UA sniffing is required +// ========================================================================== +const browser = { + isIE: Boolean(window.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: navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 || /(iPad|iPhone|iPod)/gi.test(navigator.platform) +}; + +// ========================================================================== + +function cloneDeep(object) { + return JSON.parse(JSON.stringify(object)); +} // Get a nested value in an object + +function getDeep(object, path) { + return path.split('.').reduce((obj, key) => obj && obj[key], object); +} // Deep extend destination object with N more objects + +function extend(target = {}, ...sources) { + if (!sources.length) { + return target; + } + + const source = sources.shift(); + + if (!is.object(source)) { + return target; + } + + Object.keys(source).forEach(key => { + if (is.object(source[key])) { + if (!Object.keys(target).includes(key)) { + Object.assign(target, { + [key]: {} + }); + } + + extend(target[key], source[key]); + } else { + Object.assign(target, { + [key]: source[key] + }); + } + }); + return extend(target, ...sources); +} + +// ========================================================================== + +function wrap(elements, wrapper) { + // Convert `elements` to an array, if necessary. + const targets = elements.length ? elements : [elements]; // Loops backwards to prevent having to clone the wrapper on the + // first element (see `child` below). + + Array.from(targets).reverse().forEach((element, index) => { + const child = index > 0 ? wrapper.cloneNode(true) : wrapper; // Cache the current parent and sibling. + + const parent = element.parentNode; + const sibling = element.nextSibling; // Wrap the element (is automatically removed from its current + // parent). + + child.appendChild(element); // If the element had a sibling, insert the wrapper before + // the sibling to maintain the HTML structure; otherwise, just + // append it to the parent. + + if (sibling) { + parent.insertBefore(child, sibling); + } else { + parent.appendChild(child); + } + }); +} // Set attributes + +function setAttributes(element, attributes) { + if (!is.element(element) || is.empty(attributes)) { + return; + } // Assume null and undefined attributes should be left out, + // Setting them would otherwise convert them to "null" and "undefined" + + + Object.entries(attributes).filter(([, value]) => !is.nullOrUndefined(value)).forEach(([key, value]) => element.setAttribute(key, value)); +} // Create a DocumentFragment + +function createElement(type, attributes, text) { + // Create a new <element> + const element = document.createElement(type); // Set all passed attributes + + if (is.object(attributes)) { + setAttributes(element, attributes); + } // Add text node + + + if (is.string(text)) { + element.innerText = text; + } // Return built element + + + return element; +} // Inaert an element after another + +function insertAfter(element, target) { + if (!is.element(element) || !is.element(target)) { + return; + } + + target.parentNode.insertBefore(element, target.nextSibling); +} // Insert a DocumentFragment + +function insertElement(type, parent, attributes, text) { + if (!is.element(parent)) { + return; + } + + parent.appendChild(createElement(type, attributes, text)); +} // Remove element(s) + +function removeElement(element) { + if (is.nodeList(element) || is.array(element)) { + Array.from(element).forEach(removeElement); + return; + } + + if (!is.element(element) || !is.element(element.parentNode)) { + return; + } + + element.parentNode.removeChild(element); +} // Remove all child elements + +function emptyElement(element) { + if (!is.element(element)) { + return; + } + + let { + length + } = element.childNodes; + + while (length > 0) { + element.removeChild(element.lastChild); + length -= 1; + } +} // Replace element + +function replaceElement(newChild, oldChild) { + if (!is.element(oldChild) || !is.element(oldChild.parentNode) || !is.element(newChild)) { + return null; + } + + oldChild.parentNode.replaceChild(newChild, oldChild); + return newChild; +} // Get an attribute object from a string selector + +function getAttributesFromSelector(sel, existingAttributes) { + // For example: + // '.test' to { class: 'test' } + // '#test' to { id: 'test' } + // '[data-test="test"]' to { 'data-test': 'test' } + if (!is.string(sel) || is.empty(sel)) { + return {}; + } + + const attributes = {}; + const existing = extend({}, existingAttributes); + sel.split(',').forEach(s => { + // Remove whitespace + const selector = s.trim(); + const className = selector.replace('.', ''); + const stripped = selector.replace(/[[\]]/g, ''); // Get the parts and value + + const parts = stripped.split('='); + const [key] = parts; + const value = parts.length > 1 ? parts[1].replace(/["']/g, '') : ''; // Get the first character + + const start = selector.charAt(0); + + switch (start) { + case '.': + // Add to existing classname + if (is.string(existing.class)) { + attributes.class = `${existing.class} ${className}`; + } else { + attributes.class = className; + } + + break; + + case '#': + // ID selector + attributes.id = selector.replace('#', ''); + break; + + case '[': + // Attribute selector + attributes[key] = value; + break; + } + }); + return extend(existing, attributes); +} // Toggle hidden + +function toggleHidden(element, hidden) { + if (!is.element(element)) { + return; + } + + let hide = hidden; + + if (!is.boolean(hide)) { + hide = !element.hidden; + } // eslint-disable-next-line no-param-reassign + + + element.hidden = hide; +} // Mirror Element.classList.toggle, with IE compatibility for "force" argument + +function toggleClass(element, className, force) { + if (is.nodeList(element)) { + return Array.from(element).map(e => toggleClass(e, className, force)); + } + + if (is.element(element)) { + let method = 'toggle'; + + if (typeof force !== 'undefined') { + method = force ? 'add' : 'remove'; + } + + element.classList[method](className); + return element.classList.contains(className); + } + + return false; +} // Has class name + +function hasClass(element, className) { + return is.element(element) && element.classList.contains(className); +} // Element matches selector + +function matches(element, selector) { + const { + prototype + } = Element; + + function match() { + return Array.from(document.querySelectorAll(selector)).includes(this); + } + + const method = prototype.matches || prototype.webkitMatchesSelector || prototype.mozMatchesSelector || prototype.msMatchesSelector || match; + return method.call(element, selector); +} // Closest ancestor element matching selector (also tests element itself) + +function closest$1(element, selector) { + const { + prototype + } = Element; // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill + + function closestElement() { + let el = this; + + do { + if (matches.matches(el, selector)) return el; + el = el.parentElement || el.parentNode; + } while (el !== null && el.nodeType === 1); + + return null; + } + + const method = prototype.closest || closestElement; + return method.call(element, selector); +} // Find all elements + +function getElements(selector) { + return this.elements.container.querySelectorAll(selector); +} // Find a single element + +function getElement(selector) { + return this.elements.container.querySelector(selector); +} // Set focus and tab focus class + +function setFocus(element = null, tabFocus = false) { + if (!is.element(element)) { + return; + } // Set regular focus + + + element.focus({ + preventScroll: true + }); // If we want to mimic keyboard focus via tab + + if (tabFocus) { + toggleClass(element, this.config.classNames.tabFocus); + } +} + +// ========================================================================== + +const defaultCodecs = { + 'audio/ogg': 'vorbis', + 'audio/wav': '1', + 'video/webm': 'vp8, vorbis', + 'video/mp4': 'avc1.42E01E, mp4a.40.2', + 'video/ogg': 'theora' +}; // Check for feature support + +const support = { + // Basic support + audio: 'canPlayType' in document.createElement('audio'), + video: 'canPlayType' in document.createElement('video'), + + // Check for support + // Basic functionality vs full UI + check(type, provider, playsinline) { + const canPlayInline = browser.isIPhone && playsinline && support.playsinline; + const api = support[type] || provider !== 'html5'; + const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline); + return { + api, + ui + }; + }, + + // Picture-in-picture support + // Safari & Chrome only currently + pip: (() => { + if (browser.isIPhone) { + return false; + } // Safari + // https://developer.apple.com/documentation/webkitjs/adding_picture_in_picture_to_your_safari_media_controls + + + if (is.function(createElement('video').webkitSetPresentationMode)) { + return true; + } // Chrome + // https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture + + + if (document.pictureInPictureEnabled && !createElement('video').disablePictureInPicture) { + return true; + } + + return false; + })(), + // Airplay support + // Safari only currently + airplay: is.function(window.WebKitPlaybackTargetAvailabilityEvent), + // Inline playback support + // https://webkit.org/blog/6784/new-video-policies-for-ios/ + playsinline: 'playsInline' in document.createElement('video'), + + // Check for mime type support against a player instance + // Credits: http://diveintohtml5.info/everything.html + // Related: http://www.leanbackplayer.com/test/h5mt.html + 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) { + return false; + } // Add codec if required + + + if (Object.keys(defaultCodecs).includes(type)) { + type += `; codecs="${defaultCodecs[input]}"`; + } + + try { + return Boolean(type && this.media.canPlayType(type).replace(/no/, '')); + } catch (_) { + return false; + } + }, + + // Check for textTracks support + textTracks: 'textTracks' in document.createElement('video'), + // <input type="range"> Sliders + rangeInput: (() => { + const range = document.createElement('input'); + range.type = 'range'; + return range.type === 'range'; + })(), + // Touch + // NOTE: Remember a device can be mouse + touch enabled so we check on first touch event + touch: 'ontouchstart' in document.documentElement, + // Detect transitions support + transitions: transitionEndEvent !== false, + // Reduced motion iOS & MacOS setting + // https://webkit.org/blog/7551/responsive-design-for-motion/ + reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches +}; + +// ========================================================================== +// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md +// https://www.youtube.com/watch?v=NPM6172J22g + +const supportsPassiveListeners = (() => { + // Test via a getter in the options object to see if the passive property is accessed + let supported = false; + + try { + const options = Object.defineProperty({}, 'passive', { + get() { + supported = true; + return null; + } + + }); + window.addEventListener('test', null, options); + window.removeEventListener('test', null, options); + } catch (_) {// Do nothing + } + + return supported; +})(); // Toggle event listener + + +function toggleListener(element, event, callback, toggle = false, passive = true, capture = false) { + // Bail if no element, event, or callback + if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) { + return; + } // Allow multiple events + + + const events = event.split(' '); // Build options + // Default to just the capture boolean for browsers with no passive listener support + + let options = capture; // If passive events listeners are supported + + if (supportsPassiveListeners) { + options = { + // Whether the listener can be passive (i.e. default never prevented) + passive, + // Whether the listener is a capturing listener or not + capture + }; + } // If a single node is passed, bind the event listener + + + events.forEach(type => { + if (this && this.eventListeners && toggle) { + // Cache event listener + this.eventListeners.push({ + element, + type, + callback, + options + }); + } + + element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options); + }); +} // Bind event handler + +function on(element, events = '', callback, passive = true, capture = false) { + toggleListener.call(this, element, events, callback, true, passive, capture); +} // Unbind event handler + +function off(element, events = '', callback, passive = true, capture = false) { + toggleListener.call(this, element, events, callback, false, passive, capture); +} // Bind once-only event handler + +function once(element, events = '', callback, passive = true, capture = false) { + const onceCallback = (...args) => { + off(element, events, onceCallback, passive, capture); + callback.apply(this, args); + }; + + toggleListener.call(this, element, events, onceCallback, true, passive, capture); +} // Trigger event + +function triggerEvent(element, type = '', bubbles = false, detail = {}) { + // Bail if no element + if (!is.element(element) || is.empty(type)) { + return; + } // Create and dispatch the event + + + const event = new CustomEvent(type, { + bubbles, + detail: { ...detail, + plyr: this + } + }); // Dispatch the event + + element.dispatchEvent(event); +} // Unbind all cached event listeners + +function unbindListeners() { + if (this && this.eventListeners) { + this.eventListeners.forEach(item => { + const { + element, + type, + callback, + options + } = item; + element.removeEventListener(type, callback, options); + }); + this.eventListeners = []; + } +} // Run method when / if player is ready + +function ready() { + return new Promise(resolve => this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve)).then(() => {}); +} + +/** + * Silence a Promise-like object. + * This is useful for avoiding non-harmful, but potentially confusing "uncaught + * play promise" rejection error messages. + * @param {Object} value An object that may or may not be `Promise`-like. + */ + +function silencePromise(value) { + if (is.promise(value)) { + value.then(null, () => {}); + } +} + +// ========================================================================== + +function dedupe(array) { + if (!is.array(array)) { + return array; + } + + return array.filter((item, index) => array.indexOf(item) === index); +} // Get the closest value in an array + +function closest(array, value) { + if (!is.array(array) || !array.length) { + return null; + } + + return array.reduce((prev, curr) => Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev); +} + +// ========================================================================== + +function supportsCSS(declaration) { + if (!window || !window.CSS) { + return false; + } + + return window.CSS.supports(declaration); +} // Standard/common aspect ratios + +const standardRatios = [[1, 1], [4, 3], [3, 4], [5, 4], [4, 5], [3, 2], [2, 3], [16, 10], [10, 16], [16, 9], [9, 16], [21, 9], [9, 21], [32, 9], [9, 32]].reduce((out, [x, y]) => ({ ...out, + [x / y]: [x, y] +}), {}); // Validate an aspect ratio + +function validateAspectRatio(input) { + if (!is.array(input) && (!is.string(input) || !input.includes(':'))) { + return false; + } + + const ratio = is.array(input) ? input : input.split(':'); + return ratio.map(Number).every(is.number); +} // Reduce an aspect ratio to it's lowest form + +function reduceAspectRatio(ratio) { + if (!is.array(ratio) || !ratio.every(is.number)) { + return null; + } + + const [width, height] = ratio; + + const getDivider = (w, h) => h === 0 ? w : getDivider(h, w % h); + + const divider = getDivider(width, height); + return [width / divider, height / divider]; +} // Calculate an aspect ratio + +function getAspectRatio(input) { + const parse = ratio => validateAspectRatio(ratio) ? ratio.split(':').map(Number) : null; // Try provided ratio + + + let ratio = parse(input); // Get from config + + if (ratio === null) { + ratio = parse(this.config.ratio); + } // Get from embed + + + if (ratio === null && !is.empty(this.embed) && is.array(this.embed.ratio)) { + ({ + ratio + } = this.embed); + } // Get from HTML5 video + + + if (ratio === null && this.isHTML5) { + const { + videoWidth, + videoHeight + } = this.media; + ratio = [videoWidth, videoHeight]; + } + + return reduceAspectRatio(ratio); +} // Set aspect ratio for responsive container + +function setAspectRatio(input) { + if (!this.isVideo) { + return {}; + } + + const { + wrapper + } = this.elements; + const ratio = getAspectRatio.call(this, input); + + if (!is.array(ratio)) { + return {}; + } + + const [x, y] = reduceAspectRatio(ratio); + const useNative = supportsCSS(`aspect-ratio: ${x}/${y}`); + const padding = 100 / x * y; + + if (useNative) { + wrapper.style.aspectRatio = `${x}/${y}`; + } else { + wrapper.style.paddingBottom = `${padding}%`; + } // For Vimeo we have an extra <div> to hide the standard controls and UI + + + if (this.isVimeo && !this.config.vimeo.premium && this.supported.ui) { + const height = 100 / this.media.offsetWidth * parseInt(window.getComputedStyle(this.media).paddingBottom, 10); + const offset = (height - padding) / (height / 50); + + if (this.fullscreen.active) { + wrapper.style.paddingBottom = null; + } else { + this.media.style.transform = `translateY(-${offset}%)`; + } + } else if (this.isHTML5) { + wrapper.classList.add(this.config.classNames.videoFixedRatio); + } + + return { + padding, + ratio + }; +} // Round an aspect ratio to closest standard ratio + +function roundAspectRatio(x, y, tolerance = 0.05) { + const ratio = x / y; + const closestRatio = closest(Object.keys(standardRatios), ratio); // Check match is within tolerance + + if (Math.abs(closestRatio - ratio) <= tolerance) { + return standardRatios[closestRatio]; + } // No match + + + return [x, y]; +} // Get the size of the viewport +// https://stackoverflow.com/questions/1248081/how-to-get-the-browser-viewport-dimensions + +function getViewportSize() { + const width = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0); + const height = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0); + return [width, height]; +} + +// ========================================================================== +const html5 = { + getSources() { + if (!this.isHTML5) { + return []; + } + + const sources = Array.from(this.media.querySelectorAll('source')); // 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 + getQualityOptions() { + // Whether we're forcing all options (e.g. for streaming) + if (this.config.quality.forced) { + return this.config.quality.options; + } // Get sizes from <source> elements + + + return html5.getSources.call(this).map(source => Number(source.getAttribute('data-res'))).filter(Boolean); + }, + + setup() { + if (!this.isHTML5) { + return; + } + + const player = this; // Set speed options from config + + player.options.speed = player.config.speed.options; // Set aspect ratio if fixed + + if (!is.empty(this.config.ratio)) { + setAspectRatio.call(player); + } // Quality + + + Object.defineProperty(player.media, 'quality', { + get() { + // Get sources + const sources = html5.getSources.call(player); + const source = sources.find(s => s.getAttribute('src') === player.source); // Return size, if match is found + + return source && Number(source.getAttribute('data-res')); + }, + + set(input) { + if (player.quality === input) { + return; + } // If we're using an external handler... + + + if (player.config.quality.forced && is.function(player.config.quality.onChange)) { + player.config.quality.onChange(input); + } else { + // Get sources + const sources = html5.getSources.call(player); // Get first match for requested size + + const source = sources.find(s => Number(s.getAttribute('data-res')) === input); // No matching source found + + if (!source) { + return; + } // Get current state + + + const { + currentTime, + paused, + preload, + readyState, + playbackRate + } = player.media; // Set new source + + player.media.src = source.getAttribute('src'); // Prevent loading if preload="none" and the current source isn't loaded (#1044) + + if (preload !== 'none' || readyState) { + // Restore time + player.once('loadedmetadata', () => { + player.speed = playbackRate; + player.currentTime = currentTime; // Resume playing + + if (!paused) { + silencePromise(player.play()); + } + }); // Load new source + + player.media.load(); + } + } // Trigger change event + + + triggerEvent.call(player, player.media, 'qualitychange', false, { + quality: input + }); + } + + }); + }, + + // Cancel current network requests + // See https://github.com/sampotts/plyr/issues/174 + cancelRequests() { + if (!this.isHTML5) { + return; + } // Remove child sources + + + removeElement(html5.getSources.call(this)); // Set blank video src attribute + // This is to prevent a MEDIA_ERR_SRC_NOT_SUPPORTED error + // Info: http://stackoverflow.com/questions/32231579/how-to-properly-dispose-of-an-html5-video-and-close-socket-or-connection + + this.media.setAttribute('src', this.config.blankVideo); // Load the new empty source + // This will cancel existing requests + // See https://github.com/sampotts/plyr/issues/174 + + this.media.load(); // Debugging + + this.debug.log('Cancelled network requests'); + } + +}; + +// ========================================================================== + +function generateId(prefix) { + return `${prefix}-${Math.floor(Math.random() * 10000)}`; +} // Format string + +function format(input, ...args) { + if (is.empty(input)) { + return input; + } + + return input.toString().replace(/{(\d+)}/g, (match, i) => args[i].toString()); +} // Get percentage + +function getPercentage(current, max) { + if (current === 0 || max === 0 || Number.isNaN(current) || Number.isNaN(max)) { + return 0; + } + + return (current / max * 100).toFixed(2); +} // Replace all occurances of a string in a string + +const replaceAll = (input = '', find = '', replace = '') => input.replace(new RegExp(find.toString().replace(/([.*+?^=!:${}()|[\]/\\])/g, '\\$1'), 'g'), replace.toString()); // Convert to title case + +const toTitleCase = (input = '') => input.toString().replace(/\w\S*/g, text => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()); // Convert string to pascalCase + +function toPascalCase(input = '') { + let string = input.toString(); // Convert kebab case + + string = replaceAll(string, '-', ' '); // Convert snake case + + string = replaceAll(string, '_', ' '); // Convert to title case + + string = toTitleCase(string); // Convert to pascal case + + return replaceAll(string, ' ', ''); +} // Convert string to pascalCase + +function toCamelCase(input = '') { + let string = input.toString(); // Convert to pascal case + + string = toPascalCase(string); // Convert first character to lowercase + + return string.charAt(0).toLowerCase() + string.slice(1); +} // Remove HTML from a string + +function stripHTML(source) { + const fragment = document.createDocumentFragment(); + const element = document.createElement('div'); + fragment.appendChild(element); + element.innerHTML = source; + return fragment.firstChild.innerText; +} // Like outerHTML, but also works for DocumentFragment + +function getHTML(element) { + const wrapper = document.createElement('div'); + wrapper.appendChild(element); + return wrapper.innerHTML; +} + +// ========================================================================== + +const resources = { + pip: 'PIP', + airplay: 'AirPlay', + html5: 'HTML5', + vimeo: 'Vimeo', + youtube: 'YouTube' +}; +const i18n = { + get(key = '', config = {}) { + if (is.empty(key) || is.empty(config)) { + return ''; + } + + let string = getDeep(config.i18n, key); + + if (is.empty(string)) { + if (Object.keys(resources).includes(key)) { + return resources[key]; + } + + return ''; + } + + const replace = { + '{seektime}': config.seekTime, + '{title}': config.title + }; + Object.entries(replace).forEach(([k, v]) => { + string = replaceAll(string, k, v); + }); + return string; + } + +}; + +class Storage { + constructor(player) { + _defineProperty$1(this, "get", key => { + if (!Storage.supported || !this.enabled) { + return null; + } + + const store = window.localStorage.getItem(this.key); + + if (is.empty(store)) { + return null; + } + + const json = JSON.parse(store); + return is.string(key) && key.length ? json[key] : json; + }); + + _defineProperty$1(this, "set", object => { + // Bail if we don't have localStorage support or it's disabled + if (!Storage.supported || !this.enabled) { + return; + } // Can only store objectst + + + if (!is.object(object)) { + return; + } // Get current storage + + + let storage = this.get(); // Default to empty object + + if (is.empty(storage)) { + storage = {}; + } // Update the working copy of the values + + + extend(storage, object); // Update storage + + try { + window.localStorage.setItem(this.key, JSON.stringify(storage)); + } catch (_) {// Do nothing + } + }); + + this.enabled = player.config.storage.enabled; + this.key = player.config.storage.key; + } // Check for actual support (see if we can use it) + + + static get supported() { + try { + if (!('localStorage' in window)) { + return false; + } + + const test = '___test'; // Try to use it (it might be disabled, e.g. user is in private mode) + // see: https://github.com/sampotts/plyr/issues/131 + + window.localStorage.setItem(test, test); + window.localStorage.removeItem(test); + return true; + } catch (_) { + return false; + } + } + +} + +// ========================================================================== +// Fetch wrapper +// Using XHR to avoid issues with older browsers +// ========================================================================== +function fetch(url, responseType = 'text') { + return new Promise((resolve, reject) => { + try { + const request = new XMLHttpRequest(); // Check for CORS support + + if (!('withCredentials' in request)) { + return; + } + + request.addEventListener('load', () => { + if (responseType === 'text') { + try { + resolve(JSON.parse(request.responseText)); + } catch (_) { + resolve(request.responseText); + } + } else { + resolve(request.response); + } + }); + request.addEventListener('error', () => { + throw new Error(request.status); + }); + request.open('GET', url, true); // Set the required response type + + request.responseType = responseType; + request.send(); + } catch (error) { + reject(error); + } + }); +} + +// ========================================================================== + +function loadSprite(url, id) { + if (!is.string(url)) { + return; + } + + const prefix = 'cache'; + const hasId = is.string(id); + let isCached = false; + + const exists = () => document.getElementById(id) !== null; + + const update = (container, data) => { + // eslint-disable-next-line no-param-reassign + container.innerHTML = data; // Check again incase of race condition + + if (hasId && exists()) { + return; + } // Inject the SVG to the body + + + document.body.insertAdjacentElement('afterbegin', container); + }; // Only load once if ID set + + + if (!hasId || !exists()) { + const useStorage = Storage.supported; // Create container + + const container = document.createElement('div'); + container.setAttribute('hidden', ''); + + if (hasId) { + container.setAttribute('id', id); + } // Check in cache + + + if (useStorage) { + const cached = window.localStorage.getItem(`${prefix}-${id}`); + isCached = cached !== null; + + if (isCached) { + const data = JSON.parse(cached); + update(container, data.content); + } + } // Get the sprite + + + fetch(url).then(result => { + if (is.empty(result)) { + return; + } + + if (useStorage) { + try { + window.localStorage.setItem(`${prefix}-${id}`, JSON.stringify({ + content: result + })); + } catch (_) {// Do nothing + } + } + + update(container, result); + }).catch(() => {}); + } +} + +// ========================================================================== + +const getHours = value => Math.trunc(value / 60 / 60 % 60, 10); +const getMinutes = value => Math.trunc(value / 60 % 60, 10); +const getSeconds = value => Math.trunc(value % 60, 10); // Format time to UI friendly string + +function formatTime(time = 0, displayHours = false, inverted = false) { + // Bail if the value isn't a number + if (!is.number(time)) { + return formatTime(undefined, displayHours, inverted); + } // Format time component to add leading zero + + + const format = value => `0${value}`.slice(-2); // Breakdown to hours, mins, secs + + + let hours = getHours(time); + const mins = getMinutes(time); + const secs = getSeconds(time); // Do we need to display hours? + + if (displayHours || hours > 0) { + hours = `${hours}:`; + } else { + hours = ''; + } // Render + + + return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`; +} + +// ========================================================================== + +const controls = { + // Get icon URL + getIconUrl() { + const url = new URL(this.config.iconUrl, window.location); + const host = window.location.host ? window.location.host : window.top.location.host; + const cors = url.host !== host || browser.isIE && !window.svg4everybody; + return { + url: this.config.iconUrl, + cors + }; + }, + + // Find the UI controls + findElements() { + try { + this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper); // Buttons + + this.elements.buttons = { + play: getElements.call(this, this.config.selectors.buttons.play), + pause: getElement.call(this, this.config.selectors.buttons.pause), + restart: getElement.call(this, this.config.selectors.buttons.restart), + rewind: getElement.call(this, this.config.selectors.buttons.rewind), + fastForward: getElement.call(this, this.config.selectors.buttons.fastForward), + mute: getElement.call(this, this.config.selectors.buttons.mute), + pip: getElement.call(this, this.config.selectors.buttons.pip), + airplay: getElement.call(this, this.config.selectors.buttons.airplay), + settings: getElement.call(this, this.config.selectors.buttons.settings), + captions: getElement.call(this, this.config.selectors.buttons.captions), + fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen) + }; // Progress + + this.elements.progress = getElement.call(this, this.config.selectors.progress); // Inputs + + this.elements.inputs = { + seek: getElement.call(this, this.config.selectors.inputs.seek), + volume: getElement.call(this, this.config.selectors.inputs.volume) + }; // Display + + this.elements.display = { + buffer: getElement.call(this, this.config.selectors.display.buffer), + currentTime: getElement.call(this, this.config.selectors.display.currentTime), + duration: getElement.call(this, this.config.selectors.display.duration) + }; // Seek tooltip + + if (is.element(this.elements.progress)) { + this.elements.display.seekTooltip = this.elements.progress.querySelector(`.${this.config.classNames.tooltip}`); + } + + return true; + } catch (error) { + // Log it + this.debug.warn('It looks like there is a problem with your custom controls HTML', error); // Restore native video controls + + this.toggleNativeControls(true); + return false; + } + }, + + // Create <svg> icon + createIcon(type, attributes) { + const namespace = 'http://www.w3.org/2000/svg'; + const iconUrl = controls.getIconUrl.call(this); + const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`; // Create <svg> + + const icon = document.createElementNS(namespace, 'svg'); + setAttributes(icon, extend(attributes, { + 'aria-hidden': 'true', + focusable: 'false' + })); // Create the <use> to reference sprite + + const use = document.createElementNS(namespace, 'use'); + const path = `${iconPath}-${type}`; // Set `href` attributes + // https://github.com/sampotts/plyr/issues/460 + // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href + + if ('href' in use) { + use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path); + } // Always set the older attribute even though it's "deprecated" (it'll be around for ages) + + + use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path); // Add <use> to <svg> + + icon.appendChild(use); + return icon; + }, + + // Create hidden text label + createLabel(key, attr = {}) { + const text = i18n.get(key, this.config); + const attributes = { ...attr, + class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' ') + }; + return createElement('span', attributes, text); + }, + + // Create a badge + createBadge(text) { + if (is.empty(text)) { + return null; + } + + const badge = createElement('span', { + class: this.config.classNames.menu.value + }); + badge.appendChild(createElement('span', { + class: this.config.classNames.menu.badge + }, text)); + return badge; + }, + + // Create a <button> + createButton(buttonType, attr) { + const attributes = extend({}, attr); + let type = toCamelCase(buttonType); + const props = { + element: 'button', + toggle: false, + label: null, + icon: null, + labelPressed: null, + iconPressed: null + }; + ['element', 'icon', 'label'].forEach(key => { + if (Object.keys(attributes).includes(key)) { + props[key] = attributes[key]; + delete attributes[key]; + } + }); // Default to 'button' type to prevent form submission + + if (props.element === 'button' && !Object.keys(attributes).includes('type')) { + attributes.type = 'button'; + } // Set class name + + + if (Object.keys(attributes).includes('class')) { + if (!attributes.class.split(' ').some(c => c === this.config.classNames.control)) { + extend(attributes, { + class: `${attributes.class} ${this.config.classNames.control}` + }); + } + } else { + attributes.class = this.config.classNames.control; + } // Large play button + + + switch (buttonType) { + case 'play': + props.toggle = true; + props.label = 'play'; + props.labelPressed = 'pause'; + props.icon = 'play'; + props.iconPressed = 'pause'; + break; + + case 'mute': + props.toggle = true; + props.label = 'mute'; + props.labelPressed = 'unmute'; + props.icon = 'volume'; + props.iconPressed = 'muted'; + break; + + case 'captions': + props.toggle = true; + props.label = 'enableCaptions'; + props.labelPressed = 'disableCaptions'; + props.icon = 'captions-off'; + props.iconPressed = 'captions-on'; + break; + + case 'fullscreen': + props.toggle = true; + props.label = 'enterFullscreen'; + props.labelPressed = 'exitFullscreen'; + props.icon = 'enter-fullscreen'; + props.iconPressed = 'exit-fullscreen'; + break; + + case 'play-large': + attributes.class += ` ${this.config.classNames.control}--overlaid`; + type = 'play'; + props.label = 'play'; + props.icon = 'play'; + break; + + default: + if (is.empty(props.label)) { + props.label = type; + } + + if (is.empty(props.icon)) { + props.icon = buttonType; + } + + } + + const button = createElement(props.element); // Setup toggle icon and labels + + if (props.toggle) { + // Icon + button.appendChild(controls.createIcon.call(this, props.iconPressed, { + class: 'icon--pressed' + })); + button.appendChild(controls.createIcon.call(this, props.icon, { + class: 'icon--not-pressed' + })); // Label/Tooltip + + button.appendChild(controls.createLabel.call(this, props.labelPressed, { + class: 'label--pressed' + })); + button.appendChild(controls.createLabel.call(this, props.label, { + class: 'label--not-pressed' + })); + } else { + button.appendChild(controls.createIcon.call(this, props.icon)); + button.appendChild(controls.createLabel.call(this, props.label)); + } // Merge and set attributes + + + extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes)); + setAttributes(button, attributes); // We have multiple play buttons + + if (type === 'play') { + if (!is.array(this.elements.buttons[type])) { + this.elements.buttons[type] = []; + } + + this.elements.buttons[type].push(button); + } else { + this.elements.buttons[type] = button; + } + + return button; + }, + + // Create an <input type='range'> + createRange(type, attributes) { + // Seek input + const input = createElement('input', extend(getAttributesFromSelector(this.config.selectors.inputs[type]), { + type: 'range', + min: 0, + max: 100, + step: 0.01, + value: 0, + autocomplete: 'off', + // A11y fixes for https://github.com/sampotts/plyr/issues/905 + role: 'slider', + 'aria-label': i18n.get(type, this.config), + 'aria-valuemin': 0, + 'aria-valuemax': 100, + 'aria-valuenow': 0 + }, attributes)); + this.elements.inputs[type] = input; // Set the fill for webkit now + + controls.updateRangeFill.call(this, input); // Improve support on touch devices + + RangeTouch.setup(input); + return input; + }, + + // Create a <progress> + createProgress(type, attributes) { + const progress = createElement('progress', extend(getAttributesFromSelector(this.config.selectors.display[type]), { + min: 0, + max: 100, + value: 0, + role: 'progressbar', + 'aria-hidden': true + }, attributes)); // Create the label inside + + if (type !== 'volume') { + progress.appendChild(createElement('span', null, '0')); + const suffixKey = { + played: 'played', + buffer: 'buffered' + }[type]; + const suffix = suffixKey ? i18n.get(suffixKey, this.config) : ''; + progress.innerText = `% ${suffix.toLowerCase()}`; + } + + this.elements.display[type] = progress; + return progress; + }, + + // Create time display + createTime(type, attrs) { + const attributes = getAttributesFromSelector(this.config.selectors.display[type], attrs); + const container = createElement('div', extend(attributes, { + class: `${attributes.class ? attributes.class : ''} ${this.config.classNames.display.time} `.trim(), + 'aria-label': i18n.get(type, this.config) + }), '00:00'); // Reference for updates + + this.elements.display[type] = container; + return container; + }, + + // Bind keyboard shortcuts for a menu item + // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus + // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143 + bindMenuItemShortcuts(menuItem, type) { + // Navigate through menus via arrow keys and space + on.call(this, menuItem, 'keydown keyup', event => { + // We only care about space and ⬆️ ⬇️️ ➡️ + if (![32, 38, 39, 40].includes(event.which)) { + return; + } // Prevent play / seek + + + event.preventDefault(); + event.stopPropagation(); // We're just here to prevent the keydown bubbling + + if (event.type === 'keydown') { + return; + } + + const isRadioButton = matches(menuItem, '[role="menuitemradio"]'); // Show the respective menu + + if (!isRadioButton && [32, 39].includes(event.which)) { + controls.showMenuPanel.call(this, type, true); + } else { + let target; + + if (event.which !== 32) { + if (event.which === 40 || isRadioButton && event.which === 39) { + target = menuItem.nextElementSibling; + + if (!is.element(target)) { + target = menuItem.parentNode.firstElementChild; + } + } else { + target = menuItem.previousElementSibling; + + if (!is.element(target)) { + target = menuItem.parentNode.lastElementChild; + } + } + + setFocus.call(this, target, true); + } + } + }, false); // Enter will fire a `click` event but we still need to manage focus + // So we bind to keyup which fires after and set focus here + + on.call(this, menuItem, 'keyup', event => { + if (event.which !== 13) { + return; + } + + controls.focusFirstMenuItem.call(this, null, true); + }); + }, + + // Create a settings menu item + createMenuItem({ + value, + list, + type, + title, + badge = null, + checked = false + }) { + const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]); + const menuItem = createElement('button', extend(attributes, { + type: 'button', + role: 'menuitemradio', + class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(), + 'aria-checked': checked, + value + })); + const flex = createElement('span'); // We have to set as HTML incase of special characters + + flex.innerHTML = title; + + if (is.element(badge)) { + flex.appendChild(badge); + } + + menuItem.appendChild(flex); // Replicate radio button behaviour + + Object.defineProperty(menuItem, 'checked', { + enumerable: true, + + get() { + return menuItem.getAttribute('aria-checked') === 'true'; + }, + + set(check) { + // Ensure exclusivity + if (check) { + Array.from(menuItem.parentNode.children).filter(node => matches(node, '[role="menuitemradio"]')).forEach(node => node.setAttribute('aria-checked', 'false')); + } + + menuItem.setAttribute('aria-checked', check ? 'true' : 'false'); + } + + }); + this.listeners.bind(menuItem, 'click keyup', event => { + if (is.keyboardEvent(event) && event.which !== 32) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + menuItem.checked = true; + + switch (type) { + case 'language': + this.currentTrack = Number(value); + break; + + case 'quality': + this.quality = value; + break; + + case 'speed': + this.speed = parseFloat(value); + break; + } + + controls.showMenuPanel.call(this, 'home', is.keyboardEvent(event)); + }, type, false); + controls.bindMenuItemShortcuts.call(this, menuItem, type); + list.appendChild(menuItem); + }, + + // Format a time for display + formatTime(time = 0, inverted = false) { + // Bail if the value isn't a number + if (!is.number(time)) { + return time; + } // Always display hours if duration is over an hour + + + const forceHours = getHours(this.duration) > 0; + return formatTime(time, forceHours, inverted); + }, + + // Update the displayed time + updateTimeDisplay(target = null, time = 0, inverted = false) { + // Bail if there's no element to display or the value isn't a number + if (!is.element(target) || !is.number(time)) { + return; + } // eslint-disable-next-line no-param-reassign + + + target.innerText = controls.formatTime(time, inverted); + }, + + // Update volume UI and storage + updateVolume() { + if (!this.supported.ui) { + return; + } // Update range + + + if (is.element(this.elements.inputs.volume)) { + controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume); + } // Update mute state + + + if (is.element(this.elements.buttons.mute)) { + this.elements.buttons.mute.pressed = this.muted || this.volume === 0; + } + }, + + // Update seek value and lower fill + setRange(target, value = 0) { + if (!is.element(target)) { + return; + } // eslint-disable-next-line + + + target.value = value; // Webkit range fill + + controls.updateRangeFill.call(this, target); + }, + + // Update <progress> elements + updateProgress(event) { + if (!this.supported.ui || !is.event(event)) { + return; + } + + let value = 0; + + const setProgress = (target, input) => { + const val = is.number(input) ? input : 0; + const progress = is.element(target) ? target : this.elements.display.buffer; // Update value and label + + if (is.element(progress)) { + progress.value = val; // Update text label inside + + const label = progress.getElementsByTagName('span')[0]; + + if (is.element(label)) { + label.childNodes[0].nodeValue = val; + } + } + }; + + if (event) { + switch (event.type) { + // Video playing + case 'timeupdate': + case 'seeking': + case 'seeked': + value = getPercentage(this.currentTime, this.duration); // Set seek range value only if it's a 'natural' time event + + if (event.type === 'timeupdate') { + controls.setRange.call(this, this.elements.inputs.seek, value); + } + + break; + // Check buffer status + + case 'playing': + case 'progress': + setProgress(this.elements.display.buffer, this.buffered * 100); + break; + } + } + }, + + // Webkit polyfill for lower fill range + updateRangeFill(target) { + // Get range from event if event passed + const range = is.event(target) ? target.target : target; // Needs to be a valid <input type='range'> + + if (!is.element(range) || range.getAttribute('type') !== 'range') { + return; + } // Set aria values for https://github.com/sampotts/plyr/issues/905 + + + if (matches(range, this.config.selectors.inputs.seek)) { + range.setAttribute('aria-valuenow', this.currentTime); + const currentTime = controls.formatTime(this.currentTime); + const duration = controls.formatTime(this.duration); + const format = i18n.get('seekLabel', this.config); + range.setAttribute('aria-valuetext', format.replace('{currentTime}', currentTime).replace('{duration}', duration)); + } else if (matches(range, this.config.selectors.inputs.volume)) { + const percent = range.value * 100; + range.setAttribute('aria-valuenow', percent); + range.setAttribute('aria-valuetext', `${percent.toFixed(1)}%`); + } else { + range.setAttribute('aria-valuenow', range.value); + } // WebKit only + + + if (!browser.isWebkit) { + return; + } // Set CSS custom property + + + range.style.setProperty('--value', `${range.value / range.max * 100}%`); + }, + + // Update hover tooltip for seeking + updateSeekTooltip(event) { + // Bail if setting not true + if (!this.config.tooltips.seek || !is.element(this.elements.inputs.seek) || !is.element(this.elements.display.seekTooltip) || this.duration === 0) { + return; + } + + const visible = `${this.config.classNames.tooltip}--visible`; + + const toggle = show => toggleClass(this.elements.display.seekTooltip, visible, show); // Hide on touch + + + if (this.touch) { + toggle(false); + return; + } // Determine percentage, if already visible + + + let percent = 0; + const clientRect = this.elements.progress.getBoundingClientRect(); + + if (is.event(event)) { + percent = 100 / clientRect.width * (event.pageX - clientRect.left); + } else if (hasClass(this.elements.display.seekTooltip, visible)) { + percent = parseFloat(this.elements.display.seekTooltip.style.left, 10); + } else { + return; + } // Set bounds + + + if (percent < 0) { + percent = 0; + } else if (percent > 100) { + percent = 100; + } // Display the time a click would seek to + + + controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent); // Set position + + this.elements.display.seekTooltip.style.left = `${percent}%`; // Show/hide the tooltip + // If the event is a moues in/out and percentage is inside bounds + + if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) { + toggle(event.type === 'mouseenter'); + } + }, + + // Handle time change event + timeUpdate(event) { + // Only invert if only one time element is displayed and used for both duration and currentTime + const invert = !is.element(this.elements.display.duration) && this.config.invertTime; // Duration + + controls.updateTimeDisplay.call(this, this.elements.display.currentTime, invert ? this.duration - this.currentTime : this.currentTime, invert); // Ignore updates while seeking + + if (event && event.type === 'timeupdate' && this.media.seeking) { + return; + } // Playing progress + + + controls.updateProgress.call(this, event); + }, + + // Show the duration on metadataloaded or durationchange events + durationUpdate() { + // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false + if (!this.supported.ui || !this.config.invertTime && this.currentTime) { + return; + } // If duration is the 2**32 (shaka), Infinity (HLS), DASH-IF (Number.MAX_SAFE_INTEGER || Number.MAX_VALUE) indicating live we hide the currentTime and progressbar. + // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415 + // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062 + // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338 + + + if (this.duration >= 2 ** 32) { + toggleHidden(this.elements.display.currentTime, true); + toggleHidden(this.elements.progress, true); + return; + } // Update ARIA values + + + if (is.element(this.elements.inputs.seek)) { + this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration); + } // If there's a spot to display duration + + + const hasDuration = is.element(this.elements.display.duration); // If there's only one time display, display duration there + + if (!hasDuration && this.config.displayDuration && this.paused) { + controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration); + } // If there's a duration element, update content + + + if (hasDuration) { + controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration); + } // Update the tooltip (if visible) + + + controls.updateSeekTooltip.call(this); + }, + + // Hide/show a tab + toggleMenuButton(setting, toggle) { + toggleHidden(this.elements.settings.buttons[setting], !toggle); + }, + + // Update the selected setting + updateSetting(setting, container, input) { + const pane = this.elements.settings.panels[setting]; + let value = null; + let list = container; + + if (setting === 'captions') { + value = this.currentTrack; + } else { + value = !is.empty(input) ? input : this[setting]; // Get default + + if (is.empty(value)) { + value = this.config[setting].default; + } // Unsupported value + + + if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) { + this.debug.warn(`Unsupported value of '${value}' for ${setting}`); + return; + } // Disabled value + + + if (!this.config[setting].options.includes(value)) { + this.debug.warn(`Disabled value of '${value}' for ${setting}`); + return; + } + } // Get the list if we need to + + + if (!is.element(list)) { + list = pane && pane.querySelector('[role="menu"]'); + } // If there's no list it means it's not been rendered... + + + if (!is.element(list)) { + return; + } // Update the label + + + const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`); + label.innerHTML = controls.getLabel.call(this, setting, value); // Find the radio option and check it + + const target = list && list.querySelector(`[value="${value}"]`); + + if (is.element(target)) { + target.checked = true; + } + }, + + // Translate a value into a nice label + getLabel(setting, value) { + switch (setting) { + case 'speed': + return value === 1 ? i18n.get('normal', this.config) : `${value}×`; + + case 'quality': + if (is.number(value)) { + const label = i18n.get(`qualityLabel.${value}`, this.config); + + if (!label.length) { + return `${value}p`; + } + + return label; + } + + return toTitleCase(value); + + case 'captions': + return captions.getLabel.call(this); + + default: + return null; + } + }, + + // Set the quality menu + setQualityMenu(options) { + // Menu required + if (!is.element(this.elements.settings.panels.quality)) { + return; + } + + const type = 'quality'; + const list = this.elements.settings.panels.quality.querySelector('[role="menu"]'); // Set options if passed and filter based on uniqueness and config + + if (is.array(options)) { + this.options.quality = dedupe(options).filter(quality => this.config.quality.options.includes(quality)); + } // Toggle the pane and tab + + + const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1; + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If we're hiding, nothing more to do + + if (!toggle) { + return; + } // Get the badge HTML for HD, 4K etc + + + const getBadge = quality => { + const label = i18n.get(`qualityBadge.${quality}`, this.config); + + if (!label.length) { + return null; + } + + return controls.createBadge.call(this, label); + }; // Sort options by the config and then render options + + + this.options.quality.sort((a, b) => { + const sorting = this.config.quality.options; + return sorting.indexOf(a) > sorting.indexOf(b) ? 1 : -1; + }).forEach(quality => { + controls.createMenuItem.call(this, { + value: quality, + list, + type, + title: controls.getLabel.call(this, 'quality', quality), + badge: getBadge(quality) + }); + }); + controls.updateSetting.call(this, type, list); + }, + + // Set the looping options + + /* setLoopMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.loop)) { + return; + } + const options = ['start', 'end', 'all', 'reset']; + const list = this.elements.settings.panels.loop.querySelector('[role="menu"]'); + // Show the pane and tab + toggleHidden(this.elements.settings.buttons.loop, false); + toggleHidden(this.elements.settings.panels.loop, false); + // Toggle the pane and tab + const toggle = !is.empty(this.loop.options); + controls.toggleMenuButton.call(this, 'loop', toggle); + // Empty the menu + emptyElement(list); + options.forEach(option => { + const item = createElement('li'); + const button = createElement( + 'button', + extend(getAttributesFromSelector(this.config.selectors.buttons.loop), { + type: 'button', + class: this.config.classNames.control, + 'data-plyr-loop-action': option, + }), + i18n.get(option, this.config) + ); + if (['start', 'end'].includes(option)) { + const badge = controls.createBadge.call(this, '00:00'); + button.appendChild(badge); + } + item.appendChild(button); + list.appendChild(item); + }); + }, */ + // Get current selected caption language + // TODO: rework this to user the getter in the API? + // Set a list of available captions languages + setCaptionsMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.captions)) { + return; + } // TODO: Captions or language? Currently it's mixed + + + const type = 'captions'; + const list = this.elements.settings.panels.captions.querySelector('[role="menu"]'); + const tracks = captions.getTracks.call(this); + const toggle = Boolean(tracks.length); // Toggle the pane and tab + + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If there's no captions, bail + + if (!toggle) { + return; + } // Generate options data + + + const options = tracks.map((track, value) => ({ + value, + checked: this.captions.toggled && this.currentTrack === value, + title: captions.getLabel.call(this, track), + badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()), + list, + type: 'language' + })); // Add the "Disabled" option to turn off captions + + options.unshift({ + value: -1, + checked: !this.captions.toggled, + title: i18n.get('disabled', this.config), + list, + type: 'language' + }); // Generate options + + options.forEach(controls.createMenuItem.bind(this)); + controls.updateSetting.call(this, type, list); + }, + + // Set a list of available captions languages + setSpeedMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.speed)) { + return; + } + + const type = 'speed'; + const list = this.elements.settings.panels.speed.querySelector('[role="menu"]'); // Filter out invalid speeds + + this.options.speed = this.options.speed.filter(o => o >= this.minimumSpeed && o <= this.maximumSpeed); // Toggle the pane and tab + + const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1; + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu + + emptyElement(list); // Check if we need to toggle the parent + + controls.checkMenu.call(this); // If we're hiding, nothing more to do + + if (!toggle) { + return; + } // Create items + + + this.options.speed.forEach(speed => { + controls.createMenuItem.call(this, { + value: speed, + list, + type, + title: controls.getLabel.call(this, 'speed', speed) + }); + }); + controls.updateSetting.call(this, type, list); + }, + + // Check if we need to hide/show the settings menu + checkMenu() { + const { + buttons + } = this.elements.settings; + const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden); + toggleHidden(this.elements.settings.menu, !visible); + }, + + // Focus the first menu item in a given (or visible) menu + focusFirstMenuItem(pane, tabFocus = false) { + if (this.elements.settings.popup.hidden) { + return; + } + + let target = pane; + + if (!is.element(target)) { + target = Object.values(this.elements.settings.panels).find(p => !p.hidden); + } + + const firstItem = target.querySelector('[role^="menuitem"]'); + setFocus.call(this, firstItem, tabFocus); + }, + + // Show/hide menu + toggleMenu(input) { + const { + popup + } = this.elements.settings; + const button = this.elements.buttons.settings; // Menu and button are required + + if (!is.element(popup) || !is.element(button)) { + return; + } // True toggle by default + + + const { + hidden + } = popup; + let show = hidden; + + if (is.boolean(input)) { + show = input; + } else if (is.keyboardEvent(input) && input.which === 27) { + show = false; + } else if (is.event(input)) { + // If Plyr is in a shadowDOM, the event target is set to the component, instead of the + // Element in the shadowDOM. The path, if available, is complete. + const target = is.function(input.composedPath) ? input.composedPath()[0] : input.target; + const isMenuItem = popup.contains(target); // If the click was inside the menu or if the click + // wasn't the button or menu item and we're trying to + // show the menu (a doc click shouldn't show the menu) + + if (isMenuItem || !isMenuItem && input.target !== button && show) { + return; + } + } // Set button attributes + + + button.setAttribute('aria-expanded', show); // Show the actual popup + + toggleHidden(popup, !show); // Add class hook + + toggleClass(this.elements.container, this.config.classNames.menu.open, show); // Focus the first item if key interaction + + if (show && is.keyboardEvent(input)) { + controls.focusFirstMenuItem.call(this, null, true); + } else if (!show && !hidden) { + // If closing, re-focus the button + setFocus.call(this, button, is.keyboardEvent(input)); + } + }, + + // Get the natural size of a menu panel + getMenuSize(tab) { + const clone = tab.cloneNode(true); + clone.style.position = 'absolute'; + clone.style.opacity = 0; + clone.removeAttribute('hidden'); // Append to parent so we get the "real" size + + tab.parentNode.appendChild(clone); // Get the sizes before we remove + + const width = clone.scrollWidth; + const height = clone.scrollHeight; // Remove from the DOM + + removeElement(clone); + return { + width, + height + }; + }, + + // Show a panel in the menu + showMenuPanel(type = '', tabFocus = false) { + const target = this.elements.container.querySelector(`#plyr-settings-${this.id}-${type}`); // Nothing to show, bail + + if (!is.element(target)) { + return; + } // Hide all other panels + + + const container = target.parentNode; + const current = Array.from(container.children).find(node => !node.hidden); // If we can do fancy animations, we'll animate the height/width + + if (support.transitions && !support.reducedMotion) { + // Set the current width as a base + container.style.width = `${current.scrollWidth}px`; + container.style.height = `${current.scrollHeight}px`; // Get potential sizes + + const size = controls.getMenuSize.call(this, target); // Restore auto height/width + + const restore = event => { + // We're only bothered about height and width on the container + if (event.target !== container || !['width', 'height'].includes(event.propertyName)) { + return; + } // Revert back to auto + + + container.style.width = ''; + container.style.height = ''; // Only listen once + + off.call(this, container, transitionEndEvent, restore); + }; // Listen for the transition finishing and restore auto height/width + + + on.call(this, container, transitionEndEvent, restore); // Set dimensions to target + + container.style.width = `${size.width}px`; + container.style.height = `${size.height}px`; + } // Set attributes on current tab + + + toggleHidden(current, true); // Set attributes on target + + toggleHidden(target, false); // Focus the first item + + controls.focusFirstMenuItem.call(this, target, tabFocus); + }, + + // Set the download URL + setDownloadUrl() { + const button = this.elements.buttons.download; // Bail if no button + + if (!is.element(button)) { + return; + } // Set attribute + + + button.setAttribute('href', this.download); + }, + + // Build the default HTML + create(data) { + const { + bindMenuItemShortcuts, + createButton, + createProgress, + createRange, + createTime, + setQualityMenu, + setSpeedMenu, + showMenuPanel + } = controls; + this.elements.controls = null; // Larger overlaid play button + + if (is.array(this.config.controls) && this.config.controls.includes('play-large')) { + this.elements.container.appendChild(createButton.call(this, 'play-large')); + } // Create the container + + + const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper)); + this.elements.controls = container; // Default item attributes + + const defaultAttributes = { + class: 'plyr__controls__item' + }; // Loop through controls in order + + dedupe(is.array(this.config.controls) ? this.config.controls : []).forEach(control => { + // Restart button + if (control === 'restart') { + container.appendChild(createButton.call(this, 'restart', defaultAttributes)); + } // Rewind button + + + if (control === 'rewind') { + container.appendChild(createButton.call(this, 'rewind', defaultAttributes)); + } // Play/Pause button + + + if (control === 'play') { + container.appendChild(createButton.call(this, 'play', defaultAttributes)); + } // Fast forward button + + + if (control === 'fast-forward') { + container.appendChild(createButton.call(this, 'fast-forward', defaultAttributes)); + } // Progress + + + if (control === 'progress') { + const progressContainer = createElement('div', { + class: `${defaultAttributes.class} plyr__progress__container` + }); + const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress)); // Seek range slider + + progress.appendChild(createRange.call(this, 'seek', { + id: `plyr-seek-${data.id}` + })); // Buffer progress + + progress.appendChild(createProgress.call(this, 'buffer')); // TODO: Add loop display indicator + // Seek tooltip + + if (this.config.tooltips.seek) { + const tooltip = createElement('span', { + class: this.config.classNames.tooltip + }, '00:00'); + progress.appendChild(tooltip); + this.elements.display.seekTooltip = tooltip; + } + + this.elements.progress = progress; + progressContainer.appendChild(this.elements.progress); + container.appendChild(progressContainer); + } // Media current time display + + + if (control === 'current-time') { + container.appendChild(createTime.call(this, 'currentTime', defaultAttributes)); + } // Media duration display + + + if (control === 'duration') { + container.appendChild(createTime.call(this, 'duration', defaultAttributes)); + } // Volume controls + + + if (control === 'mute' || control === 'volume') { + let { + volume + } = this.elements; // Create the volume container if needed + + if (!is.element(volume) || !container.contains(volume)) { + volume = createElement('div', extend({}, defaultAttributes, { + class: `${defaultAttributes.class} plyr__volume`.trim() + })); + this.elements.volume = volume; + container.appendChild(volume); + } // Toggle mute button + + + if (control === 'mute') { + volume.appendChild(createButton.call(this, 'mute')); + } // Volume range control + // Ignored on iOS as it's handled globally + // https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html + + + if (control === 'volume' && !browser.isIos) { + // Set the attributes + const attributes = { + max: 1, + step: 0.05, + value: this.config.volume + }; // Create the volume range slider + + volume.appendChild(createRange.call(this, 'volume', extend(attributes, { + id: `plyr-volume-${data.id}` + }))); + } + } // Toggle captions button + + + if (control === 'captions') { + container.appendChild(createButton.call(this, 'captions', defaultAttributes)); + } // Settings button / menu + + + if (control === 'settings' && !is.empty(this.config.settings)) { + const wrapper = createElement('div', extend({}, defaultAttributes, { + class: `${defaultAttributes.class} plyr__menu`.trim(), + hidden: '' + })); + wrapper.appendChild(createButton.call(this, 'settings', { + 'aria-haspopup': true, + 'aria-controls': `plyr-settings-${data.id}`, + 'aria-expanded': false + })); + const popup = createElement('div', { + class: 'plyr__menu__container', + id: `plyr-settings-${data.id}`, + hidden: '' + }); + const inner = createElement('div'); + const home = createElement('div', { + id: `plyr-settings-${data.id}-home` + }); // Create the menu + + const menu = createElement('div', { + role: 'menu' + }); + home.appendChild(menu); + inner.appendChild(home); + this.elements.settings.panels.home = home; // Build the menu items + + this.config.settings.forEach(type => { + // TODO: bundle this with the createMenuItem helper and bindings + const menuItem = createElement('button', extend(getAttributesFromSelector(this.config.selectors.buttons.settings), { + type: 'button', + class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`, + role: 'menuitem', + 'aria-haspopup': true, + hidden: '' + })); // Bind menu shortcuts for keyboard users + + bindMenuItemShortcuts.call(this, menuItem, type); // Show menu on click + + on.call(this, menuItem, 'click', () => { + showMenuPanel.call(this, type, false); + }); + const flex = createElement('span', null, i18n.get(type, this.config)); + const value = createElement('span', { + class: this.config.classNames.menu.value + }); // Speed contains HTML entities + + value.innerHTML = data[type]; + flex.appendChild(value); + menuItem.appendChild(flex); + menu.appendChild(menuItem); // Build the panes + + const pane = createElement('div', { + id: `plyr-settings-${data.id}-${type}`, + hidden: '' + }); // Back button + + const backButton = createElement('button', { + type: 'button', + class: `${this.config.classNames.control} ${this.config.classNames.control}--back` + }); // Visible label + + backButton.appendChild(createElement('span', { + 'aria-hidden': true + }, i18n.get(type, this.config))); // Screen reader label + + backButton.appendChild(createElement('span', { + class: this.config.classNames.hidden + }, i18n.get('menuBack', this.config))); // Go back via keyboard + + on.call(this, pane, 'keydown', event => { + // We only care about <- + if (event.which !== 37) { + return; + } // Prevent seek + + + event.preventDefault(); + event.stopPropagation(); // Show the respective menu + + showMenuPanel.call(this, 'home', true); + }, false); // Go back via button click + + on.call(this, backButton, 'click', () => { + showMenuPanel.call(this, 'home', false); + }); // Add to pane + + pane.appendChild(backButton); // Menu + + pane.appendChild(createElement('div', { + role: 'menu' + })); + inner.appendChild(pane); + this.elements.settings.buttons[type] = menuItem; + this.elements.settings.panels[type] = pane; + }); + popup.appendChild(inner); + wrapper.appendChild(popup); + container.appendChild(wrapper); + this.elements.settings.popup = popup; + this.elements.settings.menu = wrapper; + } // Picture in picture button + + + if (control === 'pip' && support.pip) { + container.appendChild(createButton.call(this, 'pip', defaultAttributes)); + } // Airplay button + + + if (control === 'airplay' && support.airplay) { + container.appendChild(createButton.call(this, 'airplay', defaultAttributes)); + } // Download button + + + if (control === 'download') { + const attributes = extend({}, defaultAttributes, { + element: 'a', + href: this.download, + target: '_blank' + }); // Set download attribute for HTML5 only + + if (this.isHTML5) { + attributes.download = ''; + } + + const { + download + } = this.config.urls; + + if (!is.url(download) && this.isEmbed) { + extend(attributes, { + icon: `logo-${this.provider}`, + label: this.provider + }); + } + + container.appendChild(createButton.call(this, 'download', attributes)); + } // Toggle fullscreen button + + + if (control === 'fullscreen') { + container.appendChild(createButton.call(this, 'fullscreen', defaultAttributes)); + } + }); // Set available quality levels + + if (this.isHTML5) { + setQualityMenu.call(this, html5.getQualityOptions.call(this)); + } + + setSpeedMenu.call(this); + return container; + }, + + // Insert controls + inject() { + // Sprite + if (this.config.loadSprite) { + const icon = controls.getIconUrl.call(this); // Only load external sprite using AJAX + + if (icon.cors) { + loadSprite(icon.url, 'sprite-plyr'); + } + } // Create a unique ID + + + this.id = Math.floor(Math.random() * 10000); // Null by default + + let container = null; + this.elements.controls = null; // Set template properties + + const props = { + id: this.id, + seektime: this.config.seekTime, + title: this.config.title + }; + let update = true; // If function, run it and use output + + if (is.function(this.config.controls)) { + this.config.controls = this.config.controls.call(this, props); + } // Convert falsy controls to empty array (primarily for empty strings) + + + if (!this.config.controls) { + this.config.controls = []; + } + + if (is.element(this.config.controls) || is.string(this.config.controls)) { + // HTMLElement or Non-empty string passed as the option + container = this.config.controls; + } else { + // Create controls + container = controls.create.call(this, { + id: this.id, + seektime: this.config.seekTime, + speed: this.speed, + quality: this.quality, + captions: captions.getLabel.call(this) // TODO: Looping + // loop: 'None', + + }); + update = false; + } // Replace props with their value + + + const replace = input => { + let result = input; + Object.entries(props).forEach(([key, value]) => { + result = replaceAll(result, `{${key}}`, value); + }); + return result; + }; // Update markup + + + if (update) { + if (is.string(this.config.controls)) { + container = replace(container); + } + } // Controls container + + + let target; // Inject to custom location + + if (is.string(this.config.selectors.controls.container)) { + target = document.querySelector(this.config.selectors.controls.container); + } // Inject into the container by default + + + if (!is.element(target)) { + target = this.elements.container; + } // Inject controls HTML (needs to be before captions, hence "afterbegin") + + + const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML'; + target[insertMethod]('afterbegin', container); // Find the elements if need be + + if (!is.element(this.elements.controls)) { + controls.findElements.call(this); + } // Add pressed property to buttons + + + if (!is.empty(this.elements.buttons)) { + const addProperty = button => { + const className = this.config.classNames.controlPressed; + Object.defineProperty(button, 'pressed', { + enumerable: true, + + get() { + return hasClass(button, className); + }, + + set(pressed = false) { + toggleClass(button, className, pressed); + } + + }); + }; // Toggle classname when pressed property is set + + + Object.values(this.elements.buttons).filter(Boolean).forEach(button => { + if (is.array(button) || is.nodeList(button)) { + Array.from(button).filter(Boolean).forEach(addProperty); + } else { + addProperty(button); + } + }); + } // Edge sometimes doesn't finish the paint so force a repaint + + + if (browser.isEdge) { + repaint(target); + } // Setup tooltips + + + if (this.config.tooltips.controls) { + const { + classNames, + selectors + } = this.config; + const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`; + const labels = getElements.call(this, selector); + Array.from(labels).forEach(label => { + toggleClass(label, this.config.classNames.hidden, false); + toggleClass(label, this.config.classNames.tooltip, true); + }); + } + } + +}; + +// ========================================================================== +/** + * Parse a string to a URL object + * @param {String} input - the URL to be parsed + * @param {Boolean} safe - failsafe parsing + */ + +function parseUrl(input, safe = true) { + let url = input; + + if (safe) { + const parser = document.createElement('a'); + parser.href = url; + url = parser.href; + } + + try { + return new URL(url); + } catch (_) { + return null; + } +} // Convert object to URLSearchParams + +function buildUrlParams(input) { + const params = new URLSearchParams(); + + if (is.object(input)) { + Object.entries(input).forEach(([key, value]) => { + params.set(key, value); + }); + } + + return params; +} + +// ========================================================================== +const captions = { + // Setup captions + setup() { + // Requires UI support + if (!this.supported.ui) { + return; + } // Only Vimeo and HTML5 video supported at this point + + + if (!this.isVideo || this.isYouTube || this.isHTML5 && !support.textTracks) { + // Clear menu and hide + if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) { + controls.setCaptionsMenu.call(this); + } + + return; + } // Inject the container + + + if (!is.element(this.elements.captions)) { + this.elements.captions = createElement('div', getAttributesFromSelector(this.config.selectors.captions)); + insertAfter(this.elements.captions, this.elements.wrapper); + } // Fix IE captions if CORS is used + // Fetch captions and inject as blobs instead (data URIs not supported!) + + + if (browser.isIE && window.URL) { + const elements = this.media.querySelectorAll('track'); + Array.from(elements).forEach(track => { + const src = track.getAttribute('src'); + const url = parseUrl(src); + + if (url !== null && url.hostname !== window.location.href.hostname && ['http:', 'https:'].includes(url.protocol)) { + fetch(src, 'blob').then(blob => { + track.setAttribute('src', window.URL.createObjectURL(blob)); + }).catch(() => { + removeElement(track); + }); + } + }); + } // Get and set initial data + // The "preferred" options are not realized unless / until the wanted language has a match + // * languages: Array of user's browser languages. + // * language: The language preferred by user settings or config + // * active: The state preferred by user settings or config + // * toggled: The real captions state + + + const browserLanguages = navigator.languages || [navigator.language || navigator.userLanguage || 'en']; + const languages = dedupe(browserLanguages.map(language => language.split('-')[0])); + let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase(); // Use first browser language when language is 'auto' + + if (language === 'auto') { + [language] = languages; + } + + let active = this.storage.get('captions'); + + if (!is.boolean(active)) { + ({ + active + } = this.config.captions); + } + + Object.assign(this.captions, { + toggled: false, + active, + language, + languages + }); // Watch changes to textTracks and update captions menu + + if (this.isHTML5) { + const trackEvents = this.config.captions.update ? 'addtrack removetrack' : 'removetrack'; + on.call(this, this.media.textTracks, trackEvents, captions.update.bind(this)); + } // Update available languages in list next tick (the event must not be triggered before the listeners) + + + setTimeout(captions.update.bind(this), 0); + }, + + // Update available language options in settings based on tracks + update() { + const tracks = captions.getTracks.call(this, true); // Get the wanted language + + const { + active, + language, + meta, + currentTrackNode + } = this.captions; + const languageExists = Boolean(tracks.find(track => track.language === language)); // Handle tracks (add event listener and "pseudo"-default) + + if (this.isHTML5 && this.isVideo) { + tracks.filter(track => !meta.get(track)).forEach(track => { + this.debug.log('Track added', track); // Attempt to store if the original dom element was "default" + + meta.set(track, { + default: track.mode === 'showing' + }); // Turn off native caption rendering to avoid double captions + // Note: mode='hidden' forces a track to download. To ensure every track + // isn't downloaded at once, only 'showing' tracks should be reassigned + // eslint-disable-next-line no-param-reassign + + if (track.mode === 'showing') { + // eslint-disable-next-line no-param-reassign + track.mode = 'hidden'; + } // Add event listener for cue changes + + + on.call(this, track, 'cuechange', () => captions.updateCues.call(this)); + }); + } // Update language first time it matches, or if the previous matching track was removed + + + if (languageExists && this.language !== language || !tracks.includes(currentTrackNode)) { + captions.setLanguage.call(this, language); + captions.toggle.call(this, active && languageExists); + } // Enable or disable captions based on track length + + + if (this.elements) { + toggleClass(this.elements.container, this.config.classNames.captions.enabled, !is.empty(tracks)); + } // Update available languages in list + + + if (is.array(this.config.controls) && this.config.controls.includes('settings') && this.config.settings.includes('captions')) { + controls.setCaptionsMenu.call(this); + } + }, + + // Toggle captions display + // Used internally for the toggleCaptions method, with the passive option forced to false + toggle(input, passive = true) { + // If there's no full support + if (!this.supported.ui) { + return; + } + + const { + toggled + } = this.captions; // Current state + + const activeClass = this.config.classNames.captions.active; // Get the next state + // If the method is called without parameter, toggle based on current value + + const active = is.nullOrUndefined(input) ? !toggled : input; // Update state and trigger event + + if (active !== toggled) { + // When passive, don't override user preferences + if (!passive) { + this.captions.active = active; + this.storage.set({ + captions: active + }); + } // Force language if the call isn't passive and there is no matching language to toggle to + + + if (!this.language && active && !passive) { + const tracks = captions.getTracks.call(this); + const track = captions.findTrack.call(this, [this.captions.language, ...this.captions.languages], true); // Override user preferences to avoid switching languages if a matching track is added + + this.captions.language = track.language; // Set caption, but don't store in localStorage as user preference + + captions.set.call(this, tracks.indexOf(track)); + return; + } // Toggle button if it's enabled + + + if (this.elements.buttons.captions) { + this.elements.buttons.captions.pressed = active; + } // Add class hook + + + toggleClass(this.elements.container, activeClass, active); + this.captions.toggled = active; // Update settings menu + + controls.updateSetting.call(this, 'captions'); // Trigger event (not used internally) + + triggerEvent.call(this, this.media, active ? 'captionsenabled' : 'captionsdisabled'); + } // Wait for the call stack to clear before setting mode='hidden' + // on the active track - forcing the browser to download it + + + setTimeout(() => { + if (active && this.captions.toggled) { + this.captions.currentTrackNode.mode = 'hidden'; + } + }); + }, + + // Set captions by track index + // Used internally for the currentTrack setter with the passive option forced to false + set(index, passive = true) { + const tracks = captions.getTracks.call(this); // Disable captions if setting to -1 + + if (index === -1) { + captions.toggle.call(this, false, passive); + return; + } + + if (!is.number(index)) { + this.debug.warn('Invalid caption argument', index); + return; + } + + if (!(index in tracks)) { + this.debug.warn('Track not found', index); + return; + } + + if (this.captions.currentTrack !== index) { + this.captions.currentTrack = index; + const track = tracks[index]; + const { + language + } = track || {}; // Store reference to node for invalidation on remove + + this.captions.currentTrackNode = track; // Update settings menu + + controls.updateSetting.call(this, 'captions'); // When passive, don't override user preferences + + if (!passive) { + this.captions.language = language; + this.storage.set({ + language + }); + } // Handle Vimeo captions + + + if (this.isVimeo) { + this.embed.enableTextTrack(language); + } // Trigger event + + + triggerEvent.call(this, this.media, 'languagechange'); + } // Show captions + + + captions.toggle.call(this, true, passive); + + if (this.isHTML5 && this.isVideo) { + // If we change the active track while a cue is already displayed we need to update it + captions.updateCues.call(this); + } + }, + + // Set captions by language + // Used internally for the language setter with the passive option forced to false + setLanguage(input, passive = true) { + if (!is.string(input)) { + this.debug.warn('Invalid language argument', input); + return; + } // Normalize + + + const language = input.toLowerCase(); + this.captions.language = language; // Set currentTrack + + const tracks = captions.getTracks.call(this); + const track = captions.findTrack.call(this, [language]); + captions.set.call(this, tracks.indexOf(track), passive); + }, + + // Get current valid caption tracks + // If update is false it will also ignore tracks without metadata + // This is used to "freeze" the language options when captions.update is false + getTracks(update = false) { + // Handle media or textTracks missing or null + const tracks = Array.from((this.media || {}).textTracks || []); // For HTML5, use cache instead of current tracks when it exists (if captions.update is false) + // Filter out removed tracks and tracks that aren't captions/subtitles (for example metadata) + + return tracks.filter(track => !this.isHTML5 || update || this.captions.meta.has(track)).filter(track => ['captions', 'subtitles'].includes(track.kind)); + }, + + // Match tracks based on languages and get the first + findTrack(languages, force = false) { + const tracks = captions.getTracks.call(this); + + const sortIsDefault = track => Number((this.captions.meta.get(track) || {}).default); + + const sorted = Array.from(tracks).sort((a, b) => sortIsDefault(b) - sortIsDefault(a)); + let track; + languages.every(language => { + track = sorted.find(t => t.language === language); + return !track; // Break iteration if there is a match + }); // If no match is found but is required, get first + + return track || (force ? sorted[0] : undefined); + }, + + // Get the current track + getCurrentTrack() { + return captions.getTracks.call(this)[this.currentTrack]; + }, + + // Get UI label for track + getLabel(track) { + let currentTrack = track; + + if (!is.track(currentTrack) && support.textTracks && this.captions.toggled) { + currentTrack = captions.getCurrentTrack.call(this); + } + + if (is.track(currentTrack)) { + if (!is.empty(currentTrack.label)) { + return currentTrack.label; + } + + if (!is.empty(currentTrack.language)) { + return track.language.toUpperCase(); + } + + return i18n.get('enabled', this.config); + } + + return i18n.get('disabled', this.config); + }, + + // Update captions using current track's active cues + // Also optional array argument in case there isn't any track (ex: vimeo) + updateCues(input) { + // Requires UI + if (!this.supported.ui) { + return; + } + + if (!is.element(this.elements.captions)) { + this.debug.warn('No captions element to render to'); + return; + } // Only accept array or empty input + + + if (!is.nullOrUndefined(input) && !Array.isArray(input)) { + this.debug.warn('updateCues: Invalid input', input); + return; + } + + let cues = input; // Get cues from track + + if (!cues) { + const track = captions.getCurrentTrack.call(this); + cues = Array.from((track || {}).activeCues || []).map(cue => cue.getCueAsHTML()).map(getHTML); + } // Set new caption text + + + const content = cues.map(cueText => cueText.trim()).join('\n'); + const changed = content !== this.elements.captions.innerHTML; + + if (changed) { + // Empty the container and create a new child element + emptyElement(this.elements.captions); + const caption = createElement('span', getAttributesFromSelector(this.config.selectors.caption)); + caption.innerHTML = content; + this.elements.captions.appendChild(caption); // Trigger event + + triggerEvent.call(this, this.media, 'cuechange'); + } + } + +}; + +// ========================================================================== +// Plyr default config +// ========================================================================== +const defaults = { + // Disable + enabled: true, + // Custom media title + title: '', + // Logging to console + debug: false, + // Auto play (if supported) + autoplay: false, + // Only allow one media playing at once (vimeo only) + autopause: true, + // Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present) + // TODO: Remove iosNative fullscreen option in favour of this (logic needs work) + playsinline: true, + // Default time to skip when rewind/fast forward + seekTime: 10, + // Default volume + volume: 1, + muted: false, + // Pass a custom duration + duration: null, + // Display the media duration on load in the current time position + // If you have opted to display both duration and currentTime, this is ignored + displayDuration: true, + // Invert the current time to be a countdown + invertTime: true, + // Clicking the currentTime inverts it's value to show time left rather than elapsed + toggleInvert: true, + // Force an aspect ratio + // The format must be `'w:h'` (e.g. `'16:9'`) + ratio: null, + // Click video container to play/pause + clickToPlay: true, + // Auto hide the controls + hideControls: true, + // Reset to start when playback ended + resetOnEnd: false, + // Disable the standard context menu + disableContextMenu: true, + // Sprite (for icons) + loadSprite: true, + iconPrefix: 'plyr', + iconUrl: 'https://cdn.plyr.io/3.6.12/plyr.svg', + // Blank video (used to prevent errors on source change) + blankVideo: 'https://cdn.plyr.io/static/blank.mp4', + // Quality default + quality: { + default: 576, + // The options to display in the UI, if available for the source media + options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240], + forced: false, + onChange: null + }, + // Set loops + loop: { + active: false // start: null, + // end: null, + + }, + // Speed default and options to display + speed: { + selected: 1, + // The options to display in the UI, if available for the source media (e.g. Vimeo and YouTube only support 0.5x-4x) + options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 4] + }, + // Keyboard shortcut settings + keyboard: { + focused: true, + global: false + }, + // Display tooltips + tooltips: { + controls: false, + seek: true + }, + // Captions settings + captions: { + active: false, + language: 'auto', + // Listen to new tracks added after Plyr is initialized. + // This is needed for streaming captions, but may result in unselectable options + update: false + }, + // Fullscreen settings + fullscreen: { + enabled: true, + // Allow fullscreen? + fallback: true, + // Fallback using full viewport/window + iosNative: false // Use the native fullscreen in iOS (disables custom controls) + // Selector for the fullscreen container so contextual / non-player content can remain visible in fullscreen mode + // Non-ancestors of the player element will be ignored + // container: null, // defaults to the player element + + }, + // Local storage + storage: { + enabled: true, + key: 'plyr' + }, + // Default controls + controls: ['play-large', // 'restart', + // 'rewind', + 'play', // 'fast-forward', + 'progress', 'current-time', // 'duration', + 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', // 'download', + 'fullscreen'], + settings: ['captions', 'quality', 'speed'], + // Localisation + i18n: { + restart: 'Restart', + rewind: 'Rewind {seektime}s', + play: 'Play', + pause: 'Pause', + fastForward: 'Forward {seektime}s', + seek: 'Seek', + seekLabel: '{currentTime} of {duration}', + played: 'Played', + buffered: 'Buffered', + currentTime: 'Current time', + duration: 'Duration', + volume: 'Volume', + mute: 'Mute', + unmute: 'Unmute', + enableCaptions: 'Enable captions', + disableCaptions: 'Disable captions', + download: 'Download', + enterFullscreen: 'Enter fullscreen', + exitFullscreen: 'Exit fullscreen', + frameTitle: 'Player for {title}', + captions: 'Captions', + settings: 'Settings', + pip: 'PIP', + menuBack: 'Go back to previous menu', + speed: 'Speed', + normal: 'Normal', + quality: 'Quality', + loop: 'Loop', + start: 'Start', + end: 'End', + all: 'All', + reset: 'Reset', + disabled: 'Disabled', + enabled: 'Enabled', + advertisement: 'Ad', + qualityBadge: { + 2160: '4K', + 1440: 'HD', + 1080: 'HD', + 720: 'HD', + 576: 'SD', + 480: 'SD' + } + }, + // URLs + urls: { + download: null, + vimeo: { + sdk: 'https://player.vimeo.com/api/player.js', + iframe: 'https://player.vimeo.com/video/{0}?{1}', + api: 'https://vimeo.com/api/oembed.json?url={0}' + }, + youtube: { + sdk: 'https://www.youtube.com/iframe_api', + api: 'https://noembed.com/embed?url=https://www.youtube.com/watch?v={0}' + }, + googleIMA: { + sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js' + } + }, + // Custom control listeners + listeners: { + seek: null, + play: null, + pause: null, + restart: null, + rewind: null, + fastForward: null, + mute: null, + volume: null, + captions: null, + download: null, + fullscreen: null, + pip: null, + airplay: null, + speed: null, + quality: null, + loop: null, + language: null + }, + // Events to watch and bubble + events: [// Events to watch on HTML5 media elements and bubble + // https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events + 'ended', 'progress', 'stalled', 'playing', 'waiting', 'canplay', 'canplaythrough', 'loadstart', 'loadeddata', 'loadedmetadata', 'timeupdate', 'volumechange', 'play', 'pause', 'error', 'seeking', 'seeked', 'emptied', 'ratechange', 'cuechange', // Custom events + 'download', 'enterfullscreen', 'exitfullscreen', 'captionsenabled', 'captionsdisabled', 'languagechange', 'controlshidden', 'controlsshown', 'ready', // YouTube + 'statechange', // Quality + 'qualitychange', // Ads + 'adsloaded', 'adscontentpause', 'adscontentresume', 'adstarted', 'adsmidpoint', 'adscomplete', 'adsallcomplete', 'adsimpression', 'adsclick'], + // Selectors + // Change these to match your template if using custom HTML + selectors: { + editable: 'input, textarea, select, [contenteditable]', + container: '.plyr', + controls: { + container: null, + wrapper: '.plyr__controls' + }, + labels: '[data-plyr]', + buttons: { + play: '[data-plyr="play"]', + pause: '[data-plyr="pause"]', + restart: '[data-plyr="restart"]', + rewind: '[data-plyr="rewind"]', + fastForward: '[data-plyr="fast-forward"]', + mute: '[data-plyr="mute"]', + captions: '[data-plyr="captions"]', + download: '[data-plyr="download"]', + fullscreen: '[data-plyr="fullscreen"]', + pip: '[data-plyr="pip"]', + airplay: '[data-plyr="airplay"]', + settings: '[data-plyr="settings"]', + loop: '[data-plyr="loop"]' + }, + inputs: { + seek: '[data-plyr="seek"]', + volume: '[data-plyr="volume"]', + speed: '[data-plyr="speed"]', + language: '[data-plyr="language"]', + quality: '[data-plyr="quality"]' + }, + display: { + currentTime: '.plyr__time--current', + duration: '.plyr__time--duration', + buffer: '.plyr__progress__buffer', + loop: '.plyr__progress__loop', + // Used later + volume: '.plyr__volume--display' + }, + progress: '.plyr__progress', + captions: '.plyr__captions', + caption: '.plyr__caption' + }, + // Class hooks added to the player in different states + classNames: { + type: 'plyr--{0}', + provider: 'plyr--{0}', + video: 'plyr__video-wrapper', + embed: 'plyr__video-embed', + videoFixedRatio: 'plyr__video-wrapper--fixed-ratio', + embedContainer: 'plyr__video-embed__container', + poster: 'plyr__poster', + posterEnabled: 'plyr__poster-enabled', + ads: 'plyr__ads', + control: 'plyr__control', + controlPressed: 'plyr__control--pressed', + playing: 'plyr--playing', + paused: 'plyr--paused', + stopped: 'plyr--stopped', + loading: 'plyr--loading', + hover: 'plyr--hover', + tooltip: 'plyr__tooltip', + cues: 'plyr__cues', + hidden: 'plyr__sr-only', + hideControls: 'plyr--hide-controls', + isIos: 'plyr--is-ios', + isTouch: 'plyr--is-touch', + uiSupported: 'plyr--full-ui', + noTransition: 'plyr--no-transition', + display: { + time: 'plyr__time' + }, + menu: { + value: 'plyr__menu__value', + badge: 'plyr__badge', + open: 'plyr--menu-open' + }, + captions: { + enabled: 'plyr--captions-enabled', + active: 'plyr--captions-active' + }, + fullscreen: { + enabled: 'plyr--fullscreen-enabled', + fallback: 'plyr--fullscreen-fallback' + }, + pip: { + supported: 'plyr--pip-supported', + active: 'plyr--pip-active' + }, + airplay: { + supported: 'plyr--airplay-supported', + 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 + attributes: { + embed: { + provider: 'data-plyr-provider', + id: 'data-plyr-embed-id', + hash: 'data-plyr-embed-hash' + } + }, + // Advertisements plugin + // Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio + 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, + // Custom settings from Plyr + customControls: true, + referrerPolicy: null, + // https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/referrerPolicy + // Whether the owner of the video has a Pro or Business account + // (which allows us to properly hide controls without CSS hacks, etc) + premium: false + }, + // YouTube plugin + youtube: { + 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) + // Custom settings from Plyr + customControls: true, + noCookie: false // Whether to use an alternative version of YouTube without cookies + + } +}; + +// ========================================================================== +// Plyr states +// ========================================================================== +const pip = { + active: 'picture-in-picture', + inactive: 'inline' +}; + +// ========================================================================== +// Plyr supported types and providers +// ========================================================================== +const providers = { + html5: 'html5', + youtube: 'youtube', + vimeo: 'vimeo' +}; +const types = { + audio: 'audio', + video: 'video' +}; +/** + * Get provider by URL + * @param {String} url + */ + +function getProviderByUrl(url) { + // YouTube + if (/^(https?:\/\/)?(www\.)?(youtube\.com|youtube-nocookie\.com|youtu\.?be)\/.+$/.test(url)) { + return providers.youtube; + } // Vimeo + + + if (/^https?:\/\/player.vimeo.com\/video\/\d{0,9}(?=\b|\/)/.test(url)) { + return providers.vimeo; + } + + return null; +} + +// ========================================================================== +// Console wrapper +// ========================================================================== +const noop = () => {}; + +class Console { + constructor(enabled = false) { + this.enabled = window.console && enabled; + + if (this.enabled) { + this.log('Debugging enabled'); + } + } + + get log() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.log, console) : noop; + } + + get warn() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.warn, console) : noop; + } + + get error() { + // eslint-disable-next-line no-console + return this.enabled ? Function.prototype.bind.call(console.error, console) : noop; + } + +} + +class Fullscreen { + constructor(player) { + _defineProperty$1(this, "onChange", () => { + if (!this.enabled) { + return; + } // Update toggle button + + + const button = this.player.elements.buttons.fullscreen; + + if (is.element(button)) { + button.pressed = this.active; + } // Always trigger events on the plyr / media element (not a fullscreen container) and let them bubble up + + + const target = this.target === this.player.media ? this.target : this.player.elements.container; // Trigger an event + + triggerEvent.call(this.player, target, this.active ? 'enterfullscreen' : 'exitfullscreen', true); + }); + + _defineProperty$1(this, "toggleFallback", (toggle = false) => { + // Store or restore scroll position + if (toggle) { + this.scrollPosition = { + x: window.scrollX || 0, + y: window.scrollY || 0 + }; + } else { + window.scrollTo(this.scrollPosition.x, this.scrollPosition.y); + } // Toggle scroll + + + document.body.style.overflow = toggle ? 'hidden' : ''; // Toggle class hook + + toggleClass(this.target, this.player.config.classNames.fullscreen.fallback, toggle); // Force full viewport on iPhone X+ + + if (browser.isIos) { + let viewport = document.head.querySelector('meta[name="viewport"]'); + const property = 'viewport-fit=cover'; // Inject the viewport meta if required + + if (!viewport) { + viewport = document.createElement('meta'); + viewport.setAttribute('name', 'viewport'); + } // Check if the property already exists + + + const hasProperty = is.string(viewport.content) && viewport.content.includes(property); + + if (toggle) { + this.cleanupViewport = !hasProperty; + + if (!hasProperty) { + viewport.content += `,${property}`; + } + } else if (this.cleanupViewport) { + viewport.content = viewport.content.split(',').filter(part => part.trim() !== property).join(','); + } + } // Toggle button and fire events + + + this.onChange(); + }); + + _defineProperty$1(this, "trapFocus", event => { + // Bail if iOS, not active, not the tab key + if (browser.isIos || !this.active || event.key !== 'Tab' || event.keyCode !== 9) { + return; + } // Get the current focused element + + + const focused = document.activeElement; + const focusable = getElements.call(this.player, 'a[href], button:not(:disabled), input:not(:disabled), [tabindex]'); + const [first] = focusable; + const last = focusable[focusable.length - 1]; + + if (focused === last && !event.shiftKey) { + // Move focus to first element that can be tabbed if Shift isn't used + first.focus(); + event.preventDefault(); + } else if (focused === first && event.shiftKey) { + // Move focus to last element that can be tabbed if Shift is used + last.focus(); + event.preventDefault(); + } + }); + + _defineProperty$1(this, "update", () => { + if (this.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'); + } // Add styling hook to show button + + + toggleClass(this.player.elements.container, this.player.config.classNames.fullscreen.enabled, this.enabled); + }); + + _defineProperty$1(this, "enter", () => { + if (!this.enabled) { + return; + } // iOS native fullscreen doesn't need the request step + + + if (browser.isIos && this.player.config.fullscreen.iosNative) { + if (this.player.isVimeo) { + this.player.embed.requestFullscreen(); + } else { + this.target.webkitEnterFullscreen(); + } + } else if (!Fullscreen.native || this.forceFallback) { + this.toggleFallback(true); + } else if (!this.prefix) { + this.target.requestFullscreen({ + navigationUI: 'hide' + }); + } else if (!is.empty(this.prefix)) { + this.target[`${this.prefix}Request${this.property}`](); + } + }); + + _defineProperty$1(this, "exit", () => { + if (!this.enabled) { + return; + } // iOS native fullscreen + + + if (browser.isIos && this.player.config.fullscreen.iosNative) { + this.target.webkitExitFullscreen(); + silencePromise(this.player.play()); + } else if (!Fullscreen.native || this.forceFallback) { + this.toggleFallback(false); + } else if (!this.prefix) { + (document.cancelFullScreen || document.exitFullscreen).call(document); + } else if (!is.empty(this.prefix)) { + const action = this.prefix === 'moz' ? 'Cancel' : 'Exit'; + document[`${this.prefix}${action}${this.property}`](); + } + }); + + _defineProperty$1(this, "toggle", () => { + if (!this.active) { + this.enter(); + } else { + this.exit(); + } + }); + + // Keep reference to parent + this.player = player; // Get prefix + + this.prefix = Fullscreen.prefix; + this.property = Fullscreen.property; // 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'; // Get the fullscreen element + // Checks container is an ancestor, defaults to null + + this.player.elements.fullscreen = player.config.fullscreen.container && closest$1(this.player.elements.container, player.config.fullscreen.container); // Register event listeners + // Handle event (incase user presses escape etc) + + on.call(this.player, document, this.prefix === 'ms' ? 'MSFullscreenChange' : `${this.prefix}fullscreenchange`, () => { + // TODO: Filter for target?? + this.onChange(); + }); // Fullscreen toggle on double click + + on.call(this.player, this.player.elements.container, 'dblclick', event => { + // Ignore double click in controls + if (is.element(this.player.elements.controls) && this.player.elements.controls.contains(event.target)) { + return; + } + + this.player.listeners.proxy(event, this.toggle, 'fullscreen'); + }); // Tap focus when in fullscreen + + on.call(this, this.player.elements.container, 'keydown', event => this.trapFocus(event)); // Update the UI + + this.update(); // this.toggle = this.toggle.bind(this); + } // Determine if native supported + + + static get native() { + return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled); + } // If we're actually using native + + + get usingNative() { + return Fullscreen.native && !this.forceFallback; + } // Get the prefix for handlers + + + static get prefix() { + // No prefix + if (is.function(document.exitFullscreen)) { + return ''; + } // Check for fullscreen support by vendor prefix + + + let value = ''; + const prefixes = ['webkit', 'moz', 'ms']; + prefixes.some(pre => { + if (is.function(document[`${pre}ExitFullscreen`]) || is.function(document[`${pre}CancelFullScreen`])) { + value = pre; + return true; + } + + return false; + }); + return value; + } + + static get property() { + return this.prefix === 'moz' ? 'FullScreen' : 'Fullscreen'; + } // Determine if fullscreen is enabled + + + get enabled() { + return (Fullscreen.native || this.player.config.fullscreen.fallback) && this.player.config.fullscreen.enabled && this.player.supported.ui && this.player.isVideo; + } // Get active state + + + get active() { + if (!this.enabled) { + return false; + } // Fallback using classname + + + if (!Fullscreen.native || this.forceFallback) { + return hasClass(this.target, this.player.config.classNames.fullscreen.fallback); + } + + const element = !this.prefix ? this.target.getRootNode().fullscreenElement : this.target.getRootNode()[`${this.prefix}${this.property}Element`]; + return element && element.shadowRoot ? element === this.target.getRootNode().host : element === this.target; + } // Get target element + + + get target() { + return browser.isIos && this.player.config.fullscreen.iosNative ? this.player.media : this.player.elements.fullscreen || this.player.elements.container; + } + +} + +// ========================================================================== +// Load image avoiding xhr/fetch CORS issues +// Server status can't be obtained this way unfortunately, so this uses "naturalWidth" to determine if the image has loaded +// By default it checks if it is at least 1px, but you can add a second argument to change this +// ========================================================================== +function loadImage(src, minWidth = 1) { + return new Promise((resolve, reject) => { + const image = new Image(); + + const handler = () => { + delete image.onload; + delete image.onerror; + (image.naturalWidth >= minWidth ? resolve : reject)(image); + }; + + Object.assign(image, { + onload: handler, + onerror: handler, + src + }); + }); +} + +// ========================================================================== +const ui = { + addStyleHook() { + toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true); + toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui); + }, + + // Toggle native HTML5 media controls + toggleNativeControls(toggle = false) { + if (toggle && this.isHTML5) { + this.media.setAttribute('controls', ''); + } else { + this.media.removeAttribute('controls'); + } + }, + + // Setup the UI + build() { + // Re-attach media element listeners + // TODO: Use event bubbling? + this.listeners.media(); // Don't setup interface if no support + + if (!this.supported.ui) { + this.debug.warn(`Basic support only for ${this.provider} ${this.type}`); // Restore native controls + + ui.toggleNativeControls.call(this, true); // Bail + + return; + } // Inject custom controls if not present + + + if (!is.element(this.elements.controls)) { + // Inject custom controls + controls.inject.call(this); // Re-attach control listeners + + this.listeners.controls(); + } // Remove native controls + + + ui.toggleNativeControls.call(this); // Setup captions for HTML5 + + if (this.isHTML5) { + captions.setup.call(this); + } // Reset volume + + + this.volume = null; // Reset mute state + + this.muted = null; // Reset loop state + + this.loop = null; // Reset quality setting + + this.quality = null; // Reset speed + + this.speed = null; // Reset volume display + + controls.updateVolume.call(this); // Reset time display + + controls.timeUpdate.call(this); // Reset duration display + + controls.durationUpdate.call(this); // Update the UI + + ui.checkPlaying.call(this); // Check for picture-in-picture support + + toggleClass(this.elements.container, this.config.classNames.pip.supported, support.pip && this.isHTML5 && this.isVideo); // Check for airplay support + + toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5); // Add iOS class + + toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos); // Add touch class + + toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch); // Ready for API calls + + this.ready = true; // Ready event at end of execution stack + + setTimeout(() => { + triggerEvent.call(this, this.media, 'ready'); + }, 0); // Set the title + + ui.setTitle.call(this); // Assure the poster image is set, if the property was added before the element was created + + if (this.poster) { + ui.setPoster.call(this, this.poster, false).catch(() => {}); + } // Manually set the duration if user has overridden it. + // The event listeners for it doesn't get called if preload is disabled (#701) + + + if (this.config.duration) { + controls.durationUpdate.call(this); + } + }, + + // Setup aria attribute for play and iframe title + setTitle() { + // Find the current text + let label = i18n.get('play', this.config); // If there's a media title set, use that for the label + + if (is.string(this.config.title) && !is.empty(this.config.title)) { + label += `, ${this.config.title}`; + } // If there's a play button, set label + + + Array.from(this.elements.buttons.play || []).forEach(button => { + button.setAttribute('aria-label', label); + }); // Set iframe title + // https://github.com/sampotts/plyr/issues/124 + + if (this.isEmbed) { + const iframe = getElement.call(this, 'iframe'); + + if (!is.element(iframe)) { + return; + } // Default to media type + + + const title = !is.empty(this.config.title) ? this.config.title : 'video'; + const format = i18n.get('frameTitle', this.config); + iframe.setAttribute('title', format.replace('{title}', title)); + } + }, + + // Toggle poster + togglePoster(enable) { + toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable); + }, + + // Set the poster image (async) + // Used internally for the poster setter, with the passive option forced to false + setPoster(poster, passive = true) { + // Don't override if call is passive + if (passive && this.poster) { + return Promise.reject(new Error('Poster already set')); + } // Set property synchronously to respect the call order + + + this.media.setAttribute('data-poster', poster); // Show the poster + + this.elements.poster.removeAttribute('hidden'); // Wait until ui is ready + + return ready.call(this) // Load image + .then(() => loadImage(poster)).catch(error => { + // Hide poster on error unless it's been set by another call + if (poster === this.poster) { + ui.togglePoster.call(this, false); + } // Rethrow + + + throw error; + }).then(() => { + // Prevent race conditions + if (poster !== this.poster) { + throw new Error('setPoster cancelled by later call to setPoster'); + } + }).then(() => { + Object.assign(this.elements.poster.style, { + backgroundImage: `url('${poster}')`, + // Reset backgroundSize as well (since it can be set to "cover" for padded thumbnails for youtube) + backgroundSize: '' + }); + ui.togglePoster.call(this, true); + return poster; + }); + }, + + // Check playing state + checkPlaying(event) { + // Class hooks + toggleClass(this.elements.container, this.config.classNames.playing, this.playing); + toggleClass(this.elements.container, this.config.classNames.paused, this.paused); + toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped); // Set state + + Array.from(this.elements.buttons.play || []).forEach(target => { + Object.assign(target, { + pressed: this.playing + }); + target.setAttribute('aria-label', i18n.get(this.playing ? 'pause' : 'play', this.config)); + }); // Only update controls on non timeupdate events + + if (is.event(event) && event.type === 'timeupdate') { + return; + } // Toggle controls + + + ui.toggleControls.call(this); + }, + + // Check if media is loading + checkLoading(event) { + this.loading = ['stalled', 'waiting'].includes(event.type); // Clear timer + + clearTimeout(this.timers.loading); // Timer to prevent flicker when seeking + + this.timers.loading = setTimeout(() => { + // Update progress bar loading class state + toggleClass(this.elements.container, this.config.classNames.loading, this.loading); // Update controls visibility + + ui.toggleControls.call(this); + }, this.loading ? 250 : 0); + }, + + // Toggle controls based on state and `force` argument + toggleControls(force) { + const { + controls: controlsElement + } = this.elements; + + if (controlsElement && this.config.hideControls) { + // Don't hide controls if a touch-device user recently seeked. (Must be limited to touch devices, or it occasionally prevents desktop controls from hiding.) + const recentTouchSeek = this.touch && this.lastSeekTime + 2000 > Date.now(); // Show controls if force, loading, paused, button interaction, or recent seek, otherwise hide + + this.toggleControls(Boolean(force || this.loading || this.paused || controlsElement.pressed || controlsElement.hover || recentTouchSeek)); + } + }, + + // Migrate any custom properties from the media to the parent + migrateStyles() { + // Loop through values (as they are the keys when the object is spread 🤔) + Object.values({ ...this.media.style + }) // We're only fussed about Plyr specific properties + .filter(key => !is.empty(key) && is.string(key) && key.startsWith('--plyr')).forEach(key => { + // Set on the container + this.elements.container.style.setProperty(key, this.media.style.getPropertyValue(key)); // Clean up from media element + + this.media.style.removeProperty(key); + }); // Remove attribute if empty + + if (is.empty(this.media.style)) { + this.media.removeAttribute('style'); + } + } + +}; + +class Listeners { + constructor(_player) { + _defineProperty$1(this, "firstTouch", () => { + const { + player + } = this; + const { + elements + } = player; + player.touch = true; // Add touch class + + toggleClass(elements.container, player.config.classNames.isTouch, true); + }); + + _defineProperty$1(this, "setTabFocus", event => { + const { + player + } = this; + const { + elements + } = player; + clearTimeout(this.focusTimer); // Ignore any key other than tab + + if (event.type === 'keydown' && event.which !== 9) { + return; + } // Store reference to event timeStamp + + + if (event.type === 'keydown') { + this.lastKeyDown = event.timeStamp; + } // Remove current classes + + + const removeCurrent = () => { + const className = player.config.classNames.tabFocus; + const current = getElements.call(player, `.${className}`); + toggleClass(current, className, false); + }; // Determine if a key was pressed to trigger this event + + + const wasKeyDown = event.timeStamp - this.lastKeyDown <= 20; // Ignore focus events if a key was pressed prior + + if (event.type === 'focus' && !wasKeyDown) { + return; + } // Remove all current + + + removeCurrent(); // Delay the adding of classname until the focus has changed + // This event fires before the focusin event + + if (event.type !== 'focusout') { + this.focusTimer = setTimeout(() => { + const focused = document.activeElement; // Ignore if current focus element isn't inside the player + + if (!elements.container.contains(focused)) { + return; + } + + toggleClass(document.activeElement, player.config.classNames.tabFocus, true); + }, 10); + } + }); + + _defineProperty$1(this, "global", (toggle = true) => { + const { + player + } = this; // Keyboard shortcuts + + if (player.config.keyboard.global) { + toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false); + } // Click anywhere closes menu + + + toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle); // Detect touch by events + + once.call(player, document.body, 'touchstart', this.firstTouch); // Tab focus detection + + toggleListener.call(player, document.body, 'keydown focus blur focusout', this.setTabFocus, toggle, false, true); + }); + + _defineProperty$1(this, "container", () => { + const { + player + } = this; + const { + config, + elements, + timers + } = player; // Keyboard shortcuts + + if (!config.keyboard.global && config.keyboard.focused) { + on.call(player, elements.container, 'keydown keyup', this.handleKey, false); + } // Toggle controls on mouse events and entering fullscreen + + + on.call(player, elements.container, 'mousemove mouseleave touchstart touchmove enterfullscreen exitfullscreen', event => { + const { + controls: controlsElement + } = elements; // Remove button states for fullscreen + + if (controlsElement && event.type === 'enterfullscreen') { + controlsElement.pressed = false; + controlsElement.hover = false; + } // Show, then hide after a timeout unless another control event occurs + + + const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type); + let delay = 0; + + if (show) { + ui.toggleControls.call(player, true); // Use longer timeout for touch devices + + delay = player.touch ? 3000 : 2000; + } // Clear timer + + + clearTimeout(timers.controls); // Set new timer to prevent flicker when seeking + + timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay); + }); // Set a gutter for Vimeo + + const setGutter = () => { + if (!player.isVimeo || player.config.vimeo.premium) { + return; + } + + const target = elements.wrapper; + const { + active + } = player.fullscreen; + const [videoWidth, videoHeight] = getAspectRatio.call(player); + const useNativeAspectRatio = supportsCSS(`aspect-ratio: ${videoWidth} / ${videoHeight}`); // If not active, remove styles + + if (!active) { + if (useNativeAspectRatio) { + target.style.width = null; + target.style.height = null; + } else { + target.style.maxWidth = null; + target.style.margin = null; + } + + return; + } // Determine which dimension will overflow and constrain view + + + const [viewportWidth, viewportHeight] = getViewportSize(); + const overflow = viewportWidth / viewportHeight > videoWidth / videoHeight; + + if (useNativeAspectRatio) { + target.style.width = overflow ? 'auto' : '100%'; + target.style.height = overflow ? '100%' : 'auto'; + } else { + target.style.maxWidth = overflow ? `${viewportHeight / videoHeight * videoWidth}px` : null; + target.style.margin = overflow ? '0 auto' : null; + } + }; // Handle resizing + + + const resized = () => { + clearTimeout(timers.resized); + timers.resized = setTimeout(setGutter, 50); + }; + + on.call(player, elements.container, 'enterfullscreen exitfullscreen', event => { + const { + target + } = player.fullscreen; // Ignore events not from target + + if (target !== elements.container) { + return; + } // If it's not an embed and no ratio specified + + + if (!player.isEmbed && is.empty(player.config.ratio)) { + return; + } // Set Vimeo gutter + + + setGutter(); // Watch for resizes + + const method = event.type === 'enterfullscreen' ? on : off; + method.call(player, window, 'resize', resized); + }); + }); + + _defineProperty$1(this, "media", () => { + const { + player + } = this; + const { + elements + } = player; // Time change on media + + on.call(player, player.media, 'timeupdate seeking seeked', event => controls.timeUpdate.call(player, event)); // Display duration + + on.call(player, player.media, 'durationchange loadeddata loadedmetadata', event => controls.durationUpdate.call(player, event)); // Handle the media finishing + + on.call(player, player.media, 'ended', () => { + // Show poster on end + if (player.isHTML5 && player.isVideo && player.config.resetOnEnd) { + // Restart + player.restart(); // Call pause otherwise IE11 will start playing the video again + + player.pause(); + } + }); // Check for buffer progress + + on.call(player, player.media, 'progress playing seeking seeked', event => controls.updateProgress.call(player, event)); // Handle volume changes + + on.call(player, player.media, 'volumechange', event => controls.updateVolume.call(player, event)); // Handle play/pause + + on.call(player, player.media, 'playing play pause ended emptied timeupdate', event => ui.checkPlaying.call(player, event)); // Loading state + + on.call(player, player.media, 'waiting canplay seeked playing', event => ui.checkLoading.call(player, event)); // Click video + + if (player.supported.ui && player.config.clickToPlay && !player.isAudio) { + // Re-fetch the wrapper + const wrapper = getElement.call(player, `.${player.config.classNames.video}`); // Bail if there's no wrapper (this should never happen) + + if (!is.element(wrapper)) { + return; + } // On click play, pause or restart + + + on.call(player, elements.container, 'click', event => { + const targets = [elements.container, wrapper]; // Ignore if click if not container or in video wrapper + + if (!targets.includes(event.target) && !wrapper.contains(event.target)) { + return; + } // Touch devices will just show controls (if hidden) + + + if (player.touch && player.config.hideControls) { + return; + } + + if (player.ended) { + this.proxy(event, player.restart, 'restart'); + this.proxy(event, () => { + silencePromise(player.play()); + }, 'play'); + } else { + this.proxy(event, () => { + silencePromise(player.togglePlay()); + }, 'play'); + } + }); + } // Disable right click + + + if (player.supported.ui && player.config.disableContextMenu) { + on.call(player, elements.wrapper, 'contextmenu', event => { + event.preventDefault(); + }, false); + } // Volume change + + + on.call(player, player.media, 'volumechange', () => { + // Save to storage + player.storage.set({ + volume: player.volume, + muted: player.muted + }); + }); // Speed change + + on.call(player, player.media, 'ratechange', () => { + // Update UI + controls.updateSetting.call(player, 'speed'); // Save to storage + + player.storage.set({ + speed: player.speed + }); + }); // Quality change + + on.call(player, player.media, 'qualitychange', event => { + // Update UI + controls.updateSetting.call(player, 'quality', null, event.detail.quality); + }); // Update download link when ready and if quality changes + + on.call(player, player.media, 'ready qualitychange', () => { + controls.setDownloadUrl.call(player); + }); // Proxy events to container + // Bubble up key events for Edge + + const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' '); + on.call(player, player.media, proxyEvents, event => { + let { + detail = {} + } = event; // Get error details from media + + if (event.type === 'error') { + detail = player.media.error; + } + + triggerEvent.call(player, elements.container, event.type, true, detail); + }); + }); + + _defineProperty$1(this, "proxy", (event, defaultHandler, customHandlerKey) => { + const { + player + } = this; + const customHandler = player.config.listeners[customHandlerKey]; + const hasCustomHandler = is.function(customHandler); + let returned = true; // Execute custom handler + + if (hasCustomHandler) { + returned = customHandler.call(player, event); + } // Only call default handler if not prevented in custom handler + + + if (returned !== false && is.function(defaultHandler)) { + defaultHandler.call(player, event); + } + }); + + _defineProperty$1(this, "bind", (element, type, defaultHandler, customHandlerKey, passive = true) => { + const { + player + } = this; + const customHandler = player.config.listeners[customHandlerKey]; + const hasCustomHandler = is.function(customHandler); + on.call(player, element, type, event => this.proxy(event, defaultHandler, customHandlerKey), passive && !hasCustomHandler); + }); + + _defineProperty$1(this, "controls", () => { + const { + player + } = this; + const { + elements + } = player; // IE doesn't support input event, so we fallback to change + + const inputEvent = browser.isIE ? 'change' : 'input'; // Play/pause toggle + + if (elements.buttons.play) { + Array.from(elements.buttons.play).forEach(button => { + this.bind(button, 'click', () => { + silencePromise(player.togglePlay()); + }, 'play'); + }); + } // Pause + + + this.bind(elements.buttons.restart, 'click', player.restart, 'restart'); // Rewind + + this.bind(elements.buttons.rewind, 'click', () => { + // Record seek time so we can prevent hiding controls for a few seconds after rewind + player.lastSeekTime = Date.now(); + player.rewind(); + }, 'rewind'); // Rewind + + this.bind(elements.buttons.fastForward, 'click', () => { + // Record seek time so we can prevent hiding controls for a few seconds after fast forward + player.lastSeekTime = Date.now(); + player.forward(); + }, 'fastForward'); // Mute toggle + + this.bind(elements.buttons.mute, 'click', () => { + player.muted = !player.muted; + }, 'mute'); // Captions toggle + + this.bind(elements.buttons.captions, 'click', () => player.toggleCaptions()); // Download + + this.bind(elements.buttons.download, 'click', () => { + triggerEvent.call(player, player.media, 'download'); + }, 'download'); // Fullscreen toggle + + this.bind(elements.buttons.fullscreen, 'click', () => { + player.fullscreen.toggle(); + }, 'fullscreen'); // Picture-in-Picture + + this.bind(elements.buttons.pip, 'click', () => { + player.pip = 'toggle'; + }, 'pip'); // Airplay + + this.bind(elements.buttons.airplay, 'click', player.airplay, 'airplay'); // Settings menu - click toggle + + this.bind(elements.buttons.settings, 'click', event => { + // Prevent the document click listener closing the menu + event.stopPropagation(); + event.preventDefault(); + controls.toggleMenu.call(player, event); + }, null, false); // Can't be passive as we're preventing default + // Settings menu - keyboard toggle + // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus + // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143 + + this.bind(elements.buttons.settings, 'keyup', event => { + const code = event.which; // We only care about space and return + + if (![13, 32].includes(code)) { + return; + } // Because return triggers a click anyway, all we need to do is set focus + + + if (code === 13) { + controls.focusFirstMenuItem.call(player, null, true); + return; + } // Prevent scroll + + + event.preventDefault(); // Prevent playing video (Firefox) + + event.stopPropagation(); // Toggle menu + + controls.toggleMenu.call(player, event); + }, null, false // Can't be passive as we're preventing default + ); // Escape closes menu + + this.bind(elements.settings.menu, 'keydown', event => { + if (event.which === 27) { + controls.toggleMenu.call(player, event); + } + }); // Set range input alternative "value", which matches the tooltip time (#954) + + this.bind(elements.inputs.seek, 'mousedown mousemove', event => { + const rect = elements.progress.getBoundingClientRect(); + const percent = 100 / rect.width * (event.pageX - rect.left); + event.currentTarget.setAttribute('seek-value', percent); + }); // Pause while seeking + + this.bind(elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', event => { + const seek = event.currentTarget; + const code = event.keyCode ? event.keyCode : event.which; + const attribute = 'play-on-seeked'; + + if (is.keyboardEvent(event) && code !== 39 && code !== 37) { + return; + } // Record seek time so we can prevent hiding controls for a few seconds after seek + + + player.lastSeekTime = Date.now(); // Was playing before? + + const play = seek.hasAttribute(attribute); // Done seeking + + const done = ['mouseup', 'touchend', 'keyup'].includes(event.type); // If we're done seeking and it was playing, resume playback + + if (play && done) { + seek.removeAttribute(attribute); + silencePromise(player.play()); + } else if (!done && player.playing) { + seek.setAttribute(attribute, ''); + player.pause(); + } + }); // Fix range inputs on iOS + // Super weird iOS bug where after you interact with an <input type="range">, + // it takes over further interactions on the page. This is a hack + + if (browser.isIos) { + const inputs = getElements.call(player, 'input[type="range"]'); + Array.from(inputs).forEach(input => this.bind(input, inputEvent, event => repaint(event.target))); + } // Seek + + + this.bind(elements.inputs.seek, inputEvent, event => { + const seek = event.currentTarget; // If it exists, use seek-value instead of "value" for consistency with tooltip time (#954) + + let seekTo = seek.getAttribute('seek-value'); + + if (is.empty(seekTo)) { + seekTo = seek.value; + } + + seek.removeAttribute('seek-value'); + player.currentTime = seekTo / seek.max * player.duration; + }, 'seek'); // Seek tooltip + + this.bind(elements.progress, 'mouseenter mouseleave mousemove', event => 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 touchend 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 => { + this.bind(element, 'input', event => controls.updateRangeFill.call(player, event.target)); + }); + } // Current time invert + // Only if one time element is used for both currentTime and duration + + + if (player.config.toggleInvert && !is.element(elements.display.duration)) { + this.bind(elements.display.currentTime, 'click', () => { + // Do nothing if we're at the start + if (player.currentTime === 0) { + return; + } + + player.config.invertTime = !player.config.invertTime; + controls.timeUpdate.call(player); + }); + } // Volume + + + this.bind(elements.inputs.volume, inputEvent, event => { + player.volume = event.target.value; + }, 'volume'); // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting) + + this.bind(elements.controls, 'mouseenter mouseleave', event => { + elements.controls.hover = !player.touch && event.type === 'mouseenter'; + }); // Also update controls.hover state for any non-player children of fullscreen element (as above) + + if (elements.fullscreen) { + Array.from(elements.fullscreen.children).filter(c => !c.contains(elements.container)).forEach(child => { + this.bind(child, 'mouseenter mouseleave', event => { + if (elements.controls) { + elements.controls.hover = !player.touch && event.type === 'mouseenter'; + } + }); + }); + } // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting) + + + this.bind(elements.controls, 'mousedown mouseup touchstart touchend touchcancel', event => { + elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type); + }); // Show controls when they receive focus (e.g., when using keyboard tab key) + + this.bind(elements.controls, 'focusin', () => { + const { + config, + timers + } = player; // Skip transition to prevent focus from scrolling the parent element + + toggleClass(elements.controls, config.classNames.noTransition, true); // Toggle + + ui.toggleControls.call(player, true); // Restore transition + + setTimeout(() => { + toggleClass(elements.controls, config.classNames.noTransition, false); + }, 0); // Delay a little more for mouse users + + const delay = this.touch ? 3000 : 4000; // Clear timer + + clearTimeout(timers.controls); // Hide again after delay + + timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay); + }); // Mouse wheel for volume + + this.bind(elements.inputs.volume, 'wheel', event => { + // Detect "natural" scroll - suppored on OS X Safari only + // Other browsers on OS X will be inverted until support improves + const inverted = event.webkitDirectionInvertedFromDevice; // Get delta from event. Invert if `inverted` is true + + const [x, y] = [event.deltaX, -event.deltaY].map(value => inverted ? -value : value); // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta) + + const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y); // Change the volume by 2% + + player.increaseVolume(direction / 50); // Don't break page scrolling at max and min + + const { + volume + } = player.media; + + if (direction === 1 && volume < 1 || direction === -1 && volume > 0) { + event.preventDefault(); + } + }, 'volume', false); + }); + + this.player = _player; + this.lastKey = null; + this.focusTimer = null; + this.lastKeyDown = null; + this.handleKey = this.handleKey.bind(this); + this.toggleMenu = this.toggleMenu.bind(this); + this.setTabFocus = this.setTabFocus.bind(this); + this.firstTouch = this.firstTouch.bind(this); + } // Handle key presses + + + handleKey(event) { + const { + player + } = this; + const { + elements + } = player; + const code = event.keyCode ? event.keyCode : event.which; + const pressed = event.type === 'keydown'; + const repeat = pressed && code === this.lastKey; // Bail if a modifier key is set + + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { + return; + } // If the event is bubbled from the media element + // Firefox doesn't get the keycode for whatever reason + + + if (!is.number(code)) { + return; + } // Seek by the number keys + + + const seekByKey = () => { + // Divide the max duration into 10th's and times by the number value + player.currentTime = player.duration / 10 * (code - 48); + }; // Handle the key on keydown + // Reset on keyup + + + if (pressed) { + // Check focused element + // and if the focused element is not editable (e.g. text input) + // and any that accept key input http://webaim.org/techniques/keyboard/ + const focused = document.activeElement; + + if (is.element(focused)) { + const { + editable + } = player.config.selectors; + const { + seek + } = elements.inputs; + + if (focused !== seek && matches(focused, editable)) { + return; + } + + if (event.which === 32 && matches(focused, 'button, [role^="menuitem"]')) { + return; + } + } // Which keycodes should we prevent default + + + const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79]; // If the code is found prevent default (e.g. prevent scrolling for arrows) + + if (preventDefault.includes(code)) { + event.preventDefault(); + event.stopPropagation(); + } + + switch (code) { + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + // 0-9 + if (!repeat) { + seekByKey(); + } + + break; + + case 32: + case 75: + // Space and K key + if (!repeat) { + silencePromise(player.togglePlay()); + } + + break; + + case 38: + // Arrow up + player.increaseVolume(0.1); + break; + + case 40: + // Arrow down + player.decreaseVolume(0.1); + break; + + case 77: + // M key + if (!repeat) { + player.muted = !player.muted; + } + + break; + + case 39: + // Arrow forward + player.forward(); + break; + + case 37: + // Arrow back + player.rewind(); + break; + + case 70: + // F key + player.fullscreen.toggle(); + break; + + case 67: + // C key + if (!repeat) { + player.toggleCaptions(); + } + + break; + + case 76: + // L key + player.loop = !player.loop; + break; + } // Escape is handle natively when in full screen + // So we only need to worry about non native + + + if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) { + player.fullscreen.toggle(); + } // Store last code for next cycle + + + this.lastKey = code; + } else { + this.lastKey = null; + } + } // Toggle menu + + + toggleMenu(event) { + controls.toggleMenu.call(this.player, event); + } // Device is touch enabled + + +} + +var loadjs_umd = createCommonjsModule(function (module, exports) { + (function (root, factory) { + { + module.exports = factory(); + } + })(commonjsGlobal, function () { + /** + * Global dependencies. + * @global {Object} document - DOM + */ + var devnull = function () {}, + bundleIdCache = {}, + bundleResultCache = {}, + bundleCallbackQueue = {}; + /** + * Subscribe to bundle load event. + * @param {string[]} bundleIds - Bundle ids + * @param {Function} callbackFn - The callback function + */ + + + function subscribe(bundleIds, callbackFn) { + // listify + bundleIds = bundleIds.push ? bundleIds : [bundleIds]; + var depsNotFound = [], + i = bundleIds.length, + numWaiting = i, + fn, + bundleId, + r, + q; // define callback function + + fn = function (bundleId, pathsNotFound) { + if (pathsNotFound.length) depsNotFound.push(bundleId); + numWaiting--; + if (!numWaiting) callbackFn(depsNotFound); + }; // register callback + + + while (i--) { + bundleId = bundleIds[i]; // execute callback if in result cache + + r = bundleResultCache[bundleId]; + + if (r) { + fn(bundleId, r); + continue; + } // add to callback queue + + + q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || []; + q.push(fn); + } + } + /** + * Publish bundle load event. + * @param {string} bundleId - Bundle id + * @param {string[]} pathsNotFound - List of files not found + */ + + + function publish(bundleId, pathsNotFound) { + // exit if id isn't defined + if (!bundleId) return; + var q = bundleCallbackQueue[bundleId]; // cache result + + bundleResultCache[bundleId] = pathsNotFound; // exit if queue is empty + + if (!q) return; // empty callback queue + + while (q.length) { + q[0](bundleId, pathsNotFound); + q.splice(0, 1); + } + } + /** + * Execute callbacks. + * @param {Object or Function} args - The callback args + * @param {string[]} depsNotFound - List of dependencies not found + */ + + + function executeCallbacks(args, depsNotFound) { + // accept function as argument + if (args.call) args = { + success: args + }; // success and error callbacks + + if (depsNotFound.length) (args.error || devnull)(depsNotFound);else (args.success || devnull)(args); + } + /** + * Load individual file. + * @param {string} path - The file path + * @param {Function} callbackFn - The callback function + */ + + + function loadFile(path, callbackFn, args, numTries) { + var doc = document, + async = args.async, + maxTries = (args.numRetries || 0) + 1, + beforeCallbackFn = args.before || devnull, + pathname = path.replace(/[\?|#].*$/, ''), + pathStripped = path.replace(/^(css|img)!/, ''), + isLegacyIECss, + e; + numTries = numTries || 0; + + if (/(^css!|\.css$)/.test(pathname)) { + // css + e = doc.createElement('link'); + e.rel = 'stylesheet'; + e.href = pathStripped; // tag IE9+ + + isLegacyIECss = 'hideFocus' in e; // use preload in IE Edge (to detect load errors) + + if (isLegacyIECss && e.relList) { + isLegacyIECss = 0; + e.rel = 'preload'; + e.as = 'style'; + } + } else if (/(^img!|\.(png|gif|jpg|svg|webp)$)/.test(pathname)) { + // image + e = doc.createElement('img'); + e.src = pathStripped; + } else { + // javascript + e = doc.createElement('script'); + e.src = path; + e.async = async === undefined ? true : async; + } + + e.onload = e.onerror = e.onbeforeload = function (ev) { + var result = ev.type[0]; // treat empty stylesheets as failures to get around lack of onerror + // support in IE9-11 + + if (isLegacyIECss) { + try { + if (!e.sheet.cssText.length) result = 'e'; + } catch (x) { + // sheets objects created from load errors don't allow access to + // `cssText` (unless error is Code:18 SecurityError) + if (x.code != 18) result = 'e'; + } + } // handle retries in case of load failure + + + if (result == 'e') { + // increment counter + numTries += 1; // exit function and try again + + if (numTries < maxTries) { + return loadFile(path, callbackFn, args, numTries); + } + } else if (e.rel == 'preload' && e.as == 'style') { + // activate preloaded stylesheets + return e.rel = 'stylesheet'; // jshint ignore:line + } // execute callback + + + callbackFn(path, result, ev.defaultPrevented); + }; // add to document (unless callback returns `false`) + + + if (beforeCallbackFn(path, e) !== false) doc.head.appendChild(e); + } + /** + * Load multiple files. + * @param {string[]} paths - The file paths + * @param {Function} callbackFn - The callback function + */ + + + function loadFiles(paths, callbackFn, args) { + // listify paths + paths = paths.push ? paths : [paths]; + var numWaiting = paths.length, + x = numWaiting, + pathsNotFound = [], + fn, + i; // define callback function + + fn = function (path, result, defaultPrevented) { + // handle error + if (result == 'e') pathsNotFound.push(path); // handle beforeload event. If defaultPrevented then that means the load + // will be blocked (ex. Ghostery/ABP on Safari) + + if (result == 'b') { + if (defaultPrevented) pathsNotFound.push(path);else return; + } + + numWaiting--; + if (!numWaiting) callbackFn(pathsNotFound); + }; // load scripts + + + for (i = 0; i < x; i++) loadFile(paths[i], fn, args); + } + /** + * Initiate script load and register bundle. + * @param {(string|string[])} paths - The file paths + * @param {(string|Function|Object)} [arg1] - The (1) bundleId or (2) success + * callback or (3) object literal with success/error arguments, numRetries, + * etc. + * @param {(Function|Object)} [arg2] - The (1) success callback or (2) object + * literal with success/error arguments, numRetries, etc. + */ + + + function loadjs(paths, arg1, arg2) { + var bundleId, args; // bundleId (if string) + + if (arg1 && arg1.trim) bundleId = arg1; // args (default is {}) + + args = (bundleId ? arg2 : arg1) || {}; // throw error if bundle is already defined + + if (bundleId) { + if (bundleId in bundleIdCache) { + throw "LoadJS"; + } else { + bundleIdCache[bundleId] = true; + } + } + + function loadFn(resolve, reject) { + loadFiles(paths, function (pathsNotFound) { + // execute callbacks + executeCallbacks(args, pathsNotFound); // resolve Promise + + if (resolve) { + executeCallbacks({ + success: resolve, + error: reject + }, pathsNotFound); + } // publish bundle load event + + + publish(bundleId, pathsNotFound); + }, args); + } + + if (args.returnPromise) return new Promise(loadFn);else loadFn(); + } + /** + * Execute callbacks when dependencies have been satisfied. + * @param {(string|string[])} deps - List of bundle ids + * @param {Object} args - success/error arguments + */ + + + loadjs.ready = function ready(deps, args) { + // subscribe to bundle load event + subscribe(deps, function (depsNotFound) { + // execute callbacks + executeCallbacks(args, depsNotFound); + }); + return loadjs; + }; + /** + * Manually satisfy bundle dependencies. + * @param {string} bundleId - The bundle id + */ + + + loadjs.done = function done(bundleId) { + publish(bundleId, []); + }; + /** + * Reset loadjs dependencies statuses + */ + + + loadjs.reset = function reset() { + bundleIdCache = {}; + bundleResultCache = {}; + bundleCallbackQueue = {}; + }; + /** + * Determine if bundle has already been defined + * @param String} bundleId - The bundle id + */ + + + loadjs.isDefined = function isDefined(bundleId) { + return bundleId in bundleIdCache; + }; // export + + + return loadjs; + }); +}); + +// ========================================================================== +function loadScript(url) { + return new Promise((resolve, reject) => { + loadjs_umd(url, { + success: resolve, + error: reject + }); + }); +} + +// ========================================================================== + +function parseId$1(url) { + if (is.empty(url)) { + return null; + } + + if (is.number(Number(url))) { + return url; + } + + const regex = /^.*(vimeo.com\/|video\/)(\d+).*/; + return url.match(regex) ? RegExp.$2 : url; +} // Try to extract a hash for private videos from the URL + + +function parseHash(url) { + /* This regex matches a hexadecimal hash if given in any of these forms: + * - [https://player.]vimeo.com/video/{id}/{hash}[?params] + * - [https://player.]vimeo.com/video/{id}?h={hash}[¶ms] + * - [https://player.]vimeo.com/video/{id}?[params]&h={hash} + * - video/{id}/{hash} + * If matched, the hash is available in the named group `hash` + */ + const regex = /^.*(?:vimeo.com\/|video\/)(?:\d+)(?:\?.*&*h=|\/)+(?<hash>[\d,a-f]+)/; + const found = url.match(regex); + return found ? found.groups.hash : null; +} // Set playback state and trigger change (only on actual change) + + +function assurePlaybackState$1(play) { + if (play && !this.embed.hasPlayed) { + this.embed.hasPlayed = true; + } + + if (this.media.paused === play) { + this.media.paused = !play; + triggerEvent.call(this, this.media, play ? 'play' : 'pause'); + } +} + +const vimeo = { + setup() { + const player = this; // Add embed class for responsive + + toggleClass(player.elements.wrapper, player.config.classNames.embed, true); // Set speed options from config + + player.options.speed = player.config.speed.options; // Set intial ratio + + setAspectRatio.call(player); // Load the SDK if not already + + if (!is.object(window.Vimeo)) { + loadScript(player.config.urls.vimeo.sdk).then(() => { + vimeo.ready.call(player); + }).catch(error => { + player.debug.warn('Vimeo SDK (player.js) failed to load', error); + }); + } else { + vimeo.ready.call(player); + } + }, + + // API Ready + ready() { + const player = this; + const config = player.config.vimeo; + const { + premium, + referrerPolicy, + ...frameParams + } = config; // Get the source URL or ID + + let source = player.media.getAttribute('src'); + let hash = ''; // Get from <div> if needed + + if (is.empty(source)) { + source = player.media.getAttribute(player.config.attributes.embed.id); // hash can also be set as attribute on the <div> + + hash = player.media.getAttribute(player.config.attributes.embed.hash); + } else { + hash = parseHash(source); + } + + const hashParam = hash ? { + h: hash + } : {}; // If the owner has a pro or premium account then we can hide controls etc + + if (premium) { + Object.assign(frameParams, { + controls: false, + sidedock: false + }); + } // Get Vimeo params for the iframe + + + const params = buildUrlParams({ + loop: player.config.loop.active, + autoplay: player.autoplay, + muted: player.muted, + gesture: 'media', + playsinline: !this.config.fullscreen.iosNative, + // hash has to be added to iframe-URL + ...hashParam, + ...frameParams + }); + const id = parseId$1(source); // Build an iframe + + const iframe = createElement('iframe'); + const src = format(player.config.urls.vimeo.iframe, id, params); + iframe.setAttribute('src', src); + iframe.setAttribute('allowfullscreen', ''); + iframe.setAttribute('allow', ['autoplay', 'fullscreen', 'picture-in-picture', 'encrypted-media', 'accelerometer', 'gyroscope'].join('; ')); // Set the referrer policy if required + + if (!is.empty(referrerPolicy)) { + iframe.setAttribute('referrerPolicy', referrerPolicy); + } // Inject the package + + + if (premium || !config.customControls) { + iframe.setAttribute('data-poster', player.poster); + player.media = replaceElement(iframe, player.media); + } else { + const wrapper = createElement('div', { + class: player.config.classNames.embedContainer, + 'data-poster': player.poster + }); + wrapper.appendChild(iframe); + player.media = replaceElement(wrapper, player.media); + } // Get poster image + + + if (!config.customControls) { + fetch(format(player.config.urls.vimeo.api, src)).then(response => { + if (is.empty(response) || !response.thumbnail_url) { + return; + } // Set and show poster + + + ui.setPoster.call(player, response.thumbnail_url).catch(() => {}); + }); + } // Setup instance + // https://github.com/vimeo/player.js + + + player.embed = new window.Vimeo.Player(iframe, { + autopause: player.config.autopause, + muted: player.muted + }); + player.media.paused = true; + player.media.currentTime = 0; // Disable native text track rendering + + if (player.supported.ui) { + player.embed.disableTextTrack(); + } // Create a faux HTML5 API using the Vimeo API + + + player.media.play = () => { + assurePlaybackState$1.call(player, true); + return player.embed.play(); + }; + + player.media.pause = () => { + assurePlaybackState$1.call(player, false); + return player.embed.pause(); + }; + + player.media.stop = () => { + player.pause(); + player.currentTime = 0; + }; // Seeking + + + let { + currentTime + } = player.media; + Object.defineProperty(player.media, 'currentTime', { + get() { + return currentTime; + }, + + set(time) { + // Vimeo will automatically play on seek if the video hasn't been played before + // Get current paused state and volume etc + const { + embed, + media, + paused, + volume + } = player; + const restorePause = paused && !embed.hasPlayed; // Set seeking state and trigger event + + media.seeking = true; + triggerEvent.call(player, media, 'seeking'); // If paused, mute until seek is complete + + Promise.resolve(restorePause && embed.setVolume(0)) // Seek + .then(() => embed.setCurrentTime(time)) // Restore paused + .then(() => restorePause && embed.pause()) // Restore volume + .then(() => restorePause && embed.setVolume(volume)).catch(() => {// Do nothing + }); + } + + }); // Playback speed + + let speed = player.config.speed.selected; + Object.defineProperty(player.media, 'playbackRate', { + get() { + return speed; + }, + + set(input) { + player.embed.setPlaybackRate(input).then(() => { + speed = input; + triggerEvent.call(player, player.media, 'ratechange'); + }).catch(() => { + // Cannot set Playback Rate, Video is probably not on Pro account + player.options.speed = [1]; + }); + } + + }); // Volume + + let { + volume + } = player.config; + Object.defineProperty(player.media, 'volume', { + get() { + return volume; + }, + + set(input) { + player.embed.setVolume(input).then(() => { + volume = input; + triggerEvent.call(player, player.media, 'volumechange'); + }); + } + + }); // Muted + + let { + muted + } = player.config; + Object.defineProperty(player.media, 'muted', { + get() { + return muted; + }, + + set(input) { + const toggle = is.boolean(input) ? input : false; + player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => { + muted = toggle; + triggerEvent.call(player, player.media, 'volumechange'); + }); + } + + }); // Loop + + let { + loop + } = player.config; + Object.defineProperty(player.media, 'loop', { + get() { + return loop; + }, + + set(input) { + const toggle = is.boolean(input) ? input : player.config.loop.active; + player.embed.setLoop(toggle).then(() => { + loop = toggle; + }); + } + + }); // Source + + let currentSrc; + player.embed.getVideoUrl().then(value => { + currentSrc = value; + controls.setDownloadUrl.call(player); + }).catch(error => { + this.debug.warn(error); + }); + Object.defineProperty(player.media, 'currentSrc', { + get() { + return currentSrc; + } + + }); // Ended + + Object.defineProperty(player.media, 'ended', { + get() { + return player.currentTime === player.duration; + } + + }); // Set aspect ratio based on video size + + Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(dimensions => { + const [width, height] = dimensions; + player.embed.ratio = roundAspectRatio(width, height); + setAspectRatio.call(this); + }); // Set autopause + + player.embed.setAutopause(player.config.autopause).then(state => { + player.config.autopause = state; + }); // Get title + + player.embed.getVideoTitle().then(title => { + player.config.title = title; + ui.setTitle.call(this); + }); // Get current time + + player.embed.getCurrentTime().then(value => { + currentTime = value; + triggerEvent.call(player, player.media, 'timeupdate'); + }); // Get duration + + player.embed.getDuration().then(value => { + player.media.duration = value; + triggerEvent.call(player, player.media, 'durationchange'); + }); // Get captions + + player.embed.getTextTracks().then(tracks => { + player.media.textTracks = tracks; + captions.setup.call(player); + }); + player.embed.on('cuechange', ({ + cues = [] + }) => { + const strippedCues = cues.map(cue => stripHTML(cue.text)); + captions.updateCues.call(player, strippedCues); + }); + player.embed.on('loaded', () => { + // Assure state and events are updated on autoplay + player.embed.getPaused().then(paused => { + assurePlaybackState$1.call(player, !paused); + + if (!paused) { + triggerEvent.call(player, player.media, 'playing'); + } + }); + + if (is.element(player.embed.element) && player.supported.ui) { + const frame = player.embed.element; // Fix keyboard focus issues + // https://github.com/sampotts/plyr/issues/317 + + frame.setAttribute('tabindex', -1); + } + }); + player.embed.on('bufferstart', () => { + triggerEvent.call(player, player.media, 'waiting'); + }); + player.embed.on('bufferend', () => { + triggerEvent.call(player, player.media, 'playing'); + }); + player.embed.on('play', () => { + assurePlaybackState$1.call(player, true); + triggerEvent.call(player, player.media, 'playing'); + }); + player.embed.on('pause', () => { + assurePlaybackState$1.call(player, false); + }); + player.embed.on('timeupdate', data => { + player.media.seeking = false; + currentTime = data.seconds; + triggerEvent.call(player, player.media, 'timeupdate'); + }); + player.embed.on('progress', data => { + player.media.buffered = data.percent; + triggerEvent.call(player, player.media, 'progress'); // Check all loaded + + if (parseInt(data.percent, 10) === 1) { + triggerEvent.call(player, player.media, 'canplaythrough'); + } // Get duration as if we do it before load, it gives an incorrect value + // https://github.com/sampotts/plyr/issues/891 + + + player.embed.getDuration().then(value => { + if (value !== player.media.duration) { + player.media.duration = value; + triggerEvent.call(player, player.media, 'durationchange'); + } + }); + }); + player.embed.on('seeked', () => { + player.media.seeking = false; + triggerEvent.call(player, player.media, 'seeked'); + }); + player.embed.on('ended', () => { + player.media.paused = true; + triggerEvent.call(player, player.media, 'ended'); + }); + player.embed.on('error', detail => { + player.media.error = detail; + triggerEvent.call(player, player.media, 'error'); + }); // Rebuild UI + + if (config.customControls) { + setTimeout(() => ui.build.call(player), 0); + } + } + +}; + +// ========================================================================== + +function parseId(url) { + if (is.empty(url)) { + return null; + } + + const regex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/; + return url.match(regex) ? RegExp.$2 : url; +} // Set playback state and trigger change (only on actual change) + + +function assurePlaybackState(play) { + if (play && !this.embed.hasPlayed) { + this.embed.hasPlayed = true; + } + + if (this.media.paused === play) { + this.media.paused = !play; + triggerEvent.call(this, this.media, play ? 'play' : 'pause'); + } +} + +function getHost(config) { + if (config.noCookie) { + return 'https://www.youtube-nocookie.com'; + } + + if (window.location.protocol === 'http:') { + return 'http://www.youtube.com'; + } // Use YouTube's default + + + return undefined; +} + +const youtube = { + setup() { + // Add embed class for responsive + toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Setup API + + if (is.object(window.YT) && is.function(window.YT.Player)) { + youtube.ready.call(this); + } else { + // Reference current global callback + const callback = window.onYouTubeIframeAPIReady; // Set callback to process queue + + window.onYouTubeIframeAPIReady = () => { + // Call global callback if set + if (is.function(callback)) { + callback(); + } + + youtube.ready.call(this); + }; // Load the SDK + + + loadScript(this.config.urls.youtube.sdk).catch(error => { + this.debug.warn('YouTube API failed to load', error); + }); + } + }, + + // Get the media title + getTitle(videoId) { + const url = format(this.config.urls.youtube.api, videoId); + fetch(url).then(data => { + if (is.object(data)) { + const { + title, + height, + width + } = data; // Set title + + this.config.title = title; + ui.setTitle.call(this); // Set aspect ratio + + this.embed.ratio = roundAspectRatio(width, height); + } + + setAspectRatio.call(this); + }).catch(() => { + // Set aspect ratio + setAspectRatio.call(this); + }); + }, + + // API ready + ready() { + const player = this; + const config = player.config.youtube; // Ignore already setup (race condition) + + const currentId = player.media && player.media.getAttribute('id'); + + if (!is.empty(currentId) && currentId.startsWith('youtube-')) { + return; + } // Get the source URL or ID + + + let source = player.media.getAttribute('src'); // Get from <div> if needed + + if (is.empty(source)) { + source = player.media.getAttribute(this.config.attributes.embed.id); + } // Replace the <iframe> with a <div> due to YouTube API issues + + + const videoId = parseId(source); + const id = generateId(player.provider); // Replace media element + + const container = createElement('div', { + id, + 'data-poster': config.customControls ? player.poster : undefined + }); + player.media = replaceElement(container, player.media); // Only load the poster when using custom controls + + if (config.customControls) { + const posterSrc = s => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`; // Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide) + + + loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded + .catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3 + .catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists + .then(image => ui.setPoster.call(player, image.src)).then(src => { + // If the image is padded, use background-size "cover" instead (like youtube does too with their posters) + if (!src.includes('maxres')) { + player.elements.poster.style.backgroundSize = 'cover'; + } + }).catch(() => {}); + } // Setup instance + // https://developers.google.com/youtube/iframe_api_reference + + + player.embed = new window.YT.Player(player.media, { + videoId, + host: getHost(config), + playerVars: extend({}, { + // Autoplay + autoplay: player.config.autoplay ? 1 : 0, + // iframe interface language + hl: player.config.hl, + // Only show controls if not fully supported or opted out + controls: player.supported.ui && config.customControls ? 0 : 1, + // Disable keyboard as we handle it + disablekb: 1, + // Allow iOS inline playback + playsinline: !player.config.fullscreen.iosNative ? 1 : 0, + // 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 + if (!player.media.error) { + const code = event.data; // Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError + + const message = { + 2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.', + 5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.', + 100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.', + 101: 'The owner of the requested video does not allow it to be played in embedded players.', + 150: 'The owner of the requested video does not allow it to be played in embedded players.' + }[code] || 'An unknown error occured'; + player.media.error = { + code, + message + }; + triggerEvent.call(player, player.media, 'error'); + } + }, + + onPlaybackRateChange(event) { + // Get the instance + const instance = event.target; // Get current speed + + player.media.playbackRate = instance.getPlaybackRate(); + triggerEvent.call(player, player.media, 'ratechange'); + }, + + onReady(event) { + // Bail if onReady has already been called. See issue #1108 + if (is.function(player.media.play)) { + return; + } // Get the instance + + + const instance = event.target; // Get the title + + youtube.getTitle.call(player, videoId); // Create a faux HTML5 API using the YouTube API + + player.media.play = () => { + assurePlaybackState.call(player, true); + instance.playVideo(); + }; + + player.media.pause = () => { + assurePlaybackState.call(player, false); + instance.pauseVideo(); + }; + + player.media.stop = () => { + instance.stopVideo(); + }; + + player.media.duration = instance.getDuration(); + player.media.paused = true; // Seeking + + player.media.currentTime = 0; + Object.defineProperty(player.media, 'currentTime', { + get() { + return Number(instance.getCurrentTime()); + }, + + set(time) { + // If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet). + if (player.paused && !player.embed.hasPlayed) { + player.embed.mute(); + } // Set seeking state and trigger event + + + player.media.seeking = true; + triggerEvent.call(player, player.media, 'seeking'); // Seek after events sent + + instance.seekTo(time); + } + + }); // Playback speed + + Object.defineProperty(player.media, 'playbackRate', { + get() { + return instance.getPlaybackRate(); + }, + + set(input) { + instance.setPlaybackRate(input); + } + + }); // Volume + + let { + volume + } = player.config; + Object.defineProperty(player.media, 'volume', { + get() { + return volume; + }, + + set(input) { + volume = input; + instance.setVolume(volume * 100); + triggerEvent.call(player, player.media, 'volumechange'); + } + + }); // Muted + + let { + muted + } = player.config; + Object.defineProperty(player.media, 'muted', { + get() { + return muted; + }, + + set(input) { + const toggle = is.boolean(input) ? input : muted; + muted = toggle; + instance[toggle ? 'mute' : 'unMute'](); + instance.setVolume(volume * 100); + triggerEvent.call(player, player.media, 'volumechange'); + } + + }); // Source + + Object.defineProperty(player.media, 'currentSrc', { + get() { + return instance.getVideoUrl(); + } + + }); // Ended + + Object.defineProperty(player.media, 'ended', { + get() { + return player.currentTime === player.duration; + } + + }); // Get available speeds + + const speeds = instance.getAvailablePlaybackRates(); // Filter based on config + + player.options.speed = speeds.filter(s => player.config.speed.options.includes(s)); // Set the tabindex to avoid focus entering iframe + + if (player.supported.ui && config.customControls) { + player.media.setAttribute('tabindex', -1); + } + + triggerEvent.call(player, player.media, 'timeupdate'); + triggerEvent.call(player, player.media, 'durationchange'); // Reset timer + + clearInterval(player.timers.buffering); // Setup buffering + + player.timers.buffering = setInterval(() => { + // Get loaded % from YouTube + player.media.buffered = instance.getVideoLoadedFraction(); // Trigger progress only when we actually buffer something + + if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) { + triggerEvent.call(player, player.media, 'progress'); + } // Set last buffer point + + + player.media.lastBuffered = player.media.buffered; // Bail if we're at 100% + + if (player.media.buffered === 1) { + clearInterval(player.timers.buffering); // Trigger event + + triggerEvent.call(player, player.media, 'canplaythrough'); + } + }, 200); // Rebuild UI + + if (config.customControls) { + setTimeout(() => ui.build.call(player), 50); + } + }, + + onStateChange(event) { + // Get the instance + const instance = event.target; // Reset timer + + clearInterval(player.timers.playing); + const seeked = player.media.seeking && [1, 2].includes(event.data); + + if (seeked) { + // Unset seeking and fire seeked event + player.media.seeking = false; + triggerEvent.call(player, player.media, 'seeked'); + } // Handle events + // -1 Unstarted + // 0 Ended + // 1 Playing + // 2 Paused + // 3 Buffering + // 5 Video cued + + + switch (event.data) { + case -1: + // Update scrubber + triggerEvent.call(player, player.media, 'timeupdate'); // Get loaded % from YouTube + + player.media.buffered = instance.getVideoLoadedFraction(); + triggerEvent.call(player, player.media, 'progress'); + break; + + case 0: + assurePlaybackState.call(player, false); // YouTube doesn't support loop for a single video, so mimick it. + + if (player.media.loop) { + // YouTube needs a call to `stopVideo` before playing again + instance.stopVideo(); + instance.playVideo(); + } else { + triggerEvent.call(player, player.media, 'ended'); + } + + break; + + case 1: + // Restore paused state (YouTube starts playing on seek if the video hasn't been played yet) + if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) { + player.media.pause(); + } else { + assurePlaybackState.call(player, true); + triggerEvent.call(player, player.media, 'playing'); // Poll to get playback progress + + player.timers.playing = setInterval(() => { + triggerEvent.call(player, player.media, 'timeupdate'); + }, 50); // Check duration again due to YouTube bug + // https://github.com/sampotts/plyr/issues/374 + // https://code.google.com/p/gdata-issues/issues/detail?id=8690 + + if (player.media.duration !== instance.getDuration()) { + player.media.duration = instance.getDuration(); + triggerEvent.call(player, player.media, 'durationchange'); + } + } + + break; + + case 2: + // Restore audio (YouTube starts playing on seek if the video hasn't been played yet) + if (!player.muted) { + player.embed.unMute(); + } + + assurePlaybackState.call(player, false); + break; + + case 3: + // Trigger waiting event to add loading classes to container as the video buffers. + triggerEvent.call(player, player.media, 'waiting'); + break; + } + + triggerEvent.call(player, player.elements.container, 'statechange', false, { + code: event.data + }); + } + + } + }); + } + +}; + +// ========================================================================== +const media = { + // Setup media + setup() { + // If there's no media, bail + if (!this.media) { + this.debug.warn('No media element found!'); + return; + } // Add type class + + + toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true); // Add provider class + + toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true); // Add video class for embeds + // This will require changes if audio embeds are added + + if (this.isEmbed) { + toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true); + } // Inject the player wrapper + + + if (this.isVideo) { + // Create the wrapper div + this.elements.wrapper = createElement('div', { + class: this.config.classNames.video + }); // Wrap the video in a container + + wrap(this.media, this.elements.wrapper); // Poster image container + + this.elements.poster = createElement('div', { + class: this.config.classNames.poster + }); + this.elements.wrapper.appendChild(this.elements.poster); + } + + if (this.isHTML5) { + html5.setup.call(this); + } else if (this.isYouTube) { + youtube.setup.call(this); + } else if (this.isVimeo) { + vimeo.setup.call(this); + } + } + +}; + +const destroy = instance => { + // Destroy our adsManager + if (instance.manager) { + instance.manager.destroy(); + } // Destroy our adsManager + + + if (instance.elements.displayContainer) { + instance.elements.displayContainer.destroy(); + } + + instance.elements.container.remove(); +}; + +class Ads { + /** + * Ads constructor. + * @param {Object} player + * @return {Ads} + */ + constructor(player) { + _defineProperty$1(this, "load", () => { + if (!this.enabled) { + return; + } // Check if the Google IMA3 SDK is loaded or load it ourselves + + + if (!is.object(window.google) || !is.object(window.google.ima)) { + loadScript(this.player.config.urls.googleIMA.sdk).then(() => { + this.ready(); + }).catch(() => { + // Script failed to load or is blocked + this.trigger('error', new Error('Google IMA SDK failed to load')); + }); + } else { + this.ready(); + } + }); + + _defineProperty$1(this, "ready", () => { + // Double check we're enabled + if (!this.enabled) { + destroy(this); + } // Start ticking our safety timer. If the whole advertisement + // thing doesn't resolve within our set time; we bail + + + this.startSafetyTimer(12000, 'ready()'); // Clear the safety timer + + this.managerPromise.then(() => { + this.clearSafetyTimer('onAdsManagerLoaded()'); + }); // Set listeners on the Plyr instance + + this.listeners(); // Setup the IMA SDK + + this.setupIMA(); + }); + + _defineProperty$1(this, "setupIMA", () => { + // Create the container for our advertisements + this.elements.container = createElement('div', { + class: this.player.config.classNames.ads + }); + this.player.elements.container.appendChild(this.elements.container); // So we can run VPAID2 + + google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED); // Set language + + google.ima.settings.setLocale(this.player.config.ads.language); // 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); // Create ads loader + + this.loader = new google.ima.AdsLoader(this.elements.displayContainer); // Listen and respond to ads loaded and error events + + this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false); + this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false); // Request video ads to be pre-loaded + + this.requestAds(); + }); + + _defineProperty$1(this, "requestAds", () => { + const { + container + } = this.player.elements; + + try { + // Request video ads + const request = new google.ima.AdsRequest(); + request.adTagUrl = this.tagUrl; // Specify the linear and nonlinear slot sizes. This helps the SDK + // to select the correct creative if multiple are returned + + request.linearAdSlotWidth = container.offsetWidth; + request.linearAdSlotHeight = container.offsetHeight; + request.nonLinearAdSlotWidth = container.offsetWidth; + request.nonLinearAdSlotHeight = container.offsetHeight; // We only overlay ads as we only support video. + + request.forceNonLinearFullSlot = false; // Mute based on current state + + request.setAdWillPlayMuted(!this.player.muted); + this.loader.requestAds(request); + } catch (error) { + this.onAdError(error); + } + }); + + _defineProperty$1(this, "pollCountdown", (start = false) => { + if (!start) { + clearInterval(this.countdownTimer); + this.elements.container.removeAttribute('data-badge-text'); + return; + } + + const update = () => { + const time = formatTime(Math.max(this.manager.getRemainingTime(), 0)); + const label = `${i18n.get('advertisement', this.player.config)} - ${time}`; + this.elements.container.setAttribute('data-badge-text', label); + }; + + this.countdownTimer = setInterval(update, 100); + }); + + _defineProperty$1(this, "onAdsManagerLoaded", event => { + // Load could occur after a source change (race condition) + if (!this.enabled) { + return; + } // Get the ads manager + + + const settings = new google.ima.AdsRenderingSettings(); // Tell the SDK to save and restore content video state on our behalf + + settings.restoreCustomPlaybackStateOnAdBreakComplete = true; + settings.enablePreloading = true; // The SDK is polling currentTime on the contentPlayback. And needs a duration + // so it can determine when to start the mid- and post-roll + + this.manager = event.getAdsManager(this.player, settings); // Get the cue points for any mid-rolls by filtering out the pre- and post-roll + + this.cuePoints = this.manager.getCuePoints(); // Add listeners to the required events + // Advertisement error events + + this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error)); // Advertisement regular events + + Object.keys(google.ima.AdEvent.Type).forEach(type => { + this.manager.addEventListener(google.ima.AdEvent.Type[type], e => this.onAdEvent(e)); + }); // Resolve our adsManager + + this.trigger('loaded'); + }); + + _defineProperty$1(this, "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); + } + } + }); + } + }); + + _defineProperty$1(this, "onAdEvent", event => { + const { + container + } = this.player.elements; // 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 => { + triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`); + }; // Bubble the event + + + dispatchEvent(event.type); + + switch (event.type) { + case google.ima.AdEvent.Type.LOADED: + // This is the first event sent for an ad - it is possible to determine whether the + // ad is a video ad or an overlay + this.trigger('loaded'); // Start countdown + + this.pollCountdown(true); + + if (!ad.isLinear()) { + // Position AdDisplayContainer correctly for overlay + ad.width = container.offsetWidth; + ad.height = container.offsetHeight; + } // console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex()); + // console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset()); + + + break; + + case google.ima.AdEvent.Type.STARTED: + // Set volume to match player + this.manager.setVolume(this.player.volume); + break; + + case google.ima.AdEvent.Type.ALL_ADS_COMPLETED: + // All ads for the current videos are done. We can now request new advertisements + // in case the video is re-played + // TODO: Example for what happens when a next video in a playlist would be loaded. + // So here we load a new video when all ads are done. + // Then we load new ads within a new adsManager. When the video + // Is started - after - the ads are loaded, then we get ads. + // You can also easily test cancelling and reloading by running + // player.ads.cancel() and player.ads.play from the console I guess. + // this.player.source = { + // type: 'video', + // title: 'View From A Blue Moon', + // sources: [{ + // src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type: + // 'video/mp4', }], poster: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks: + // [ { kind: 'captions', label: 'English', srclang: 'en', src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt', + // default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src: + // 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ], + // }; + // TODO: So there is still this thing where a video should only be allowed to start + // playing when the IMA SDK is ready or has failed + if (this.player.ended) { + this.loadAds(); + } else { + // The SDK won't allow new ads to be called without receiving a contentComplete() + this.loader.contentComplete(); + } + + break; + + case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED: + // This event indicates the ad has started - the video player can adjust the UI, + // for example display a pause button and remaining time. Fired when content should + // be paused. This usually happens right before an ad is about to cover the content + this.pauseContent(); + break; + + case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED: + // This event indicates the ad has finished - the video player can perform + // appropriate UI actions, such as removing the timer for remaining time detection. + // Fired when content should be resumed. This usually happens when an ad finishes + // or collapses + this.pollCountdown(); + this.resumeContent(); + break; + + case google.ima.AdEvent.Type.LOG: + if (adData.adError) { + this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`); + } + + break; + } + }); + + _defineProperty$1(this, "onAdError", event => { + this.cancel(); + this.player.debug.warn('Ads error', event); + }); + + _defineProperty$1(this, "listeners", () => { + const { + container + } = this.player.elements; + let time; + this.player.on('canplay', () => { + this.addCuePoints(); + }); + this.player.on('ended', () => { + this.loader.contentComplete(); + }); + this.player.on('timeupdate', () => { + time = this.player.currentTime; + }); + this.player.on('seeked', () => { + const seekedTime = this.player.currentTime; + + if (is.empty(this.cuePoints)) { + return; + } + + this.cuePoints.forEach((cuePoint, index) => { + if (time < cuePoint && cuePoint < seekedTime) { + this.manager.discardAdBreak(); + this.cuePoints.splice(index, 1); + } + }); + }); // Listen to the resizing of the window. And resize ad accordingly + // TODO: eventually implement ResizeObserver + + window.addEventListener('resize', () => { + if (this.manager) { + this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); + } + }); + }); + + _defineProperty$1(this, "play", () => { + const { + container + } = this.player.elements; + + if (!this.managerPromise) { + this.resumeContent(); + } // Play the requested advertisement whenever the adsManager is ready + + + this.managerPromise.then(() => { + // Set volume to match player + this.manager.setVolume(this.player.volume); // Initialize the container. Must be done via a user action on mobile devices + + this.elements.displayContainer.initialize(); + + try { + if (!this.initialized) { + // Initialize the ads manager. Ad rules playlist will start at this time + this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); // Call play to start showing the ad. Single video and overlay ads will + // start at this time; the call will be ignored for ad rules + + this.manager.start(); + } + + this.initialized = true; + } catch (adError) { + // An error may be thrown if there was a problem with the + // VAST response + this.onAdError(adError); + } + }).catch(() => {}); + }); + + _defineProperty$1(this, "resumeContent", () => { + // Hide the advertisement container + this.elements.container.style.zIndex = ''; // Ad is stopped + + this.playing = false; // Play video + + silencePromise(this.player.media.play()); + }); + + _defineProperty$1(this, "pauseContent", () => { + // Show the advertisement container + this.elements.container.style.zIndex = 3; // Ad is playing + + this.playing = true; // Pause our video. + + this.player.media.pause(); + }); + + _defineProperty$1(this, "cancel", () => { + // Pause our video + if (this.initialized) { + this.resumeContent(); + } // Tell our instance that we're done for now + + + this.trigger('error'); // Re-create our adsManager + + this.loadAds(); + }); + + _defineProperty$1(this, "loadAds", () => { + // Tell our adsManager to go bye bye + this.managerPromise.then(() => { + // Destroy our adsManager + if (this.manager) { + this.manager.destroy(); + } // Re-set our adsManager promises + + + this.managerPromise = new Promise(resolve => { + this.on('loaded', resolve); + this.player.debug.log(this.manager); + }); // Now that the manager has been destroyed set it to also be un-initialized + + this.initialized = false; // Now request some new advertisements + + this.requestAds(); + }).catch(() => {}); + }); + + _defineProperty$1(this, "trigger", (event, ...args) => { + const handlers = this.events[event]; + + if (is.array(handlers)) { + handlers.forEach(handler => { + if (is.function(handler)) { + handler.apply(this, args); + } + }); + } + }); + + _defineProperty$1(this, "on", (event, callback) => { + if (!is.array(this.events[event])) { + this.events[event] = []; + } + + this.events[event].push(callback); + return this; + }); + + _defineProperty$1(this, "startSafetyTimer", (time, from) => { + this.player.debug.log(`Safety timer invoked from: ${from}`); + this.safetyTimer = setTimeout(() => { + this.cancel(); + this.clearSafetyTimer('startSafetyTimer()'); + }, time); + }); + + _defineProperty$1(this, "clearSafetyTimer", from => { + if (!is.nullOrUndefined(this.safetyTimer)) { + this.player.debug.log(`Safety timer cleared from: ${from}`); + clearTimeout(this.safetyTimer); + this.safetyTimer = null; + } + }); + + this.player = player; + this.config = player.config.ads; + this.playing = false; + this.initialized = false; + this.elements = { + container: null, + displayContainer: null + }; + this.manager = null; + this.loader = null; + this.cuePoints = null; + this.events = {}; + this.safetyTimer = null; + this.countdownTimer = null; // Setup a promise to resolve when the IMA manager is ready + + this.managerPromise = new Promise((resolve, reject) => { + // The ad is loaded and ready + this.on('loaded', resolve); // Ads failed + + this.on('error', reject); + }); + this.load(); + } + + get enabled() { + const { + config + } = this; + return this.player.isHTML5 && this.player.isVideo && config.enabled && (!is.empty(config.publisherId) || is.url(config.tagUrl)); + } + /** + * Load the IMA SDK + */ + + + // 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', + AV_URL: window.location.hostname, + cb: Date.now(), + AV_WIDTH: 640, + AV_HEIGHT: 480, + AV_CDIM2: config.publisherId + }; + const base = 'https://go.aniview.com/api/adserver6/vast/'; + return `${base}?${buildUrlParams(params)}`; + } + /** + * In order for the SDK to display ads for our video, we need to tell it where to put them, + * so here we define our ad container. This div is set up to render on top of the video player. + * Using the code below, we tell the SDK to render ads within that div. We also provide a + * handle to the content video player - the SDK will poll the current time of our player to + * properly place mid-rolls. After we create the ad display container, we initialize it. On + * mobile devices, this initialization is done as the result of a user action. + */ + + +} + +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] || 0) * 60 * 60 + Number(matchTimes[2]) * 60 + Number(matchTimes[3]) + Number(`0.${matchTimes[4]}`); + result.endTime = Number(matchTimes[6] || 0) * 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 + */ + + +const fitRatio = (ratio, outer) => { + const targetRatio = outer.width / outer.height; + const result = {}; + + if (ratio > targetRatio) { + result.width = outer.width; + result.height = 1 / ratio * outer.width; + } else { + result.height = outer.height; + result.width = ratio * outer.height; + } + + return result; +}; + +class PreviewThumbnails { + /** + * PreviewThumbnails constructor. + * @param {Plyr} player + * @return {PreviewThumbnails} + */ + constructor(player) { + _defineProperty$1(this, "load", () => { + // Toggle the regular seek tooltip + if (this.player.elements.display.seekTooltip) { + this.player.elements.display.seekTooltip.hidden = this.enabled; + } + + if (!this.enabled) { + return; + } + + this.getThumbnails().then(() => { + if (!this.enabled) { + return; + } // Render DOM elements + + + this.render(); // Check to see if thumb container size was specified manually in CSS + + this.determineContainerAutoSizing(); + this.loaded = true; + }); + }); + + _defineProperty$1(this, "getThumbnails", () => { + return new Promise(resolve => { + const { + src + } = this.player.config.previewThumbnails; + + if (is.empty(src)) { + throw new Error('Missing previewThumbnails.src config attribute'); + } // Resolve promise + + + const sortAndResolve = () => { + // 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(); + }; // Via callback() + + + if (is.function(src)) { + src(thumbnails => { + this.thumbnails = thumbnails; + sortAndResolve(); + }); + } // VTT urls + else { + // 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)); // Resolve + + Promise.all(promises).then(sortAndResolve); + } + }); + }); + + _defineProperty$1(this, "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 the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file + + if (!thumbnail.frames[0].text.startsWith('/') && !thumbnail.frames[0].text.startsWith('http://') && !thumbnail.frames[0].text.startsWith('https://')) { + 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; + }); + }); + }); + + _defineProperty$1(this, "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(); + }); + + _defineProperty$1(this, "endMove", () => { + this.toggleThumbContainer(false, true); + }); + + _defineProperty$1(this, "startScrubbing", event => { + // Only act on left mouse button (0), or touch device (event.button does not exist or is false) + if (is.nullOrUndefined(event.button) || 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(); + } + } + }); + + _defineProperty$1(this, "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); + } + }); + } + }); + + _defineProperty$1(this, "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; + }); + }); + + _defineProperty$1(this, "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 + + if (is.element(this.player.elements.progress)) { + 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); + }); + + _defineProperty$1(this, "destroy", () => { + if (this.elements.thumb.container) { + this.elements.thumb.container.remove(); + } + + if (this.elements.scrubbing.container) { + this.elements.scrubbing.container.remove(); + } + }); + + _defineProperty$1(this, "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); + } + }); + + _defineProperty$1(this, "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); + } + }); + + _defineProperty$1(this, "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)); + }); + + _defineProperty$1(this, "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 + // eslint-disable-next-line no-param-reassign + 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); + } + }); + }); + + _defineProperty$1(this, "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); + }); + }); + + _defineProperty$1(this, "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); + } + } + }); + + _defineProperty$1(this, "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; + } + }); + + _defineProperty$1(this, "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; + } + }); + + _defineProperty$1(this, "determineContainerAutoSizing", () => { + if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) { + // This will prevent auto sizing in this.setThumbContainerSizeAndPos() + this.sizeSpecifiedInCSS = true; + } + }); + + _defineProperty$1(this, "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`; + } else if (this.elements.thumb.imageContainer.clientHeight > 20 && this.elements.thumb.imageContainer.clientWidth < 20) { + const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio); + this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`; + } else if (this.elements.thumb.imageContainer.clientHeight < 20 && this.elements.thumb.imageContainer.clientWidth > 20) { + const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio); + this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`; + } + + this.setThumbContainerPos(); + }); + + _defineProperty$1(this, "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`; + }); + + _defineProperty$1(this, "setScrubbingContainerSize", () => { + const { + width, + height + } = fitRatio(this.thumbAspectRatio, { + width: this.player.media.clientWidth, + height: this.player.media.clientHeight + }); + this.elements.scrubbing.container.style.width = `${width}px`; + this.elements.scrubbing.container.style.height = `${height}px`; + }); + + _defineProperty$1(this, "setImageSizeAndOffset", (previewImage, frame) => { + if (!this.usingSprites) { + return; + } // Find difference between height and preview container height + + + const multiplier = this.thumbContainerHeight / frame.h; // eslint-disable-next-line no-param-reassign + + previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.left = `-${frame.x * multiplier}px`; // eslint-disable-next-line no-param-reassign + + previewImage.style.top = `-${frame.y * multiplier}px`; + }); + + 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; + } + + 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) { + const { + height + } = fitRatio(this.thumbAspectRatio, { + width: this.player.media.clientWidth, + height: this.player.media.clientHeight + }); + return height; + } // If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset) + + + if (this.sizeSpecifiedInCSS) { + return this.elements.thumb.imageContainer.clientHeight; + } + + 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; + } + } + +} + +// ========================================================================== +const source = { + // Add elements to HTML5 media (source, tracks, etc) + insertElements(type, attributes) { + if (is.string(attributes)) { + insertElement(type, this.media, { + src: attributes + }); + } else if (is.array(attributes)) { + attributes.forEach(attribute => { + insertElement(type, this.media, attribute); + }); + } + }, + + // Update source + // Sources are not checked for support so be careful + change(input) { + if (!getDeep(input, 'sources.length')) { + this.debug.warn('Invalid source format'); + return; + } // Cancel current network requests + + + html5.cancelRequests.call(this); // Destroy instance and re-setup + + this.destroy.call(this, () => { + // Reset quality options + this.options.quality = []; // Remove elements + + removeElement(this.media); + this.media = null; // Reset class name + + if (is.element(this.elements.container)) { + this.elements.container.removeAttribute('class'); + } // Set the type and provider + + + const { + sources, + type + } = input; + const [{ + provider = providers.html5, + src + }] = sources; + const tagName = provider === 'html5' ? type : 'div'; + const attributes = provider === 'html5' ? {} : { + src + }; + Object.assign(this, { + provider, + type, + // Check for support + supported: support.check(type, provider, this.config.playsinline), + // Create new element + media: createElement(tagName, attributes) + }); // Inject the new element + + this.elements.container.appendChild(this.media); // Autoplay the new source? + + if (is.boolean(input.autoplay)) { + this.config.autoplay = input.autoplay; + } // Set attributes for audio and video + + + if (this.isHTML5) { + if (this.config.crossorigin) { + this.media.setAttribute('crossorigin', ''); + } + + if (this.config.autoplay) { + this.media.setAttribute('autoplay', ''); + } + + if (!is.empty(input.poster)) { + this.poster = input.poster; + } + + if (this.config.loop.active) { + this.media.setAttribute('loop', ''); + } + + if (this.config.muted) { + this.media.setAttribute('muted', ''); + } + + if (this.config.playsinline) { + this.media.setAttribute('playsinline', ''); + } + } // Restore class hook + + + ui.addStyleHook.call(this); // Set new sources for html5 + + if (this.isHTML5) { + source.insertElements.call(this, 'source', sources); + } // Set video title + + + this.config.title = input.title; // Set up from scratch + + media.setup.call(this); // HTML5 stuff + + if (this.isHTML5) { + // Setup captions + if (Object.keys(input).includes('tracks')) { + source.insertElements.call(this, 'track', input.tracks); + } + } // If HTML5 or embed but not fully supported, setupInterface and call ready now + + + if (this.isHTML5 || this.isEmbed && !this.supported.ui) { + // Setup interface + ui.build.call(this); + } // Load HTML5 sources + + + if (this.isHTML5) { + this.media.load(); + } // Update previewThumbnails config & reload plugin + + + if (!is.empty(input.previewThumbnails)) { + Object.assign(this.config.previewThumbnails, input.previewThumbnails); // Cleanup previewThumbnails plugin if it was loaded + + if (this.previewThumbnails && this.previewThumbnails.loaded) { + this.previewThumbnails.destroy(); + this.previewThumbnails = null; + } // Create new instance if it is still enabled + + + if (this.config.previewThumbnails.enabled) { + this.previewThumbnails = new PreviewThumbnails(this); + } + } // Update the fullscreen support + + + this.fullscreen.update(); + }, true); + } + +}; + +/** + * Returns a number whose value is limited to the given range. + * + * Example: limit the output of this computation to between 0 and 255 + * (x * 255).clamp(0, 255) + * + * @param {Number} input + * @param {Number} min The lower boundary of the output range + * @param {Number} max The upper boundary of the output range + * @returns A number in the range [min, max] + * @type Number + */ +function clamp(input = 0, min = 0, max = 255) { + return Math.min(Math.max(input, min), max); +} + +// TODO: Use a WeakMap for private globals +// const globals = new WeakMap(); +// Plyr instance + +class Plyr { + constructor(target, options) { + _defineProperty$1(this, "play", () => { + if (!is.function(this.media.play)) { + return null; + } // Intecept play with ads + + + if (this.ads && this.ads.enabled) { + this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play())); + } // Return the promise (for HTML5) + + + return this.media.play(); + }); + + _defineProperty$1(this, "pause", () => { + if (!this.playing || !is.function(this.media.pause)) { + return null; + } + + return this.media.pause(); + }); + + _defineProperty$1(this, "togglePlay", input => { + // Toggle based on current state if nothing passed + const toggle = is.boolean(input) ? input : !this.playing; + + if (toggle) { + return this.play(); + } + + return this.pause(); + }); + + _defineProperty$1(this, "stop", () => { + if (this.isHTML5) { + this.pause(); + this.restart(); + } else if (is.function(this.media.stop)) { + this.media.stop(); + } + }); + + _defineProperty$1(this, "restart", () => { + this.currentTime = 0; + }); + + _defineProperty$1(this, "rewind", seekTime => { + this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime; + }); + + _defineProperty$1(this, "forward", seekTime => { + this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime; + }); + + _defineProperty$1(this, "increaseVolume", step => { + const volume = this.media.muted ? 0 : this.volume; + this.volume = volume + (is.number(step) ? step : 0); + }); + + _defineProperty$1(this, "decreaseVolume", step => { + this.increaseVolume(-step); + }); + + _defineProperty$1(this, "airplay", () => { + // Show dialog if supported + if (support.airplay) { + this.media.webkitShowPlaybackTargetPicker(); + } + }); + + _defineProperty$1(this, "toggleControls", toggle => { + // Don't toggle if missing UI support or if it's audio + if (this.supported.ui && !this.isAudio) { + // Get state before change + const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls); // Negate the argument if not undefined since adding the class to hides the controls + + const force = typeof toggle === 'undefined' ? undefined : !toggle; // Apply and get updated state + + const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force); // Close menu + + if (hiding && is.array(this.config.controls) && this.config.controls.includes('settings') && !is.empty(this.config.settings)) { + controls.toggleMenu.call(this, false); + } // Trigger event on change + + + if (hiding !== isHidden) { + const eventName = hiding ? 'controlshidden' : 'controlsshown'; + triggerEvent.call(this, this.media, eventName); + } + + return !hiding; + } + + return false; + }); + + _defineProperty$1(this, "on", (event, callback) => { + on.call(this, this.elements.container, event, callback); + }); + + _defineProperty$1(this, "once", (event, callback) => { + once.call(this, this.elements.container, event, callback); + }); + + _defineProperty$1(this, "off", (event, callback) => { + off(this.elements.container, event, callback); + }); + + _defineProperty$1(this, "destroy", (callback, soft = false) => { + if (!this.ready) { + return; + } + + const done = () => { + // Reset overflow (incase destroyed while in fullscreen) + document.body.style.overflow = ''; // GC for embed + + this.embed = null; // If it's a soft destroy, make minimal changes + + if (soft) { + if (Object.keys(this.elements).length) { + // Remove elements + removeElement(this.elements.buttons.play); + removeElement(this.elements.captions); + removeElement(this.elements.controls); + removeElement(this.elements.wrapper); // Clear for GC + + this.elements.buttons.play = null; + this.elements.captions = null; + this.elements.controls = null; + this.elements.wrapper = null; + } // Callback + + + if (is.function(callback)) { + callback(); + } + } else { + // Unbind listeners + unbindListeners.call(this); // Cancel current network requests + + html5.cancelRequests.call(this); // Replace the container with the original element provided + + replaceElement(this.elements.original, this.elements.container); // Event + + triggerEvent.call(this, this.elements.original, 'destroyed', true); // Callback + + if (is.function(callback)) { + callback.call(this.elements.original); + } // Reset state + + + this.ready = false; // Clear for garbage collection + + setTimeout(() => { + this.elements = null; + this.media = null; + }, 200); + } + }; // Stop playback + + + this.stop(); // Clear timeouts + + clearTimeout(this.timers.loading); + clearTimeout(this.timers.controls); + clearTimeout(this.timers.resized); // Provider specific stuff + + if (this.isHTML5) { + // Restore native video controls + ui.toggleNativeControls.call(this, true); // Clean up + + done(); + } else if (this.isYouTube) { + // Clear timers + clearInterval(this.timers.buffering); + clearInterval(this.timers.playing); // Destroy YouTube API + + if (this.embed !== null && is.function(this.embed.destroy)) { + this.embed.destroy(); + } // Clean up + + + done(); + } else if (this.isVimeo) { + // Destroy Vimeo API + // then clean up (wait, to prevent postmessage errors) + if (this.embed !== null) { + this.embed.unload().then(done); + } // Vimeo does not always return + + + setTimeout(done, 200); + } + }); + + _defineProperty$1(this, "supports", type => support.mime.call(this, type)); + + this.timers = {}; // State + + this.ready = false; + this.loading = false; + this.failed = false; // Touch device + + this.touch = support.touch; // Set the media element + + this.media = target; // String selector passed + + if (is.string(this.media)) { + this.media = document.querySelectorAll(this.media); + } // jQuery, NodeList or Array passed, use first element + + + if (window.jQuery && this.media instanceof jQuery || is.nodeList(this.media) || is.array(this.media)) { + // eslint-disable-next-line + this.media = this.media[0]; + } // Set config + + + this.config = extend({}, defaults, Plyr.defaults, options || {}, (() => { + try { + return JSON.parse(this.media.getAttribute('data-plyr-config')); + } catch (_) { + return {}; + } + })()); // Elements cache + + this.elements = { + container: null, + fullscreen: null, + captions: null, + buttons: {}, + display: {}, + progress: {}, + inputs: {}, + settings: { + popup: null, + menu: null, + panels: {}, + buttons: {} + } + }; // Captions + + this.captions = { + active: null, + currentTrack: -1, + meta: new WeakMap() + }; // Fullscreen + + this.fullscreen = { + active: false + }; // Options + + this.options = { + speed: [], + quality: [] + }; // Debugging + // TODO: move to globals + + this.debug = new Console(this.config.debug); // Log config options and support + + this.debug.log('Config', this.config); + this.debug.log('Support', support); // We need an element to setup + + if (is.nullOrUndefined(this.media) || !is.element(this.media)) { + this.debug.error('Setup failed: no suitable element passed'); + return; + } // Bail if the element is initialized + + + if (this.media.plyr) { + this.debug.warn('Target already setup'); + return; + } // Bail if not enabled + + + if (!this.config.enabled) { + this.debug.error('Setup failed: disabled by config'); + return; + } // Bail if disabled or no basic support + // You may want to disable certain UAs etc + + + if (!support.check().api) { + this.debug.error('Setup failed: no support'); + return; + } // Cache original element state for .destroy() + + + const clone = this.media.cloneNode(true); + clone.autoplay = false; + this.elements.original = clone; // Set media type based on tag or data attribute + // Supported: video, audio, vimeo, youtube + + const _type = this.media.tagName.toLowerCase(); // Embed properties + + + let iframe = null; + let url = null; // Different setup based on type + + switch (_type) { + case 'div': + // Find the frame + iframe = this.media.querySelector('iframe'); // <iframe> type + + if (is.element(iframe)) { + // Detect provider + url = parseUrl(iframe.getAttribute('src')); + this.provider = getProviderByUrl(url.toString()); // Rework elements + + this.elements.container = this.media; + this.media = iframe; // Reset classname + + this.elements.container.className = ''; // Get attributes from URL and set config + + if (url.search.length) { + const truthy = ['1', 'true']; + + if (truthy.includes(url.searchParams.get('autoplay'))) { + this.config.autoplay = true; + } + + if (truthy.includes(url.searchParams.get('loop'))) { + this.config.loop.active = true; + } // TODO: replace fullscreen.iosNative with this playsinline config option + // YouTube requires the playsinline in the URL + + + if (this.isYouTube) { + this.config.playsinline = truthy.includes(url.searchParams.get('playsinline')); + this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language? + } else { + this.config.playsinline = true; + } + } + } else { + // <div> with attributes + this.provider = this.media.getAttribute(this.config.attributes.embed.provider); // Remove attribute + + this.media.removeAttribute(this.config.attributes.embed.provider); + } // Unsupported or missing provider + + + if (is.empty(this.provider) || !Object.values(providers).includes(this.provider)) { + this.debug.error('Setup failed: Invalid provider'); + return; + } // Audio will come later for external providers + + + this.type = types.video; + break; + + case 'video': + case 'audio': + this.type = _type; + this.provider = providers.html5; // Get config from attributes + + if (this.media.hasAttribute('crossorigin')) { + this.config.crossorigin = true; + } + + if (this.media.hasAttribute('autoplay')) { + this.config.autoplay = true; + } + + if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) { + this.config.playsinline = true; + } + + if (this.media.hasAttribute('muted')) { + this.config.muted = true; + } + + if (this.media.hasAttribute('loop')) { + this.config.loop.active = true; + } + + break; + + default: + this.debug.error('Setup failed: unsupported type'); + return; + } // Check for support again but with type + + + this.supported = support.check(this.type, this.provider, this.config.playsinline); // If no support for even API, bail + + if (!this.supported.api) { + this.debug.error('Setup failed: no support'); + return; + } + + this.eventListeners = []; // Create listeners + + this.listeners = new Listeners(this); // Setup local storage for user settings + + this.storage = new Storage(this); // Store reference + + this.media.plyr = this; // Wrap media + + if (!is.element(this.elements.container)) { + this.elements.container = createElement('div', { + tabindex: 0 + }); + wrap(this.media, this.elements.container); + } // Migrate custom properties from media to container (so they work 😉) + + + ui.migrateStyles.call(this); // Add style hook + + ui.addStyleHook.call(this); // Setup media + + media.setup.call(this); // Listen for events if debugging + + if (this.config.debug) { + on.call(this, this.elements.container, this.config.events.join(' '), event => { + this.debug.log(`event: ${event.type}`); + }); + } // Setup fullscreen + + + this.fullscreen = new Fullscreen(this); // Setup interface + // If embed but not fully supported, build interface now to avoid flash of controls + + if (this.isHTML5 || this.isEmbed && !this.supported.ui) { + ui.build.call(this); + } // Container listeners + + + this.listeners.container(); // Global listeners + + this.listeners.global(); // Setup ads if provided + + if (this.config.ads.enabled) { + this.ads = new Ads(this); + } // Autoplay if required + + + if (this.isHTML5 && this.config.autoplay) { + this.once('canplay', () => silencePromise(this.play())); + } // 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); + } + } // --------------------------------------- + // API + // --------------------------------------- + + /** + * Types and provider helpers + */ + + + get isHTML5() { + return this.provider === providers.html5; + } + + get isEmbed() { + return this.isYouTube || this.isVimeo; + } + + get isYouTube() { + return this.provider === providers.youtube; + } + + get isVimeo() { + return this.provider === providers.vimeo; + } + + get isVideo() { + return this.type === types.video; + } + + get isAudio() { + return this.type === types.audio; + } + /** + * Play the media, or play the advertisement (if they are not blocked) + */ + + + /** + * Get playing state + */ + get playing() { + return Boolean(this.ready && !this.paused && !this.ended); + } + /** + * Get paused state + */ + + + get paused() { + return Boolean(this.media.paused); + } + /** + * Get stopped state + */ + + + get stopped() { + return Boolean(this.paused && this.currentTime === 0); + } + /** + * Get ended state + */ + + + get ended() { + return Boolean(this.media.ended); + } + /** + * Toggle playback based on current status + * @param {Boolean} input + */ + + + /** + * Seek to a time + * @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 + if (!this.duration) { + return; + } // Validate input + + + const inputIsValid = is.number(input) && input > 0; // Set + + this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0; // Logging + + this.debug.log(`Seeking to ${this.currentTime} seconds`); + } + /** + * Get current time + */ + + + get currentTime() { + return Number(this.media.currentTime); + } + /** + * Get buffered + */ + + + get buffered() { + const { + buffered + } = this.media; // YouTube / Vimeo return a float between 0-1 + + if (is.number(buffered)) { + return buffered; + } // HTML5 + // TODO: Handle buffered chunks of the media + // (i.e. seek to another section buffers only that section) + + + if (buffered && buffered.length && this.duration > 0) { + return buffered.end(0) / this.duration; + } + + return 0; + } + /** + * Get seeking status + */ + + + get seeking() { + return Boolean(this.media.seeking); + } + /** + * Get the duration of the current media + */ + + + get duration() { + // Faux duration set via config + const fauxDuration = parseFloat(this.config.duration); // Media duration can be NaN or Infinity before the media has loaded + + const realDuration = (this.media || {}).duration; + const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration; // If config duration is funky, use regular duration + + return fauxDuration || duration; + } + /** + * 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 + */ + + + set volume(value) { + let volume = value; + const max = 1; + const min = 0; + + if (is.string(volume)) { + volume = Number(volume); + } // Load volume from storage if no value specified + + + if (!is.number(volume)) { + volume = this.storage.get('volume'); + } // Use config if all else fails + + + if (!is.number(volume)) { + ({ + volume + } = this.config); + } // Maximum is volumeMax + + + if (volume > max) { + volume = max; + } // Minimum is volumeMin + + + if (volume < min) { + volume = min; + } // Update config + + + this.config.volume = volume; // Set the player volume + + this.media.volume = volume; // If muted, and we're increasing volume manually, reset muted state + + if (!is.empty(value) && this.muted && volume > 0) { + this.muted = false; + } + } + /** + * Get the current player volume + */ + + + get volume() { + return Number(this.media.volume); + } + /** + * Increase volume + * @param {Boolean} step - How much to decrease by (between 0 and 1) + */ + + + /** + * Set muted state + * @param {Boolean} mute + */ + set muted(mute) { + let toggle = mute; // Load muted state from storage + + if (!is.boolean(toggle)) { + toggle = this.storage.get('muted'); + } // Use config if all else fails + + + if (!is.boolean(toggle)) { + toggle = this.config.muted; + } // Update config + + + this.config.muted = toggle; // Set mute on the player + + this.media.muted = toggle; + } + /** + * Get current muted state + */ + + + get muted() { + return Boolean(this.media.muted); + } + /** + * Check if the media has audio + */ + + + get hasAudio() { + // Assume yes for all non HTML5 (as we can't tell...) + if (!this.isHTML5) { + return true; + } + + if (this.isAudio) { + return true; + } // Get audio tracks + + + return Boolean(this.media.mozHasAudio) || Boolean(this.media.webkitAudioDecodedByteCount) || Boolean(this.media.audioTracks && this.media.audioTracks.length); + } + /** + * Set playback speed + * @param {Number} speed - the speed of playback (0.5-2.0) + */ + + + set speed(input) { + let speed = null; + + if (is.number(input)) { + speed = input; + } + + if (!is.number(speed)) { + speed = this.storage.get('speed'); + } + + if (!is.number(speed)) { + speed = this.config.speed.selected; + } // Clamp to min/max + + + const { + minimumSpeed: min, + maximumSpeed: max + } = this; + speed = clamp(speed, min, max); // Update config + + this.config.speed.selected = speed; // Set media speed + + setTimeout(() => { + if (this.media) { + this.media.playbackRate = speed; + } + }, 0); + } + /** + * Get current playback speed + */ + + + get speed() { + return Number(this.media.playbackRate); + } + /** + * Get the minimum allowed speed + */ + + + get minimumSpeed() { + if (this.isYouTube) { + // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate + return Math.min(...this.options.speed); + } + + if (this.isVimeo) { + // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror + return 0.5; + } // https://stackoverflow.com/a/32320020/1191319 + + + return 0.0625; + } + /** + * Get the maximum allowed speed + */ + + + get maximumSpeed() { + if (this.isYouTube) { + // https://developers.google.com/youtube/iframe_api_reference#setPlaybackRate + return Math.max(...this.options.speed); + } + + if (this.isVimeo) { + // https://github.com/vimeo/player.js/#setplaybackrateplaybackrate-number-promisenumber-rangeerrorerror + return 2; + } // https://stackoverflow.com/a/32320020/1191319 + + + return 16; + } + /** + * Set playback quality + * Currently HTML5 & YouTube only + * @param {Number} input - Quality level + */ + + + set quality(input) { + const config = this.config.quality; + const options = this.options.quality; + + if (!options.length) { + return; + } + + let quality = [!is.empty(input) && Number(input), this.storage.get('quality'), config.selected, config.default].find(is.number); + let updateStorage = true; + + if (!options.includes(quality)) { + const value = closest(options, quality); + this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`); + quality = value; // Don't update storage if quality is not supported + + updateStorage = false; + } // Update config + + + config.selected = quality; // Set quality + + this.media.quality = quality; // Save to storage + + if (updateStorage) { + this.storage.set({ + quality + }); + } + } + /** + * Get current quality level + */ + + + get quality() { + return this.media.quality; + } + /** + * 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 + */ + + + set loop(input) { + const toggle = is.boolean(input) ? input : this.config.loop.active; + this.config.loop.active = toggle; + this.media.loop = toggle; // Set default to be a true toggle + + /* const type = ['start', 'end', 'all', 'none', 'toggle'].includes(input) ? input : 'toggle'; + switch (type) { + case 'start': + if (this.config.loop.end && this.config.loop.end <= this.currentTime) { + this.config.loop.end = null; + } + this.config.loop.start = this.currentTime; + // this.config.loop.indicator.start = this.elements.display.played.value; + break; + case 'end': + if (this.config.loop.start >= this.currentTime) { + return this; + } + this.config.loop.end = this.currentTime; + // this.config.loop.indicator.end = this.elements.display.played.value; + break; + case 'all': + this.config.loop.start = 0; + this.config.loop.end = this.duration - 2; + this.config.loop.indicator.start = 0; + this.config.loop.indicator.end = 100; + break; + case 'toggle': + if (this.config.loop.active) { + this.config.loop.start = 0; + this.config.loop.end = null; + } else { + this.config.loop.start = 0; + this.config.loop.end = this.duration - 2; + } + break; + default: + this.config.loop.start = 0; + this.config.loop.end = null; + break; + } */ + } + /** + * Get current loop state + */ + + + get loop() { + return Boolean(this.media.loop); + } + /** + * Set new media source + * @param {Object} input - The new source object (see docs) + */ + + + set source(input) { + source.change.call(this, input); + } + /** + * Get current source + */ + + + get source() { + return this.media.currentSrc; + } + /** + * Get a download URL (either source or custom) + */ + + + get download() { + const { + download + } = this.config.urls; + return is.url(download) ? download : this.source; + } + /** + * Set the download URL + */ + + + set download(input) { + if (!is.url(input)) { + return; + } + + this.config.urls.download = input; + controls.setDownloadUrl.call(this); + } + /** + * Set the poster image for a video + * @param {String} input - the URL for the new poster image + */ + + + set poster(input) { + if (!this.isVideo) { + this.debug.warn('Poster can only be set for video'); + return; + } + + ui.setPoster.call(this, input, false).catch(() => {}); + } + /** + * Get the current poster image + */ + + + get poster() { + if (!this.isVideo) { + return null; + } + + return this.media.getAttribute('poster') || this.media.getAttribute('data-poster'); + } + /** + * Get the current aspect ratio in use + */ + + + get ratio() { + if (!this.isVideo) { + return null; + } + + const ratio = reduceAspectRatio(getAspectRatio.call(this)); + return is.array(ratio) ? ratio.join(':') : ratio; + } + /** + * Set video aspect ratio + */ + + + set ratio(input) { + if (!this.isVideo) { + this.debug.warn('Aspect ratio can only be set for video'); + return; + } + + if (!is.string(input) || !validateAspectRatio(input)) { + this.debug.error(`Invalid aspect ratio specified (${input})`); + return; + } + + this.config.ratio = reduceAspectRatio(input); + setAspectRatio.call(this); + } + /** + * Set the autoplay state + * @param {Boolean} input - Whether to autoplay or not + */ + + + set autoplay(input) { + const toggle = is.boolean(input) ? input : this.config.autoplay; + this.config.autoplay = toggle; + } + /** + * Get the current autoplay state + */ + + + get autoplay() { + return Boolean(this.config.autoplay); + } + /** + * Toggle captions + * @param {Boolean} input - Whether to enable captions + */ + + + toggleCaptions(input) { + captions.toggle.call(this, input, false); + } + /** + * Set the caption track by index + * @param {Number} - Caption index + */ + + + set currentTrack(input) { + captions.set.call(this, input, false); + captions.setup(); + } + /** + * Get the current caption track index (-1 if disabled) + */ + + + get currentTrack() { + const { + toggled, + currentTrack + } = this.captions; + return toggled ? currentTrack : -1; + } + /** + * 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) + */ + + + set language(input) { + captions.setLanguage.call(this, input, false); + } + /** + * Get the current track's language + */ + + + get language() { + return (captions.getCurrentTrack.call(this) || {}).language; + } + /** + * Toggle picture-in-picture playback on WebKit/MacOS + * TODO: update player with state, support, enabled + * TODO: detect outside changes + */ + + + set pip(input) { + // Bail if no support + if (!support.pip) { + return; + } // Toggle based on current state if not passed + + + const toggle = is.boolean(input) ? input : !this.pip; // Toggle based on current state + // Safari + + if (is.function(this.media.webkitSetPresentationMode)) { + this.media.webkitSetPresentationMode(toggle ? pip.active : pip.inactive); + } // Chrome + + + if (is.function(this.media.requestPictureInPicture)) { + if (!this.pip && toggle) { + this.media.requestPictureInPicture(); + } else if (this.pip && !toggle) { + document.exitPictureInPicture(); + } + } + } + /** + * Get the current picture-in-picture state + */ + + + get pip() { + if (!support.pip) { + return null; + } // Safari + + + if (!is.empty(this.media.webkitPresentationMode)) { + return this.media.webkitPresentationMode === pip.active; + } // Chrome + + + return this.media === document.pictureInPictureElement; + } + /** + * Sets the preview thubmnails for the current source + */ + + + setPreviewThumbnails(thumbnailSource) { + if (this.previewThumbnails && this.previewThumbnails.loaded) { + this.previewThumbnails.destroy(); + this.previewThumbnails = null; + } + + Object.assign(this.config.previewThumbnails, thumbnailSource); // Create new instance if it is still enabled + + if (this.config.previewThumbnails.enabled) { + this.previewThumbnails = new PreviewThumbnails(this); + } + } + /** + * Trigger the airplay dialog + * TODO: update player with state, support, enabled + */ + + + /** + * Check for support + * @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); + } + /** + * Load an SVG sprite into the page + * @param {String} url - URL for the SVG sprite + * @param {String} [id] - Unique ID + */ + + + static loadSprite(url, id) { + return loadSprite(url, id); + } + /** + * Setup multiple instances + * @param {*} selector + * @param {Object} options + */ + + + static setup(selector, options = {}) { + let targets = null; + + if (is.string(selector)) { + targets = Array.from(document.querySelectorAll(selector)); + } else if (is.nodeList(selector)) { + targets = Array.from(selector); + } else if (is.array(selector)) { + targets = selector.filter(is.element); + } + + if (is.empty(targets)) { + return null; + } + + return targets.map(t => new Plyr(t, options)); + } + +} + +Plyr.defaults = cloneDeep(defaults); + +// ========================================================================== + +export { Plyr as default }; diff --git a/extlib/plyr/plyr.svg b/extlib/plyr/plyr.svg new file mode 100644 index 00000000..62ab2579 --- /dev/null +++ b/extlib/plyr/plyr.svg @@ -0,0 +1 @@ +<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><symbol id="plyr-airplay" viewBox="0 0 18 18"><path d="M16 1H2a1 1 0 00-1 1v10a1 1 0 001 1h3v-2H3V3h12v8h-2v2h3a1 1 0 001-1V2a1 1 0 00-1-1z"/><path d="M4 17h10l-5-6z"/></symbol><symbol id="plyr-captions-off" viewBox="0 0 18 18"><path d="M1 1c-.6 0-1 .4-1 1v11c0 .6.4 1 1 1h4.6l2.7 2.7c.2.2.4.3.7.3.3 0 .5-.1.7-.3l2.7-2.7H17c.6 0 1-.4 1-1V2c0-.6-.4-1-1-1H1zm4.52 10.15c1.99 0 3.01-1.32 3.28-2.41l-1.29-.39c-.19.66-.78 1.45-1.99 1.45-1.14 0-2.2-.83-2.2-2.34 0-1.61 1.12-2.37 2.18-2.37 1.23 0 1.78.75 1.95 1.43l1.3-.41C8.47 4.96 7.46 3.76 5.5 3.76c-1.9 0-3.61 1.44-3.61 3.7 0 2.26 1.65 3.69 3.63 3.69zm7.57 0c1.99 0 3.01-1.32 3.28-2.41l-1.29-.39c-.19.66-.78 1.45-1.99 1.45-1.14 0-2.2-.83-2.2-2.34 0-1.61 1.12-2.37 2.18-2.37 1.23 0 1.78.75 1.95 1.43l1.3-.41c-.28-1.15-1.29-2.35-3.25-2.35-1.9 0-3.61 1.44-3.61 3.7 0 2.26 1.65 3.69 3.63 3.69z" fill-rule="evenodd" fill-opacity=".5"/></symbol><symbol id="plyr-captions-on" viewBox="0 0 18 18"><path d="M1 1c-.6 0-1 .4-1 1v11c0 .6.4 1 1 1h4.6l2.7 2.7c.2.2.4.3.7.3.3 0 .5-.1.7-.3l2.7-2.7H17c.6 0 1-.4 1-1V2c0-.6-.4-1-1-1H1zm4.52 10.15c1.99 0 3.01-1.32 3.28-2.41l-1.29-.39c-.19.66-.78 1.45-1.99 1.45-1.14 0-2.2-.83-2.2-2.34 0-1.61 1.12-2.37 2.18-2.37 1.23 0 1.78.75 1.95 1.43l1.3-.41C8.47 4.96 7.46 3.76 5.5 3.76c-1.9 0-3.61 1.44-3.61 3.7 0 2.26 1.65 3.69 3.63 3.69zm7.57 0c1.99 0 3.01-1.32 3.28-2.41l-1.29-.39c-.19.66-.78 1.45-1.99 1.45-1.14 0-2.2-.83-2.2-2.34 0-1.61 1.12-2.37 2.18-2.37 1.23 0 1.78.75 1.95 1.43l1.3-.41c-.28-1.15-1.29-2.35-3.25-2.35-1.9 0-3.61 1.44-3.61 3.7 0 2.26 1.65 3.69 3.63 3.69z" fill-rule="evenodd"/></symbol><symbol id="plyr-download" viewBox="0 0 18 18"><path d="M9 13c.3 0 .5-.1.7-.3L15.4 7 14 5.6l-4 4V1H8v8.6l-4-4L2.6 7l5.7 5.7c.2.2.4.3.7.3zm-7 2h14v2H2z"/></symbol><symbol id="plyr-enter-fullscreen" viewBox="0 0 18 18"><path d="M10 3h3.6l-4 4L11 8.4l4-4V8h2V1h-7zM7 9.6l-4 4V10H1v7h7v-2H4.4l4-4z"/></symbol><symbol id="plyr-exit-fullscreen" viewBox="0 0 18 18"><path d="M1 12h3.6l-4 4L2 17.4l4-4V17h2v-7H1zM16 .6l-4 4V1h-2v7h7V6h-3.6l4-4z"/></symbol><symbol id="plyr-fast-forward" viewBox="0 0 18 18"><path d="M7.875 7.171L0 1v16l7.875-6.171V17L18 9 7.875 1z"/></symbol><symbol id="plyr-logo-vimeo" viewBox="0 0 18 18"><path d="M17 5.3c-.1 1.6-1.2 3.7-3.3 6.4-2.2 2.8-4 4.2-5.5 4.2-.9 0-1.7-.9-2.4-2.6C5 10.9 4.4 6 3 6c-.1 0-.5.3-1.2.8l-.8-1c.8-.7 3.5-3.4 4.7-3.5 1.2-.1 2 .7 2.3 2.5.3 2 .8 6.1 1.8 6.1.9 0 2.5-3.4 2.6-4 .1-.9-.3-1.9-2.3-1.1.8-2.6 2.3-3.8 4.5-3.8 1.7.1 2.5 1.2 2.4 3.3z"/></symbol><symbol id="plyr-logo-youtube" viewBox="0 0 18 18"><path d="M16.8 5.8c-.2-1.3-.8-2.2-2.2-2.4C12.4 3 9 3 9 3s-3.4 0-5.6.4C2 3.6 1.3 4.5 1.2 5.8 1 7.1 1 9 1 9s0 1.9.2 3.2c.2 1.3.8 2.2 2.2 2.4C5.6 15 9 15 9 15s3.4 0 5.6-.4c1.4-.3 2-1.1 2.2-2.4.2-1.3.2-3.2.2-3.2s0-1.9-.2-3.2zM7 12V6l5 3-5 3z"/></symbol><symbol id="plyr-muted" viewBox="0 0 18 18"><path d="M12.4 12.5l2.1-2.1 2.1 2.1 1.4-1.4L15.9 9 18 6.9l-1.4-1.4-2.1 2.1-2.1-2.1L11 6.9 13.1 9 11 11.1zM3.786 6.008H.714C.286 6.008 0 6.31 0 6.76v4.512c0 .452.286.752.714.752h3.072l4.071 3.858c.5.3 1.143 0 1.143-.602V2.752c0-.601-.643-.977-1.143-.601L3.786 6.008z"/></symbol><symbol id="plyr-pause" viewBox="0 0 18 18"><path d="M6 1H3c-.6 0-1 .4-1 1v14c0 .6.4 1 1 1h3c.6 0 1-.4 1-1V2c0-.6-.4-1-1-1zm6 0c-.6 0-1 .4-1 1v14c0 .6.4 1 1 1h3c.6 0 1-.4 1-1V2c0-.6-.4-1-1-1h-3z"/></symbol><symbol id="plyr-pip" viewBox="0 0 18 18"><path d="M13.293 3.293L7.022 9.564l1.414 1.414 6.271-6.271L17 7V1h-6z"/><path d="M13 15H3V5h5V3H2a1 1 0 00-1 1v12a1 1 0 001 1h12a1 1 0 001-1v-6h-2v5z"/></symbol><symbol id="plyr-play" viewBox="0 0 18 18"><path d="M15.562 8.1L3.87.225c-.818-.562-1.87 0-1.87.9v15.75c0 .9 1.052 1.462 1.87.9L15.563 9.9c.584-.45.584-1.35 0-1.8z"/></symbol><symbol id="plyr-restart" viewBox="0 0 18 18"><path d="M9.7 1.2l.7 6.4 2.1-2.1c1.9 1.9 1.9 5.1 0 7-.9 1-2.2 1.5-3.5 1.5-1.3 0-2.6-.5-3.5-1.5-1.9-1.9-1.9-5.1 0-7 .6-.6 1.4-1.1 2.3-1.3l-.6-1.9C6 2.6 4.9 3.2 4 4.1 1.3 6.8 1.3 11.2 4 14c1.3 1.3 3.1 2 4.9 2 1.9 0 3.6-.7 4.9-2 2.7-2.7 2.7-7.1 0-9.9L16 1.9l-6.3-.7z"/></symbol><symbol id="plyr-rewind" viewBox="0 0 18 18"><path d="M10.125 1L0 9l10.125 8v-6.171L18 17V1l-7.875 6.171z"/></symbol><symbol id="plyr-settings" viewBox="0 0 18 18"><path d="M16.135 7.784a2 2 0 01-1.23-2.969c.322-.536.225-.998-.094-1.316l-.31-.31c-.318-.318-.78-.415-1.316-.094a2 2 0 01-2.969-1.23C10.065 1.258 9.669 1 9.219 1h-.438c-.45 0-.845.258-.997.865a2 2 0 01-2.969 1.23c-.536-.322-.999-.225-1.317.093l-.31.31c-.318.318-.415.781-.093 1.317a2 2 0 01-1.23 2.969C1.26 7.935 1 8.33 1 8.781v.438c0 .45.258.845.865.997a2 2 0 011.23 2.969c-.322.536-.225.998.094 1.316l.31.31c.319.319.782.415 1.316.094a2 2 0 012.969 1.23c.151.607.547.865.997.865h.438c.45 0 .845-.258.997-.865a2 2 0 012.969-1.23c.535.321.997.225 1.316-.094l.31-.31c.318-.318.415-.781.094-1.316a2 2 0 011.23-2.969c.607-.151.865-.547.865-.997v-.438c0-.451-.26-.846-.865-.997zM9 12a3 3 0 110-6 3 3 0 010 6z"/></symbol><symbol id="plyr-volume" viewBox="0 0 18 18"><path d="M15.6 3.3c-.4-.4-1-.4-1.4 0-.4.4-.4 1 0 1.4C15.4 5.9 16 7.4 16 9c0 1.6-.6 3.1-1.8 4.3-.4.4-.4 1 0 1.4.2.2.5.3.7.3.3 0 .5-.1.7-.3C17.1 13.2 18 11.2 18 9s-.9-4.2-2.4-5.7z"/><path d="M11.282 5.282a.909.909 0 000 1.316c.735.735.995 1.458.995 2.402 0 .936-.425 1.917-.995 2.487a.909.909 0 000 1.316c.145.145.636.262 1.018.156a.725.725 0 00.298-.156C13.773 11.733 14.13 10.16 14.13 9c0-.17-.002-.34-.011-.51-.053-.992-.319-2.005-1.522-3.208a.909.909 0 00-1.316 0zm-7.496.726H.714C.286 6.008 0 6.31 0 6.76v4.512c0 .452.286.752.714.752h3.072l4.071 3.858c.5.3 1.143 0 1.143-.602V2.752c0-.601-.643-.977-1.143-.601L3.786 6.008z"/></symbol></svg>
\ No newline at end of file diff --git a/guix-env.scm b/guix-env.scm index b0c0a171..37a67359 100644 --- a/guix-env.scm +++ b/guix-env.scm @@ -52,12 +52,6 @@ ;;; ./configure --without-virtualenv ;;; make ;;; -;;; The devtools/update_extlib.sh script won't run on Guix due to missing -;;; "/usr/bin/env", so again for first time setup only, run: -;;; -;;; node node_modules/.bin/bower install -;;; ./devtools/update_extlib.sh -;;; ;;; For first time setup only with a regular `guix environment` or an ;;; `environment --pure`, but required EACH TIME you start an `environment ;;; --container` (because the generated profile goes away, breaking the links in diff --git a/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_head.html b/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_head.html index 495382f5..a984be58 100644 --- a/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_head.html +++ b/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_head.html @@ -1,23 +1,25 @@ -<script type="text/javascript" src="{{ - request.staticdirect('/extlib/video-js/video.js') }}"></script> -{# Sadly commented out till we can get the mediagoblin skin ported over - # to the newest video.js release ;\ #} -{# - <link href="{{ request.staticdirect('/css/vjs-mg-skin.css') }}" - rel="stylesheet"> -#} -<link href="{{ - request.staticdirect('/extlib/video-js/video-js.css') }}" - rel="stylesheet"> - -<style type="text/css"> - .vjs-default-skin .vjs-big-play-button - { - top: 50%; - left: 50%; - margin: -1.5em auto auto -2em; - } - .vjs-play-progress, .vjs-volume-level { - background-color: #86D4B1 !important; - } +<link href="{{ request.staticdirect('/extlib/plyr/plyr.css') }}" rel="stylesheet"> +<style> + video { + width: 100%; + } + .responsive-container { + display: inline; + } + /* plyr fix */ + .plyr:-moz-full-screen video { + max-height: initial; + } + .plyr:-webkit-full-screen video { + max-height: initial; + } + .plyr:-ms-fullscreen video { + max-height: initial; + } + .plyr:fullscreen video { + max-height: initial; + } + .plyr video { + max-height: 360px; + } </style> diff --git a/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_primary.html b/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_primary.html index 58d8c549..5de6a6cc 100644 --- a/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_primary.html +++ b/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_primary.html @@ -16,38 +16,68 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. #} -{% from "archivalook/utils/display_featured.html" import - possibly_shortened_description %} +{% from "archivalook/utils/display_featured.html" import possibly_shortened_description %} {%- set media = feature.media_entry %} {%- set display_media = request.app.public_store.file_url( - media.get_display_media()[1]) %} + media.get_display_media()[1]) %} {%- set entry_url = media.url_for_self(request.urlgen) %} <div class="primary-feature"> - <a href="{{ entry_url }}"> - <p class="f-title">{{ media.title }}</p> - </a> - <div class="f-display"> - {%- set display_type, display_path = media.get_display_media() %} - <video controls - {% if global_config['plugins']['mediagoblin.media_types.video']['auto_play'] %}autoplay{% endif %} - preload="metadata" class="video-js vjs-default-skin"> - <source src="{{ request.app.public_store.file_url(display_path) }}" - {% if media.media_data %} - type="{{ media.media_data.source_type() }}" - {% else %} - type="{{ media.media_manager['default_webm_type'] }}" - {% endif %} /> - <div class="no_html5"> - {%- trans -%}Sorry, this video will not work because - your web browser does not support HTML5 - video.{%- endtrans -%}<br/> - {%- trans -%}You can get a modern web browser that - can play this video at <a href="http://getfirefox.com"> - http://getfirefox.com</a>!{%- endtrans -%} - </div> - </video> - </div> - {{ possibly_shortened_description(request, feature.media_entry) }} + <a href="{{ entry_url }}"> + <p class="f-title">{{ media.title }}</p> + </a> + <div class="f-display" id="player"> + {%- set display_type, display_path = media.get_display_media() %} + <video controls playsinline + {% if global_config['plugins']['mediagoblin.media_types.video']['auto_play'] %}autoplay{% endif %} + preload="metadata" id="js-video-player"> + <source src="{{ request.app.public_store.file_url(display_path) }}" + {% if media.media_data %} + type="{{ media.media_data.source_type() }}" + {% else %} + type="{{ media.media_manager['default_webm_type'] }}" + {% endif %} /> + <div class="no_html5"> + {%- trans -%}Sorry, this video will not work because + your web browser does not support HTML5 + video.{%- endtrans -%}<br/> + {%- trans -%}You can get a modern web browser that + can play this video at <a href="http://getfirefox.com"> + http://getfirefox.com</a>!{%- endtrans -%} + </div> + </video> + </div> + {{ possibly_shortened_description(request, feature.media_entry) }} </div> + +<script src="{{ request.staticdirect('/extlib/plyr/plyr.js') }}"></script> +<script> + /* Fix plyr: If I set height on video element, fullscreen is broken */ + let fluid_player = document.getElementById('player'); + fluid_player.classList.add('responsive-container'); + /* Playing */ + const videoPlayer = new Plyr(document.getElementById('js-video-player'), { + disableContextMenu: false, + captions: { + active: true, + }, + controls: [ + 'play-large', + 'play', + 'progress', + 'current-time', + 'duration', + 'mute', + 'volume', + 'captions', + 'settings', + 'pip', + 'airplay', + 'fullscreen' + ], + iconUrl: "{{ request.staticdirect('/extlib/plyr/plyr.svg') }}", + blankVideo: "{{ request.staticdirect('/extlib/plyr/blank.webm') }}", + debug: false + }); +</script> diff --git a/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_secondary.html b/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_secondary.html index 0d3a1adc..cb881b43 100644 --- a/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_secondary.html +++ b/mediagoblin/plugins/archivalook/templates/archivalook/feature_displays/video_secondary.html @@ -28,11 +28,11 @@ {%- else -%} <div class="secondary-feature aligned-left"> {%- endif %} - <div class="f-display"> +<div class="f-display" id="player"> {%- set display_type, display_path = media.get_display_media() %} - <video controls + <video controls playsinline {% if global_config['plugins']['mediagoblin.media_types.video']['auto_play'] %}autoplay{% endif %} - preload="metadata" class="video-js vjs-default-skin"> + preload="metadata" id="js-video-player"> <source src="{{ request.app.public_store.file_url(display_path) }}" {% if media.media_data %} type="{{ media.media_data.source_type() }}" @@ -54,3 +54,35 @@ <p class="f-title">{{ media.title }}</p> </a> </div> + +<!-- Plyr --> +<script src="{{ request.staticdirect('/extlib/plyr/plyr.js') }}"></script> +<script> + /* Fix plyr: If I set height on video element, fullscreen is broken */ + let fluid_player = document.getElementById('player'); + fluid_player.classList.add('responsive-container'); + /* Playing */ + const videoPlayer = new Plyr(document.getElementById('js-video-player'), { + disableContextMenu: false, + captions: { + active: true, + }, + controls: [ + 'play-large', + 'play', + 'progress', + 'current-time', + 'duration', + 'mute', + 'volume', + 'captions', + 'settings', + 'pip', + 'airplay', + 'fullscreen' + ], + iconUrl: "{{ request.staticdirect('/extlib/plyr/plyr.svg') }}", + blankVideo: "{{ request.staticdirect('/extlib/plyr/blank.webm') }}", + debug: false + }); +</script> diff --git a/mediagoblin/static/extlib/leaflet b/mediagoblin/static/extlib/leaflet index b47e2b1b..8e6520e9 120000 --- a/mediagoblin/static/extlib/leaflet +++ b/mediagoblin/static/extlib/leaflet @@ -1 +1 @@ -../../../extlib/leaflet/dist/
\ No newline at end of file +../../../extlib/leaflet/dist
\ No newline at end of file diff --git a/mediagoblin/static/extlib/plyr b/mediagoblin/static/extlib/plyr new file mode 120000 index 00000000..a1ed42f8 --- /dev/null +++ b/mediagoblin/static/extlib/plyr @@ -0,0 +1 @@ +../../../extlib/plyr
\ No newline at end of file diff --git a/mediagoblin/static/extlib/skeleton b/mediagoblin/static/extlib/skeleton index 737bfce4..c2da6713 120000 --- a/mediagoblin/static/extlib/skeleton +++ b/mediagoblin/static/extlib/skeleton @@ -1 +1 @@ -../../../extlib/skeleton/
\ No newline at end of file +../../../extlib/skeleton
\ No newline at end of file diff --git a/mediagoblin/static/extlib/video-js b/mediagoblin/static/extlib/video-js deleted file mode 120000 index c13a7532..00000000 --- a/mediagoblin/static/extlib/video-js +++ /dev/null @@ -1 +0,0 @@ -../../../extlib/video.js/dist/
\ No newline at end of file diff --git a/mediagoblin/static/extlib/videojs-resolution-switcher b/mediagoblin/static/extlib/videojs-resolution-switcher deleted file mode 120000 index ace672d9..00000000 --- a/mediagoblin/static/extlib/videojs-resolution-switcher +++ /dev/null @@ -1 +0,0 @@ -../../../extlib/videojs-resolution-switcher/lib/
\ No newline at end of file diff --git a/mediagoblin/templates/mediagoblin/media_displays/video.html b/mediagoblin/templates/mediagoblin/media_displays/video.html index e378fc90..2d8d776a 100644 --- a/mediagoblin/templates/mediagoblin/media_displays/video.html +++ b/mediagoblin/templates/mediagoblin/media_displays/video.html @@ -19,92 +19,121 @@ {% extends 'mediagoblin/user_pages/media.html' %} {% block mediagoblin_head -%} - {{ super() }} - <script type="text/javascript" src="{{ - request.staticdirect('/extlib/video-js/video.js') }}"></script> - <script type="text/javascript" src="{{ - request.staticdirect('/extlib/videojs-resolution-switcher/videojs-resolution-switcher.js') }}"> - </script> - <script type="text/javascript" - src="{{ request.staticdirect('/js/change-video-resolution.js') }}"></script> - {# Sadly commented out till we can get the mediagoblin skin ported over - # to the newest video.js release ;\ #} - <link href="{{ - request.staticdirect('/extlib/video-js/video-js.css') }}" - rel="stylesheet"> - <link href="{{ - request.staticdirect('/extlib/videojs-resolution-switcher/videojs-resolution-switcher.css') }}" - rel="stylesheet"> - - <style type="text/css"> - .vjs-default-skin .vjs-big-play-button - { - top: 50%; - left: 50%; - margin: -1.5em auto auto -2em; - } - .vjs-play-progress, .vjs-volume-level { - background-color: #86D4B1 !important; - } - </style> - + {{ super() }} + <link href="{{ request.staticdirect('/extlib/plyr/plyr.css') }}" rel="stylesheet"> + <style> + video { + width: 100%; + } + .responsive-container { + display: inline; + } + /* plyr fix */ + .plyr:-moz-full-screen video { + max-height: initial; + } + .plyr:-webkit-full-screen video { + max-height: initial; + } + .plyr:-ms-fullscreen video { + max-height: initial; + } + .plyr:fullscreen video { + max-height: initial; + } + .plyr video { + max-height: 360px; + } + </style> {%- endblock %} {% block mediagoblin_media %} -<div class="media_other_container"> - {% set all_media_path = media.get_all_media() %} + <div class="media_other_container" id="player"> + {% set all_media_path = media.get_all_media() %} - <video controls - {% if global_config['plugins']['mediagoblin.media_types.video']['auto_play'] %}autoplay{% endif %} - preload="metadata" class="video-js vjs-default-skin" id="video_1"> - {% for each_media_path in all_media_path %} - <source src="{{ request.app.public_store.file_url(each_media_path[2]) }}" - {% if media.media_data %} - type="{{ media.media_data.source_type() }}" - {% else %} - type="{{ media.media_manager['default_webm_type'] }}" - {% endif %} - label="{{ each_media_path[0] }}" res="{{ each_media_path[1][1] }}" /> - {% endfor %} - {%- for subtitle in media.subtitle_files %} - <track src="{{ request.app.public_store.file_url(subtitle.filepath) }}" - label="{{ subtitle.name }}" kind="subtitles"> - {%- endfor %} - <div class="no_html5"> - {%- trans -%}Sorry, this video will not work because - your web browser does not support HTML5 - video.{%- endtrans -%}<br/> - {%- trans -%} - We recommend you install a <a href="https://libreplanet.org/wiki/Libre_Browsers_Libre_Formats">freedom-respecting browser which supports free formats</a>! - {%- endtrans -%} + <video controls playsinline + {% if global_config['plugins']['mediagoblin.media_types.video']['auto_play'] %}autoplay{% endif %} + preload="metadata" id="js-video-player"> + {% for each_media_path in all_media_path %} + <source src="{{ request.app.public_store.file_url(each_media_path[2]) }}" + {% if media.media_data %} + type="{{ media.media_data.source_type() }}" + {% else %} + type="{{ media.media_manager['default_webm_type'] }}" + {% endif %} + data-res="{{ each_media_path[1][1] }}" /> + {% endfor %} + {%- for subtitle in media.subtitle_files %} + <track src="{{ request.app.public_store.file_url(subtitle.filepath) }}" + label="{{ subtitle.name }}" kind="subtitles"> + {%- endfor %} + <div class="no_html5"> + {%- trans -%}Sorry, this video will not work because + your web browser does not support HTML5 + video.{%- endtrans -%}<br/> + {%- trans -%} + We recommend you install a <a href="https://libreplanet.org/wiki/Libre_Browsers_Libre_Formats">freedom-respecting browser which supports free formats</a>! + {%- endtrans -%} + </div> + </video> </div> - </video> -</div> + + <!-- Plyr --> + <script src="{{ request.staticdirect('/extlib/plyr/plyr.js') }}"></script> + <script> + /* Fix plyr: If I set height on video element, fullscreen is broken */ + let fluid_player = document.getElementById('player'); + fluid_player.classList.add('responsive-container'); + /* Playing */ + const videoPlayer = new Plyr(document.getElementById('js-video-player'), { + disableContextMenu: false, + captions: { + active: true, + }, + controls: [ + 'play-large', + 'play', + 'progress', + 'current-time', + 'duration', + 'mute', + 'volume', + 'captions', + 'settings', + 'pip', + 'airplay', + 'fullscreen' + ], + iconUrl: "{{ request.staticdirect('/extlib/plyr/plyr.svg') }}", + blankVideo: "{{ request.staticdirect('/extlib/plyr/blank.webm') }}", + debug: false + }); + </script> {% endblock %} {% block mediagoblin_sidebar %} - <h3>{% trans %}Download{% endtrans %}</h3> - <ul> - {% if 'original' in media.media_files %} - <li> - <a href="{{ request.app.public_store.file_url( - media.media_files.original) }}"> - {%- trans %}Original file{% endtrans -%} - </a> - </li> - {% endif %} - {# Sorting will be wrong for resolutions >= 1000p as it's alphanumeric. #} - {% for name, media in media.media_files|dictsort|list %} - {% if name.startswith('webm') %} - <li> - <a href="{{ request.app.public_store.file_url(media) }}"> - {%- trans %}WebM file (VP8/Vorbis){% endtrans -%} - {{ name | replace('webm_', ' ') }} - </a> - </li> - {% endif %} - {% endfor %} - {% if 'webm_video' in media.media_files %} - {% endif %} - </ul> + <h3>{% trans %}Download{% endtrans %}</h3> + <ul> + {% if 'original' in media.media_files %} + <li> + <a href="{{ request.app.public_store.file_url( + media.media_files.original) }}" download> + {%- trans %}Original file{% endtrans -%} + </a> + </li> + {% endif %} + {# Sorting will be wrong for resolutions >= 1000p as it's alphanumeric. #} + {% for name, media in media.media_files|dictsort|list %} + {% if name.startswith('webm') %} + <li> + <a href="{{ request.app.public_store.file_url(media) }}" download> + {%- trans %}WebM file (VP8/Vorbis){% endtrans -%} + {{ name | replace('webm_', ' ') }} + </a> + </li> + {% endif %} + {% endfor %} + {% if 'webm_video' in media.media_files %} + {% endif %} + </ul> {% endblock %} |