@splidejs/splide-extension-video
Version:
The Splide extension for embedding videos.
1,775 lines (1,425 loc) • 106 kB
JavaScript
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/*!
* Splide.js
* Version : 0.8.0
* License : MIT
* Copyright: 2022 Naotoshi Fujita
*/
(function (factory) {
typeof define === 'function' && define.amd ? define(factory) : factory();
})(function () {
'use strict';
function empty(array) {
array.length = 0;
}
function slice$1(arrayLike, start, end) {
return Array.prototype.slice.call(arrayLike, start, end);
}
function apply$1(func) {
return func.bind.apply(func, [null].concat(slice$1(arguments, 1)));
}
function typeOf$1(type, subject) {
return typeof subject === type;
}
var isArray$1 = Array.isArray;
apply$1(typeOf$1, "function");
apply$1(typeOf$1, "string");
apply$1(typeOf$1, "undefined");
function toArray$1(value) {
return isArray$1(value) ? value : [value];
}
function forEach$1(values, iteratee) {
toArray$1(values).forEach(iteratee);
}
function includes(array, value) {
return array.indexOf(value) > -1;
}
var ownKeys$1 = Object.keys;
function forOwn$1(object, iteratee, right) {
if (object) {
var keys = ownKeys$1(object);
keys = right ? keys.reverse() : keys;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key !== "__proto__") {
if (iteratee(object[key], key) === false) {
break;
}
}
}
}
return object;
}
function assign$1(object) {
slice$1(arguments, 1).forEach(function (source) {
forOwn$1(source, function (value, key) {
object[key] = source[key];
});
});
return object;
}
var PROJECT_CODE$1 = "splide";
function EventBinder() {
var listeners = [];
function bind(targets, events, callback, options) {
forEachEvent(targets, events, function (target, event, namespace) {
var isEventTarget = ("addEventListener" in target);
var remover = isEventTarget ? target.removeEventListener.bind(target, event, callback, options) : target["removeListener"].bind(target, callback);
isEventTarget ? target.addEventListener(event, callback, options) : target["addListener"](callback);
listeners.push([target, event, namespace, callback, remover]);
});
}
function unbind(targets, events, callback) {
forEachEvent(targets, events, function (target, event, namespace) {
listeners = listeners.filter(function (listener) {
if (listener[0] === target && listener[1] === event && listener[2] === namespace && (!callback || listener[3] === callback)) {
listener[4]();
return false;
}
return true;
});
});
}
function dispatch(target, type, detail) {
var e;
var bubbles = true;
if (typeof CustomEvent === "function") {
e = new CustomEvent(type, {
bubbles: bubbles,
detail: detail
});
} else {
e = document.createEvent("CustomEvent");
e.initCustomEvent(type, bubbles, false, detail);
}
target.dispatchEvent(e);
return e;
}
function forEachEvent(targets, events, iteratee) {
forEach$1(targets, function (target) {
target && forEach$1(events, function (events2) {
events2.split(" ").forEach(function (eventNS) {
var fragment = eventNS.split(".");
iteratee(target, fragment[0], fragment[1]);
});
});
});
}
function destroy() {
listeners.forEach(function (data) {
data[4]();
});
empty(listeners);
}
return {
bind: bind,
unbind: unbind,
dispatch: dispatch,
destroy: destroy
};
}
var EVENT_MOUNTED = "mounted";
var EVENT_MOVE = "move";
var EVENT_MOVED = "moved";
var EVENT_DRAG = "drag";
var EVENT_DRAGGING = "dragging";
var EVENT_SCROLL = "scroll";
var EVENT_SCROLLED = "scrolled";
var EVENT_DESTROY = "destroy";
function EventInterface(Splide2) {
var bus = Splide2 ? Splide2.event.bus : document.createDocumentFragment();
var binder = EventBinder();
function on(events, callback) {
binder.bind(bus, toArray$1(events).join(" "), function (e) {
callback.apply(callback, isArray$1(e.detail) ? e.detail : []);
});
}
function emit(event) {
binder.dispatch(bus, event, slice$1(arguments, 1));
}
if (Splide2) {
Splide2.event.on(EVENT_DESTROY, binder.destroy);
}
return assign$1(binder, {
bus: bus,
on: on,
off: apply$1(binder.unbind, bus),
emit: emit
});
}
function State(initialState) {
var state = initialState;
function set(value) {
state = value;
}
function is(states) {
return includes(toArray$1(states), state);
}
return {
set: set,
is: is
};
}
var CLASS_SLIDE = PROJECT_CODE$1 + "__slide";
var CLASS_CONTAINER = CLASS_SLIDE + "__container";
function slice(arrayLike, start, end) {
return Array.prototype.slice.call(arrayLike, start, end);
}
function find(arrayLike, predicate) {
return slice(arrayLike).filter(predicate)[0];
}
function apply(func) {
return func.bind.apply(func, [null].concat(slice(arguments, 1)));
}
function typeOf(type, subject) {
return typeof subject === type;
}
function isObject(subject) {
return !isNull(subject) && typeOf("object", subject);
}
var isArray = Array.isArray;
var isFunction = apply(typeOf, "function");
var isString = apply(typeOf, "string");
var isUndefined = apply(typeOf, "undefined");
function isNull(subject) {
return subject === null;
}
function isHTMLElement(subject) {
return subject instanceof HTMLElement;
}
function toArray(value) {
return isArray(value) ? value : [value];
}
function forEach(values, iteratee) {
toArray(values).forEach(iteratee);
}
function toggleClass(elm, classes, add) {
if (elm) {
forEach(classes, function (name) {
if (name) {
elm.classList[add ? "add" : "remove"](name);
}
});
}
}
function addClass(elm, classes) {
toggleClass(elm, isString(classes) ? classes.split(" ") : classes, true);
}
function append(parent, children) {
forEach(children, parent.appendChild.bind(parent));
}
function matches(elm, selector) {
return isHTMLElement(elm) && (elm["msMatchesSelector"] || elm.matches).call(elm, selector);
}
function children(parent, selector) {
var children2 = parent ? slice(parent.children) : [];
return selector ? children2.filter(function (child) {
return matches(child, selector);
}) : children2;
}
function child(parent, selector) {
return selector ? children(parent, selector)[0] : parent.firstElementChild;
}
var ownKeys = Object.keys;
function forOwn(object, iteratee, right) {
if (object) {
var keys = ownKeys(object);
keys = right ? keys.reverse() : keys;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key !== "__proto__") {
if (iteratee(object[key], key) === false) {
break;
}
}
}
}
return object;
}
function assign(object) {
slice(arguments, 1).forEach(function (source) {
forOwn(source, function (value, key) {
object[key] = source[key];
});
});
return object;
}
function merge(object) {
slice(arguments, 1).forEach(function (source) {
forOwn(source, function (value, key) {
if (isArray(value)) {
object[key] = value.slice();
} else if (isObject(value)) {
object[key] = merge({}, isObject(object[key]) ? object[key] : {}, value);
} else {
object[key] = value;
}
});
});
return object;
}
function removeAttribute(elms, attrs) {
forEach(elms, function (elm) {
forEach(attrs, function (attr) {
elm && elm.removeAttribute(attr);
});
});
}
function setAttribute(elms, attrs, value) {
if (isObject(attrs)) {
forOwn(attrs, function (value2, name) {
setAttribute(elms, name, value2);
});
} else {
forEach(elms, function (elm) {
isNull(value) || value === "" ? removeAttribute(elm, attrs) : elm.setAttribute(attrs, String(value));
});
}
}
function _create(tag, attrs, parent) {
var elm = document.createElement(tag);
if (attrs) {
isString(attrs) ? addClass(elm, attrs) : setAttribute(elm, attrs);
}
parent && append(parent, elm);
return elm;
}
function style(elm, prop, value) {
if (isUndefined(value)) {
return getComputedStyle(elm)[prop];
}
if (!isNull(value)) {
elm.style[prop] = "" + value;
}
}
function display(elm, display2) {
style(elm, "display", display2);
}
function getAttribute(elm, attr) {
return elm.getAttribute(attr);
}
function hasClass(elm, className) {
return elm && elm.classList.contains(className);
}
function remove(nodes) {
forEach(nodes, function (node) {
if (node && node.parentNode) {
node.parentNode.removeChild(node);
}
});
}
function queryAll(parent, selector) {
return selector ? slice(parent.querySelectorAll(selector)) : [];
}
function removeClass(elm, classes) {
toggleClass(elm, classes, false);
}
var PROJECT_CODE = "splide";
function error(message) {
console.error("[" + PROJECT_CODE + "] " + message);
}
var min = Math.min,
max = Math.max,
floor = Math.floor,
ceil = Math.ceil,
abs = Math.abs;
function clamp(number, x, y) {
var minimum = min(x, y);
var maximum = max(x, y);
return min(max(minimum, number), maximum);
}
var CLASS_VIDEO = "splide__video";
var CLASS_VIDEO_WRAPPER = CLASS_VIDEO + "__wrapper";
var CLASS_VIDEO_PLAY_BUTTON = CLASS_VIDEO + "__play";
var CLASS_PLAYING = "is-playing";
var CLASS_ERROR = "is-error";
var CLASS_VIDEO_DISABLED = "is-video-disabled";
var MODIFIER_HAS_VIDEO = "--has-video";
var YOUTUBE_DATA_ATTRIBUTE = "data-splide-youtube";
var VIMEO_DATA_ATTRIBUTE = "data-splide-vimeo";
var HTML_VIDEO__DATA_ATTRIBUTE = "data-splide-html-video";
var DEFAULTS = {
hideControls: false,
loop: false,
mute: false,
volume: 0.2
};
var EVENT_VIDEO_PLAY = "video:play";
var EVENT_VIDEO_PAUSE = "video:pause";
var EVENT_VIDEO_ENDED = "video:ended";
var EVENT_VIDEO_ERROR = "video:error";
var EVENT_VIDEO_CLICK = "video:click";
var NOT_INITIALIZED = 1;
var INITIALIZING = 2;
var INITIALIZED = 3;
var PENDING_PLAY = 4;
var IDLE = 5;
var LOADING = 6;
var PLAY_REQUEST_ABORTED = 7;
var PLAYING = 8;
var ERROR = 9;
var AbstractVideoPlayer = /*#__PURE__*/function () {
function AbstractVideoPlayer(target, videoId, options) {
this.state = State(NOT_INITIALIZED);
this.event = EventInterface();
this.target = target;
this.videoId = videoId;
this.options = options || {};
this.onPlay = this.onPlay.bind(this);
this.onPause = this.onPause.bind(this);
this.onEnded = this.onEnded.bind(this);
this.onPlayerReady = this.onPlayerReady.bind(this);
this.onError = this.onError.bind(this);
}
var _proto = AbstractVideoPlayer.prototype;
_proto.on = function on(events, callback) {
this.event.on(events, callback);
};
_proto.play = function play() {
var state = this.state;
if (state.is(ERROR)) {
error("Can not play this video.");
return;
}
this.event.emit("play");
if (state.is(INITIALIZING)) {
return state.set(PENDING_PLAY);
}
if (state.is(INITIALIZED)) {
this.player = this.createPlayer(this.videoId);
return state.set(PENDING_PLAY);
}
if (state.is([PENDING_PLAY, PLAYING])) {
return;
}
if (state.is(IDLE)) {
state.set(LOADING);
this.playVideo();
}
};
_proto.pause = function pause() {
var state = this.state;
if (state.is(ERROR)) {
return;
}
this.event.emit("pause");
if (state.is(PENDING_PLAY)) {
return state.set(INITIALIZING);
}
if (state.is(LOADING)) {
return state.set(PLAY_REQUEST_ABORTED);
}
if (state.is(PLAYING)) {
this.pauseVideo();
this.state.set(IDLE);
}
};
_proto.isPaused = function isPaused() {
return !this.state.is(PLAYING);
};
_proto.destroy = function destroy() {
this.event.destroy();
};
_proto.onPlayerReady = function onPlayerReady() {
var state = this.state;
var isPending = state.is(PENDING_PLAY);
state.set(IDLE);
if (isPending) {
this.play();
}
};
_proto.onPlay = function onPlay() {
var state = this.state;
var aborted = state.is(PLAY_REQUEST_ABORTED);
state.set(PLAYING);
if (aborted) {
this.pause();
} else {
this.event.emit("played");
}
};
_proto.onPause = function onPause() {
this.state.set(IDLE);
this.event.emit("paused");
};
_proto.onEnded = function onEnded() {
this.state.set(IDLE);
this.event.emit("ended");
};
_proto.onError = function onError() {
this.state.set(ERROR);
this.event.emit("error");
};
return AbstractVideoPlayer;
}();
var HTMLVideoPlayer = /*#__PURE__*/function (_AbstractVideoPlayer) {
_inheritsLoose(HTMLVideoPlayer, _AbstractVideoPlayer);
function HTMLVideoPlayer(target, videoId, options) {
var _this6;
if (options === void 0) {
options = {};
}
_this6 = _AbstractVideoPlayer.call(this, target, videoId, options) || this;
_this6.state.set(INITIALIZED);
return _this6;
}
var _proto2 = HTMLVideoPlayer.prototype;
_proto2.createPlayer = function createPlayer(videoId) {
var options = this.options,
_this$options$playerO = this.options.playerOptions,
playerOptions = _this$options$playerO === void 0 ? {} : _this$options$playerO;
var player = _create("video", {
src: videoId
}, this.target);
var on = player.addEventListener.bind(player);
assign(player, {
controls: !options.hideControls,
loop: options.loop,
volume: clamp(options.volume, 0, 1),
muted: options.mute
}, playerOptions.htmlVideo || {});
on("play", this.onPlay);
on("pause", this.onPause);
on("ended", this.onEnded);
on("loadeddata", this.onPlayerReady);
on("error", this.onError);
return player;
};
_proto2.playVideo = function playVideo() {
var promise = this.player.play();
promise && promise["catch"](this.onError.bind(this));
};
_proto2.pauseVideo = function pauseVideo() {
this.player.pause();
};
_proto2.onError = function onError() {
if (this.state.is(PLAY_REQUEST_ABORTED)) {
this.state.set(IDLE);
} else {
_AbstractVideoPlayer.prototype.onError.call(this);
}
};
_proto2.destroy = function destroy() {
_AbstractVideoPlayer.prototype.destroy.call(this);
var player = this.player;
var off = player.addEventListener.bind(player);
off("play", this.onPlay);
off("pause", this.onPause);
off("ended", this.onEnded);
off("loadeddata", this.onPlayerReady);
};
return HTMLVideoPlayer;
}(AbstractVideoPlayer);
/*! @vimeo/player v2.17.1 | (c) 2022 Vimeo | MIT License | https://github.com/vimeo/player.js */
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
/**
* @module lib/functions
*/
/**
* Check to see this is a node environment.
* @type {Boolean}
*/
/* global global */
var isNode = typeof global !== 'undefined' && {}.toString.call(global) === '[object global]';
/**
* Get the name of the method for a given getter or setter.
*
* @param {string} prop The name of the property.
* @param {string} type Either “get” or “set”.
* @return {string}
*/
function getMethodName(prop, type) {
if (prop.indexOf(type.toLowerCase()) === 0) {
return prop;
}
return "".concat(type.toLowerCase()).concat(prop.substr(0, 1).toUpperCase()).concat(prop.substr(1));
}
/**
* Check to see if the object is a DOM Element.
*
* @param {*} element The object to check.
* @return {boolean}
*/
function isDomElement(element) {
return Boolean(element && element.nodeType === 1 && 'nodeName' in element && element.ownerDocument && element.ownerDocument.defaultView);
}
/**
* Check to see whether the value is a number.
*
* @see http://dl.dropboxusercontent.com/u/35146/js/tests/isNumber.html
* @param {*} value The value to check.
* @param {boolean} integer Check if the value is an integer.
* @return {boolean}
*/
function isInteger(value) {
// eslint-disable-next-line eqeqeq
return !isNaN(parseFloat(value)) && isFinite(value) && Math.floor(value) == value;
}
/**
* Check to see if the URL is a Vimeo url.
*
* @param {string} url The url string.
* @return {boolean}
*/
function isVimeoUrl(url) {
return /^(https?:)?\/\/((player|www)\.)?vimeo\.com(?=$|\/)/.test(url);
}
/**
* Check to see if the URL is for a Vimeo embed.
*
* @param {string} url The url string.
* @return {boolean}
*/
function isVimeoEmbed(url) {
var expr = /^https:\/\/player\.vimeo\.com\/video\/\d+/;
return expr.test(url);
}
/**
* Get the Vimeo URL from an element.
* The element must have either a data-vimeo-id or data-vimeo-url attribute.
*
* @param {object} oEmbedParameters The oEmbed parameters.
* @return {string}
*/
function getVimeoUrl() {
var oEmbedParameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var id = oEmbedParameters.id;
var url = oEmbedParameters.url;
var idOrUrl = id || url;
if (!idOrUrl) {
throw new Error('An id or url must be passed, either in an options object or as a data-vimeo-id or data-vimeo-url attribute.');
}
if (isInteger(idOrUrl)) {
return "https://vimeo.com/".concat(idOrUrl);
}
if (isVimeoUrl(idOrUrl)) {
return idOrUrl.replace('http:', 'https:');
}
if (id) {
throw new TypeError("\u201C".concat(id, "\u201D is not a valid video id."));
}
throw new TypeError("\u201C".concat(idOrUrl, "\u201D is not a vimeo.com url."));
}
var arrayIndexOfSupport = typeof Array.prototype.indexOf !== 'undefined';
var postMessageSupport = typeof window !== 'undefined' && typeof window.postMessage !== 'undefined';
if (!isNode && (!arrayIndexOfSupport || !postMessageSupport)) {
throw new Error('Sorry, the Vimeo Player API is not available in this browser.');
}
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;
}
/*!
* weakmap-polyfill v2.0.4 - ECMAScript6 WeakMap polyfill
* https://github.com/polygonplanet/weakmap-polyfill
* Copyright (c) 2015-2021 polygonplanet <polygon.planet.aqua@gmail.com>
* @license MIT
*/
(function (self) {
if (self.WeakMap) {
return;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var hasDefine = Object.defineProperty && function () {
try {
// Avoid IE8's broken Object.defineProperty
return Object.defineProperty({}, 'x', {
value: 1
}).x === 1;
} catch (e) {}
}();
var defineProperty = function defineProperty(object, name, value) {
if (hasDefine) {
Object.defineProperty(object, name, {
configurable: true,
writable: true,
value: value
});
} else {
object[name] = value;
}
};
self.WeakMap = function () {
// ECMA-262 23.3 WeakMap Objects
function WeakMap() {
if (this === void 0) {
throw new TypeError("Constructor WeakMap requires 'new'");
}
defineProperty(this, '_id', genId('_WeakMap')); // ECMA-262 23.3.1.1 WeakMap([iterable])
if (arguments.length > 0) {
// Currently, WeakMap `iterable` argument is not supported
throw new TypeError('WeakMap iterable is not supported');
}
} // ECMA-262 23.3.3.2 WeakMap.prototype.delete(key)
defineProperty(WeakMap.prototype, 'delete', function (key) {
checkInstance(this, 'delete');
if (!isObject(key)) {
return false;
}
var entry = key[this._id];
if (entry && entry[0] === key) {
delete key[this._id];
return true;
}
return false;
}); // ECMA-262 23.3.3.3 WeakMap.prototype.get(key)
defineProperty(WeakMap.prototype, 'get', function (key) {
checkInstance(this, 'get');
if (!isObject(key)) {
return void 0;
}
var entry = key[this._id];
if (entry && entry[0] === key) {
return entry[1];
}
return void 0;
}); // ECMA-262 23.3.3.4 WeakMap.prototype.has(key)
defineProperty(WeakMap.prototype, 'has', function (key) {
checkInstance(this, 'has');
if (!isObject(key)) {
return false;
}
var entry = key[this._id];
if (entry && entry[0] === key) {
return true;
}
return false;
}); // ECMA-262 23.3.3.5 WeakMap.prototype.set(key, value)
defineProperty(WeakMap.prototype, 'set', function (key, value) {
checkInstance(this, 'set');
if (!isObject(key)) {
throw new TypeError('Invalid value used as weak map key');
}
var entry = key[this._id];
if (entry && entry[0] === key) {
entry[1] = value;
return this;
}
defineProperty(key, this._id, [key, value]);
return this;
});
function checkInstance(x, methodName) {
if (!isObject(x) || !hasOwnProperty.call(x, '_id')) {
throw new TypeError(methodName + ' method called on incompatible receiver ' + typeof x);
}
}
function genId(prefix) {
return prefix + '_' + rand() + '.' + rand();
}
function rand() {
return Math.random().toString().substring(2);
}
defineProperty(WeakMap, '_polyfill', true);
return WeakMap;
}();
function isObject(x) {
return Object(x) === x;
}
})(typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : commonjsGlobal);
var npo_src = createCommonjsModule(function (module) {
/*! Native Promise Only
v0.8.1 (c) Kyle Simpson
MIT License: http://getify.mit-license.org
*/
(function UMD(name, context, definition) {
// special form of UMD for polyfilling across evironments
context[name] = context[name] || definition();
if (module.exports) {
module.exports = context[name];
}
})("Promise", typeof commonjsGlobal != "undefined" ? commonjsGlobal : commonjsGlobal, function DEF() {
var builtInProp,
cycle,
scheduling_queue,
ToString = Object.prototype.toString,
timer = typeof setImmediate != "undefined" ? function timer(fn) {
return setImmediate(fn);
} : setTimeout; // dammit, IE8.
try {
Object.defineProperty({}, "x", {});
builtInProp = function builtInProp(obj, name, val, config) {
return Object.defineProperty(obj, name, {
value: val,
writable: true,
configurable: config !== false
});
};
} catch (err) {
builtInProp = function builtInProp(obj, name, val) {
obj[name] = val;
return obj;
};
} // Note: using a queue instead of array for efficiency
scheduling_queue = function Queue() {
var first, last, item;
function Item(fn, self) {
this.fn = fn;
this.self = self;
this.next = void 0;
}
return {
add: function add(fn, self) {
item = new Item(fn, self);
if (last) {
last.next = item;
} else {
first = item;
}
last = item;
item = void 0;
},
drain: function drain() {
var f = first;
first = last = cycle = void 0;
while (f) {
f.fn.call(f.self);
f = f.next;
}
}
};
}();
function schedule(fn, self) {
scheduling_queue.add(fn, self);
if (!cycle) {
cycle = timer(scheduling_queue.drain);
}
} // promise duck typing
function isThenable(o) {
var _then,
o_type = typeof o;
if (o != null && (o_type == "object" || o_type == "function")) {
_then = o.then;
}
return typeof _then == "function" ? _then : false;
}
function notify() {
for (var i = 0; i < this.chain.length; i++) {
notifyIsolated(this, this.state === 1 ? this.chain[i].success : this.chain[i].failure, this.chain[i]);
}
this.chain.length = 0;
} // NOTE: This is a separate function to isolate
// the `try..catch` so that other code can be
// optimized better
function notifyIsolated(self, cb, chain) {
var ret, _then;
try {
if (cb === false) {
chain.reject(self.msg);
} else {
if (cb === true) {
ret = self.msg;
} else {
ret = cb.call(void 0, self.msg);
}
if (ret === chain.promise) {
chain.reject(TypeError("Promise-chain cycle"));
} else if (_then = isThenable(ret)) {
_then.call(ret, chain.resolve, chain.reject);
} else {
chain.resolve(ret);
}
}
} catch (err) {
chain.reject(err);
}
}
function resolve(msg) {
var _then,
self = this; // already triggered?
if (self.triggered) {
return;
}
self.triggered = true; // unwrap
if (self.def) {
self = self.def;
}
try {
if (_then = isThenable(msg)) {
schedule(function () {
var def_wrapper = new MakeDefWrapper(self);
try {
_then.call(msg, function $resolve$() {
resolve.apply(def_wrapper, arguments);
}, function $reject$() {
reject.apply(def_wrapper, arguments);
});
} catch (err) {
reject.call(def_wrapper, err);
}
});
} else {
self.msg = msg;
self.state = 1;
if (self.chain.length > 0) {
schedule(notify, self);
}
}
} catch (err) {
reject.call(new MakeDefWrapper(self), err);
}
}
function reject(msg) {
var self = this; // already triggered?
if (self.triggered) {
return;
}
self.triggered = true; // unwrap
if (self.def) {
self = self.def;
}
self.msg = msg;
self.state = 2;
if (self.chain.length > 0) {
schedule(notify, self);
}
}
function iteratePromises(Constructor, arr, resolver, rejecter) {
for (var idx = 0; idx < arr.length; idx++) {
(function IIFE(idx) {
Constructor.resolve(arr[idx]).then(function $resolver$(msg) {
resolver(idx, msg);
}, rejecter);
})(idx);
}
}
function MakeDefWrapper(self) {
this.def = self;
this.triggered = false;
}
function MakeDef(self) {
this.promise = self;
this.state = 0;
this.triggered = false;
this.chain = [];
this.msg = void 0;
}
function Promise(executor) {
if (typeof executor != "function") {
throw TypeError("Not a function");
}
if (this.__NPO__ !== 0) {
throw TypeError("Not a promise");
} // instance shadowing the inherited "brand"
// to signal an already "initialized" promise
this.__NPO__ = 1;
var def = new MakeDef(this);
this["then"] = function then(success, failure) {
var o = {
success: typeof success == "function" ? success : true,
failure: typeof failure == "function" ? failure : false
}; // Note: `then(..)` itself can be borrowed to be used against
// a different promise constructor for making the chained promise,
// by substituting a different `this` binding.
o.promise = new this.constructor(function extractChain(resolve, reject) {
if (typeof resolve != "function" || typeof reject != "function") {
throw TypeError("Not a function");
}
o.resolve = resolve;
o.reject = reject;
});
def.chain.push(o);
if (def.state !== 0) {
schedule(notify, def);
}
return o.promise;
};
this["catch"] = function $catch$(failure) {
return this.then(void 0, failure);
};
try {
executor.call(void 0, function publicResolve(msg) {
resolve.call(def, msg);
}, function publicReject(msg) {
reject.call(def, msg);
});
} catch (err) {
reject.call(def, err);
}
}
var PromisePrototype = builtInProp({}, "constructor", Promise,
/*configurable=*/
false); // Note: Android 4 cannot use `Object.defineProperty(..)` here
Promise.prototype = PromisePrototype; // built-in "brand" to signal an "uninitialized" promise
builtInProp(PromisePrototype, "__NPO__", 0,
/*configurable=*/
false);
builtInProp(Promise, "resolve", function Promise$resolve(msg) {
var Constructor = this; // spec mandated checks
// note: best "isPromise" check that's practical for now
if (msg && typeof msg == "object" && msg.__NPO__ === 1) {
return msg;
}
return new Constructor(function executor(resolve, reject) {
if (typeof resolve != "function" || typeof reject != "function") {
throw TypeError("Not a function");
}
resolve(msg);
});
});
builtInProp(Promise, "reject", function Promise$reject(msg) {
return new this(function executor(resolve, reject) {
if (typeof resolve != "function" || typeof reject != "function") {
throw TypeError("Not a function");
}
reject(msg);
});
});
builtInProp(Promise, "all", function Promise$all(arr) {
var Constructor = this; // spec mandated checks
if (ToString.call(arr) != "[object Array]") {
return Constructor.reject(TypeError("Not an array"));
}
if (arr.length === 0) {
return Constructor.resolve([]);
}
return new Constructor(function executor(resolve, reject) {
if (typeof resolve != "function" || typeof reject != "function") {
throw TypeError("Not a function");
}
var len = arr.length,
msgs = Array(len),
count = 0;
iteratePromises(Constructor, arr, function resolver(idx, msg) {
msgs[idx] = msg;
if (++count === len) {
resolve(msgs);
}
}, reject);
});
});
builtInProp(Promise, "race", function Promise$race(arr) {
var Constructor = this; // spec mandated checks
if (ToString.call(arr) != "[object Array]") {
return Constructor.reject(TypeError("Not an array"));
}
return new Constructor(function executor(resolve, reject) {
if (typeof resolve != "function" || typeof reject != "function") {
throw TypeError("Not a function");
}
iteratePromises(Constructor, arr, function resolver(idx, msg) {
resolve(msg);
}, reject);
});
});
return Promise;
});
});
/**
* @module lib/callbacks
*/
var callbackMap = new WeakMap();
/**
* Store a callback for a method or event for a player.
*
* @param {Player} player The player object.
* @param {string} name The method or event name.
* @param {(function(this:Player, *): void|{resolve: function, reject: function})} callback
* The callback to call or an object with resolve and reject functions for a promise.
* @return {void}
*/
function storeCallback(player, name, callback) {
var playerCallbacks = callbackMap.get(player.element) || {};
if (!(name in playerCallbacks)) {
playerCallbacks[name] = [];
}
playerCallbacks[name].push(callback);
callbackMap.set(player.element, playerCallbacks);
}
/**
* Get the callbacks for a player and event or method.
*
* @param {Player} player The player object.
* @param {string} name The method or event name
* @return {function[]}
*/
function getCallbacks(player, name) {
var playerCallbacks = callbackMap.get(player.element) || {};
return playerCallbacks[name] || [];
}
/**
* Remove a stored callback for a method or event for a player.
*
* @param {Player} player The player object.
* @param {string} name The method or event name
* @param {function} [callback] The specific callback to remove.
* @return {boolean} Was this the last callback?
*/
function removeCallback(player, name, callback) {
var playerCallbacks = callbackMap.get(player.element) || {};
if (!playerCallbacks[name]) {
return true;
} // If no callback is passed, remove all callbacks for the event
if (!callback) {
playerCallbacks[name] = [];
callbackMap.set(player.element, playerCallbacks);
return true;
}
var index = playerCallbacks[name].indexOf(callback);
if (index !== -1) {
playerCallbacks[name].splice(index, 1);
}
callbackMap.set(player.element, playerCallbacks);
return playerCallbacks[name] && playerCallbacks[name].length === 0;
}
/**
* Return the first stored callback for a player and event or method.
*
* @param {Player} player The player object.
* @param {string} name The method or event name.
* @return {function} The callback, or false if there were none
*/
function shiftCallbacks(player, name) {
var playerCallbacks = getCallbacks(player, name);
if (playerCallbacks.length < 1) {
return false;
}
var callback = playerCallbacks.shift();
removeCallback(player, name, callback);
return callback;
}
/**
* Move callbacks associated with an element to another element.
*
* @param {HTMLElement} oldElement The old element.
* @param {HTMLElement} newElement The new element.
* @return {void}
*/
function swapCallbacks(oldElement, newElement) {
var playerCallbacks = callbackMap.get(oldElement);
callbackMap.set(newElement, playerCallbacks);
callbackMap["delete"](oldElement);
}
/**
* @module lib/postmessage
*/
/**
* Parse a message received from postMessage.
*
* @param {*} data The data received from postMessage.
* @return {object}
*/
function parseMessageData(data) {
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (error) {
// If the message cannot be parsed, throw the error as a warning
console.warn(error);
return {};
}
}
return data;
}
/**
* Post a message to the specified target.
*
* @param {Player} player The player object to use.
* @param {string} method The API method to call.
* @param {object} params The parameters to send to the player.
* @return {void}
*/
function postMessage(player, method, params) {
if (!player.element.contentWindow || !player.element.contentWindow.postMessage) {
return;
}
var message = {
method: method
};
if (params !== undefined) {
message.value = params;
} // IE 8 and 9 do not support passing messages, so stringify them
var ieVersion = parseFloat(navigator.userAgent.toLowerCase().replace(/^.*msie (\d+).*$/, '$1'));
if (ieVersion >= 8 && ieVersion < 10) {
message = JSON.stringify(message);
}
player.element.contentWindow.postMessage(message, player.origin);
}
/**
* Parse the data received from a message event.
*
* @param {Player} player The player that received the message.
* @param {(Object|string)} data The message data. Strings will be parsed into JSON.
* @return {void}
*/
function processData(player, data) {
data = parseMessageData(data);
var callbacks = [];
var param;
if (data.event) {
if (data.event === 'error') {
var promises = getCallbacks(player, data.data.method);
promises.forEach(function (promise) {
var error = new Error(data.data.message);
error.name = data.data.name;
promise.reject(error);
removeCallback(player, data.data.method, promise);
});
}
callbacks = getCallbacks(player, "event:".concat(data.event));
param = data.data;
} else if (data.method) {
var callback = shiftCallbacks(player, data.method);
if (callback) {
callbacks.push(callback);
param = data.value;
}
}
callbacks.forEach(function (callback) {
try {
if (typeof callback === 'function') {
callback.call(player, param);
return;
}
callback.resolve(param);
} catch (e) {// empty
}
});
}
/**
* @module lib/embed
*/
var oEmbedParameters = ['autopause', 'autoplay', 'background', 'byline', 'color', 'controls', 'dnt', 'height', 'id', 'interactive_params', 'keyboard', 'loop', 'maxheight', 'maxwidth', 'muted', 'playsinline', 'portrait', 'responsive', 'speed', 'texttrack', 'title', 'transparent', 'url', 'width'];
/**
* Get the 'data-vimeo'-prefixed attributes from an element as an object.
*
* @param {HTMLElement} element The element.
* @param {Object} [defaults={}] The default values to use.
* @return {Object<string, string>}
*/
function getOEmbedParameters(element) {
var defaults = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return oEmbedParameters.reduce(function (params, param) {
var value = element.getAttribute("data-vimeo-".concat(param));
if (value || value === '') {
params[param] = value === '' ? 1 : value;
}
return params;
}, defaults);
}
/**
* Create an embed from oEmbed data inside an element.
*
* @param {object} data The oEmbed data.
* @param {HTMLElement} element The element to put the iframe in.
* @return {HTMLIFrameElement} The iframe embed.
*/
function createEmbed(_ref, element) {
var html = _ref.html;
if (!element) {
throw new TypeError('An element must be provided');
}
if (element.getAttribute('data-vimeo-initialized') !== null) {
return element.querySelector('iframe');
}
var div = document.createElement('div');
div.innerHTML = html;
element.appendChild(div.firstChild);
element.setAttribute('data-vimeo-initialized', 'true');
return element.querySelector('iframe');
}
/**
* Make an oEmbed call for the specified URL.
*
* @param {string} videoUrl The vimeo.com url for the video.
* @param {Object} [params] Parameters to pass to oEmbed.
* @param {HTMLElement} element The element.
* @return {Promise}
*/
function getOEmbedData(videoUrl) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var element = arguments.length > 2 ? arguments[2] : undefined;
return new Promise(function (resolve, reject) {
if (!isVimeoUrl(videoUrl)) {
throw new TypeError("\u201C".concat(videoUrl, "\u201D is not a vimeo.com url."));
}
var url = "https://vimeo.com/api/oembed.json?url=".concat(encodeURIComponent(videoUrl));
for (var param in params) {
if (params.hasOwnProperty(param)) {
url += "&".concat(param, "=").concat(encodeURIComponent(params[param]));
}
}
var xhr = 'XDomainRequest' in window ? new XDomainRequest() : new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function () {
if (xhr.status === 404) {
reject(new Error("\u201C".concat(videoUrl, "\u201D was not found.")));
return;
}
if (xhr.status === 403) {
reject(new Error("\u201C".concat(videoUrl, "\u201D is not embeddable.")));
return;
}
try {
var json = JSON.parse(xhr.responseText); // Check api response for 403 on oembed
if (json.domain_status_code === 403) {
// We still want to create the embed to give users visual feedback
createEmbed(json, element);
reject(new Error("\u201C".concat(videoUrl, "\u201D is not embeddable.")));
return;
}
resolve(json);
} catch (error) {
reject(error);
}
};
xhr.onerror = function () {
var status = xhr.status ? " (".concat(xhr.status, ")") : '';
reject(new Error("There was an error fetching the embed code from Vimeo".concat(status, ".")));
};
xhr.send();
});
}
/**
* Initialize all embeds within a specific element
*
* @param {HTMLElement} [parent=document] The parent element.
* @return {void}
*/
function initializeEmbeds() {
var parent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;
var elements = [].slice.call(parent.querySelectorAll('[data-vimeo-id], [data-vimeo-url]'));
var handleError = function handleError(error) {
if ('console' in window && console.error) {
console.error("There was an error creating an embed: ".concat(error));
}
};
elements.forEach(function (element) {
try {
// Skip any that have data-vimeo-defer
if (element.getAttribute('data-vimeo-defer') !== null) {
return;
}
var params = getOEmbedParameters(element);
var url = getVimeoUrl(params);
getOEmbedData(url, params, element).then(function (data) {
return createEmbed(data, element);
})["catch"](handleError);
} catch (error) {
handleError(error);
}
});
}
/**
* Resize embeds when messaged by the player.
*
* @param {HTMLElement} [parent=document] The parent element.
* @return {void}
*/
function resizeEmbeds() {
var parent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document; // Prevent execution if users include the player.js script multiple times.
if (window.VimeoPlayerResizeEmbeds_) {
return;
}
window.VimeoPlayerResizeEmbeds_ = true;
var onMessage = function onMessage(event) {
if (!isVimeoUrl(event.origin)) {
return;
} // 'spacechange' is fired only on embeds with cards
if (!event.data || event.data.event !== 'spacechange') {
return;
}
var iframes = parent.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) {
if (iframes[i].contentWindow !== event.source) {
continue;
} // Change padding-bottom of the enclosing div to accommodate
// card carousel without distorting aspect ratio
var space = iframes[i].parentElement;
space.style.paddingBottom = "".concat(event.data.data[0].bottom, "px");
break;
}
};
window.addEventListener('message', onMessage);
}
/**
* Add chapters to existing metadata for Google SEO
*
* @param {HTMLElement} [parent=document] The parent element.
* @return {void}
*/
function initAppendVideoMetadata() {
var parent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document; // Prevent execution if users include the player.js script multiple times.
if (window.VimeoSeoMetadataAppended) {
return;
}
window.VimeoSeoMetadataAppended = true;
var onMessage = function onMessage(event) {
if (!isVimeoUrl(event.origin)) {
return;
}
var data = parseMessageData(event.data);
if (!data || data.event !== 'ready') {
return;
}
var iframes = parent.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) {
var iframe = iframes[i]; // Initiate appendVideoMetadata if iframe is a Vimeo embed
var isValidMessageSource = iframe.contentWindow === event.source;
if (isVimeoEmbed(iframe.src) && isValidMessageSource) {
var player = new Player$1(iframe);
player.callMethod('appendVideoMetadata', window.location.href);
}
}
};
window.addEventListener('message', onMessage);
}
/* MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Terms */
function initializeScreenfull() {
var fn = function () {
var val;
var fnMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'], // New WebKit
['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Old WebKit
['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'], ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'], ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']];
var i = 0;
var l = fnMap.length;
var ret = {};
for (; i < l; i++) {
val = fnMap[i];
if (val && val[1] in document) {
for (i = 0; i < val.length; i++) {
ret[fnMap[0][i]] = val[i];
}
return ret;
}
}
return false;
}();
var eventNameMap = {
fullscreenchange: fn.fullscreenchange,
fullscreenerror: fn.fullscreenerror
};
var screenfull = {
request: function request(element) {
return new Promise(function (resolve, reject) {
var onFullScreenEntered = function onFullScreenEntered() {
screenfull.off('fullscreenchange', onFullScreenEntered);
resolve();
};
screenfull.on('fullscreenchange', onFullScreenEntered);