UNPKG

react-player

Version:

A React component for playing a variety of URLs, including file paths, YouTube, Facebook, Twitch, SoundCloud, Streamable, Vimeo, Wistia and DailyMotion

349 lines (284 loc) • 15.5 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireWildcard(require("react")); var _utils = require("../utils"); var _patterns = require("../patterns"); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } 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; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(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; } var SDK_URL = 'https://www.youtube.com/iframe_api'; var SDK_GLOBAL = 'YT'; var SDK_GLOBAL_READY = 'onYouTubeIframeAPIReady'; var MATCH_PLAYLIST = /[?&](?:list|channel)=([a-zA-Z0-9_-]+)/; var MATCH_USER_UPLOADS = /user\/([a-zA-Z0-9_-]+)\/?/; var MATCH_NOCOOKIE = /youtube-nocookie\.com/; var NOCOOKIE_HOST = 'https://www.youtube-nocookie.com'; var YouTube = /*#__PURE__*/function (_Component) { _inherits(YouTube, _Component); var _super = _createSuper(YouTube); function YouTube() { var _this; _classCallCheck(this, YouTube); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _super.call.apply(_super, [this].concat(args)); _defineProperty(_assertThisInitialized(_this), "callPlayer", _utils.callPlayer); _defineProperty(_assertThisInitialized(_this), "parsePlaylist", function (url) { if (url instanceof Array) { return { listType: 'playlist', playlist: url.map(_this.getID).join(',') }; } if (MATCH_PLAYLIST.test(url)) { var _url$match = url.match(MATCH_PLAYLIST), _url$match2 = _slicedToArray(_url$match, 2), playlistId = _url$match2[1]; return { listType: 'playlist', list: playlistId.replace(/^UC/, 'UU') }; } if (MATCH_USER_UPLOADS.test(url)) { var _url$match3 = url.match(MATCH_USER_UPLOADS), _url$match4 = _slicedToArray(_url$match3, 2), username = _url$match4[1]; return { listType: 'user_uploads', list: username }; } return {}; }); _defineProperty(_assertThisInitialized(_this), "onStateChange", function (event) { var data = event.data; var _this$props = _this.props, onPlay = _this$props.onPlay, onPause = _this$props.onPause, onBuffer = _this$props.onBuffer, onBufferEnd = _this$props.onBufferEnd, onEnded = _this$props.onEnded, onReady = _this$props.onReady, loop = _this$props.loop, _this$props$config = _this$props.config, playerVars = _this$props$config.playerVars, onUnstarted = _this$props$config.onUnstarted; var _window$SDK_GLOBAL$Pl = window[SDK_GLOBAL].PlayerState, UNSTARTED = _window$SDK_GLOBAL$Pl.UNSTARTED, PLAYING = _window$SDK_GLOBAL$Pl.PLAYING, PAUSED = _window$SDK_GLOBAL$Pl.PAUSED, BUFFERING = _window$SDK_GLOBAL$Pl.BUFFERING, ENDED = _window$SDK_GLOBAL$Pl.ENDED, CUED = _window$SDK_GLOBAL$Pl.CUED; if (data === UNSTARTED) onUnstarted(); if (data === PLAYING) { onPlay(); onBufferEnd(); } if (data === PAUSED) onPause(); if (data === BUFFERING) onBuffer(); if (data === ENDED) { var isPlaylist = !!_this.callPlayer('getPlaylist'); // Only loop manually if not playing a playlist if (loop && !isPlaylist) { if (playerVars.start) { _this.seekTo(playerVars.start); } else { _this.play(); } } onEnded(); } if (data === CUED) onReady(); }); _defineProperty(_assertThisInitialized(_this), "mute", function () { _this.callPlayer('mute'); }); _defineProperty(_assertThisInitialized(_this), "unmute", function () { _this.callPlayer('unMute'); }); _defineProperty(_assertThisInitialized(_this), "ref", function (container) { _this.container = container; }); return _this; } _createClass(YouTube, [{ key: "componentDidMount", value: function componentDidMount() { this.props.onMount && this.props.onMount(this); } }, { key: "getID", value: function getID(url) { if (!url || url instanceof Array || MATCH_PLAYLIST.test(url)) { return null; } return url.match(_patterns.MATCH_URL_YOUTUBE)[1]; } }, { key: "load", value: function load(url, isReady) { var _this2 = this; var _this$props2 = this.props, playing = _this$props2.playing, muted = _this$props2.muted, playsinline = _this$props2.playsinline, controls = _this$props2.controls, loop = _this$props2.loop, config = _this$props2.config, _onError = _this$props2.onError; var playerVars = config.playerVars, embedOptions = config.embedOptions; var id = this.getID(url); if (isReady) { if (MATCH_PLAYLIST.test(url) || MATCH_USER_UPLOADS.test(url) || url instanceof Array) { this.player.loadPlaylist(this.parsePlaylist(url)); return; } this.player.cueVideoById({ videoId: id, startSeconds: (0, _utils.parseStartTime)(url) || playerVars.start, endSeconds: (0, _utils.parseEndTime)(url) || playerVars.end }); return; } (0, _utils.getSDK)(SDK_URL, SDK_GLOBAL, SDK_GLOBAL_READY, function (YT) { return YT.loaded; }).then(function (YT) { if (!_this2.container) return; _this2.player = new YT.Player(_this2.container, _objectSpread({ width: '100%', height: '100%', videoId: id, playerVars: _objectSpread(_objectSpread({ autoplay: playing ? 1 : 0, mute: muted ? 1 : 0, controls: controls ? 1 : 0, start: (0, _utils.parseStartTime)(url), end: (0, _utils.parseEndTime)(url), origin: window.location.origin, playsinline: playsinline ? 1 : 0 }, _this2.parsePlaylist(url)), playerVars), events: { onReady: function onReady() { if (loop) { _this2.player.setLoop(true); // Enable playlist looping } _this2.props.onReady(); }, onPlaybackRateChange: function onPlaybackRateChange(event) { return _this2.props.onPlaybackRateChange(event.data); }, onPlaybackQualityChange: function onPlaybackQualityChange(event) { return _this2.props.onPlaybackQualityChange(event); }, onStateChange: _this2.onStateChange, onError: function onError(event) { return _onError(event.data); } }, host: MATCH_NOCOOKIE.test(url) ? NOCOOKIE_HOST : undefined }, embedOptions)); }, _onError); if (embedOptions.events) { console.warn('Using `embedOptions.events` will likely break things. Use ReactPlayer’s callback props instead, eg onReady, onPlay, onPause'); } } }, { key: "play", value: function play() { this.callPlayer('playVideo'); } }, { key: "pause", value: function pause() { this.callPlayer('pauseVideo'); } }, { key: "stop", value: function stop() { if (!document.body.contains(this.callPlayer('getIframe'))) return; this.callPlayer('stopVideo'); } }, { key: "seekTo", value: function seekTo(amount) { var keepPlaying = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; this.callPlayer('seekTo', amount); if (!keepPlaying && !this.props.playing) { this.pause(); } } }, { key: "setVolume", value: function setVolume(fraction) { this.callPlayer('setVolume', fraction * 100); } }, { key: "setPlaybackRate", value: function setPlaybackRate(rate) { this.callPlayer('setPlaybackRate', rate); } }, { key: "setLoop", value: function setLoop(loop) { this.callPlayer('setLoop', loop); } }, { key: "getDuration", value: function getDuration() { return this.callPlayer('getDuration'); } }, { key: "getCurrentTime", value: function getCurrentTime() { return this.callPlayer('getCurrentTime'); } }, { key: "getSecondsLoaded", value: function getSecondsLoaded() { return this.callPlayer('getVideoLoadedFraction') * this.getDuration(); } }, { key: "render", value: function render() { var display = this.props.display; var style = { width: '100%', height: '100%', display: display }; return /*#__PURE__*/_react["default"].createElement("div", { style: style }, /*#__PURE__*/_react["default"].createElement("div", { ref: this.ref })); } }]); return YouTube; }(_react.Component); exports["default"] = YouTube; _defineProperty(YouTube, "displayName", 'YouTube'); _defineProperty(YouTube, "canPlay", _patterns.canPlay.youtube);