UNPKG

@codesweetly/react-youtube-playlist

Version:

A simple video gallery with a lightbox for displaying YouTube playlists in React apps.

244 lines (243 loc) 16.6 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; import React, { useRef, useEffect, useState } from "react"; import { youTubePlaylistStyles } from "./youTubePlaylistStyles"; import getPlaylistData from "./getPlaylistData"; export function YouTubePlaylist(_a) { var apiKey = _a.apiKey, playlistId = _a.playlistId, _b = _a.columnCount, columnCount = _b === void 0 ? "auto" : _b, _c = _a.columnWidth, columnWidth = _c === void 0 ? 230 : _c, _d = _a.gapSize, gapSize = _d === void 0 ? 24 : _d, _e = _a.customStyles, customStyles = _e === void 0 ? {} : _e; var _f = useState(""), videoId = _f[0], setVideoId = _f[1]; var _g = useState(1), slideNumber = _g[0], setSlideNumber = _g[1]; var _h = useState(null), playlistDataArray = _h[0], setPlaylistDataArray = _h[1]; var _j = useState(false), showModalControls = _j[0], setShowModalControls = _j[1]; var _k = useState(false), fullscreen = _k[0], setFullscreen = _k[1]; var lastCardRef = useRef(null); var dialogRef = useRef(null); var lightboxRef = useRef(null); var defaultStyles = youTubePlaylistStyles(columnCount, columnWidth, gapSize); var playlistStyles = __assign(__assign({}, defaultStyles), customStyles); var loaderContainerStyle = playlistStyles.loaderContainerStyle; var galleryContainerStyle = playlistStyles.galleryContainerStyle; var imageBtnStyle = playlistStyles.imageBtnStyle; var videoContainerStyle = playlistStyles.videoContainerStyle; var videoImageStyle = playlistStyles.videoImageStyle; var videoCaptionStyle = playlistStyles.videoCaptionStyle; var modalContainerStyle = playlistStyles.modalContainerStyle; var modalSlideNumberStyle = playlistStyles.modalSlideNumberStyle; var modalToolbarStyle = playlistStyles.modalToolbarStyle; var modalToolbarBtnStyle = playlistStyles.modalToolbarBtnStyle; var modalSlideShowSectionStyle = playlistStyles.modalSlideShowSectionStyle; var modalIFrameStyle = playlistStyles.modalIFrameStyle; var modalSlideBtnStyle = playlistStyles.modalSlideBtnStyle; function openLightboxOnSlide(vId, number) { var _a; setVideoId(vId); setSlideNumber(number); (_a = dialogRef.current) === null || _a === void 0 ? void 0 : _a.showModal(); } function changeSlide(directionNumber) { var totalVideos = playlistDataArray === null || playlistDataArray === void 0 ? void 0 : playlistDataArray.length; var newSlideNumber = slideNumber + directionNumber; if (totalVideos) { newSlideNumber < 1 && (newSlideNumber = totalVideos); newSlideNumber > totalVideos && (newSlideNumber = 1); if (newSlideNumber <= totalVideos && newSlideNumber > 0) { setVideoId(playlistDataArray[newSlideNumber - 1].resourceId.videoId); setSlideNumber(newSlideNumber); } } } function switchFullScreen(on) { var _a; if (on) { (_a = lightboxRef.current) === null || _a === void 0 ? void 0 : _a.requestFullscreen().catch(function (error) { alert("Error while attempting to switch into fullscreen mode: ".concat(error.message, " (").concat(error.name, ")")); }); } if (!on) { document.exitFullscreen().catch(function (error) { return console.error(error); }); } } function handleKeyDownOnModal(e) { e.key === "ArrowLeft" && changeSlide(-1); e.key === "ArrowRight" && changeSlide(1); e.key === "f" && fullscreen && switchFullScreen(false); e.key === "f" && !fullscreen && switchFullScreen(true); } function exitFullScreenAndDialog() { var _a; setVideoId(""); (_a = dialogRef.current) === null || _a === void 0 ? void 0 : _a.close(); fullscreen && switchFullScreen(false); } function SvgElement(pathElement) { return (React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "20", height: "20", fill: "currentColor", viewBox: "0 0 16 16" }, pathElement)); } function saveSubsequentPlaylistData() { return __awaiter(this, void 0, void 0, function () { var lastGalleryItem, newPlaylistData, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!playlistDataArray) return [3, 4]; lastGalleryItem = playlistDataArray[playlistDataArray.length - 1]; _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4, getPlaylistData(apiKey, playlistId, lastGalleryItem.nextPageToken)]; case 2: newPlaylistData = _a.sent(); setPlaylistDataArray(__spreadArray(__spreadArray([], playlistDataArray, true), newPlaylistData, true)); return [3, 4]; case 3: e_1 = _a.sent(); console.error("Error getting next page playlist data: ".concat(e_1)); return [3, 4]; case 4: return [2]; } }); }); } function showVideoCards() { return playlistDataArray === null || playlistDataArray === void 0 ? void 0 : playlistDataArray.map(function (item, index) { if (item.title !== "Deleted video" && item.title !== "Private video") { return (React.createElement("button", { type: "button", ref: index + 1 === playlistDataArray.length ? lastCardRef : null, style: imageBtnStyle, key: item.id, onKeyDown: function (e) { return e.key === "Enter" && openLightboxOnSlide(item.resourceId.videoId, index + 1); } }, React.createElement("figure", { style: videoContainerStyle }, React.createElement("img", { alt: "Video ".concat(index + 1, " of ").concat(playlistDataArray.length), src: item.thumbnails.high.url, onClick: function () { return openLightboxOnSlide(item.resourceId.videoId, index + 1); }, style: videoImageStyle }), React.createElement("figcaption", { style: videoCaptionStyle }, item.title)))); } else { return ""; } }); } var galleryElement = playlistDataArray ? (React.createElement("div", { style: galleryContainerStyle }, showVideoCards())) : (React.createElement("div", { style: loaderContainerStyle }, "Loading...")); var lightBoxElement = (React.createElement("dialog", { ref: dialogRef, style: { margin: "auto" } }, React.createElement("article", { autoFocus: true, tabIndex: -1, ref: lightboxRef, style: modalContainerStyle, onKeyDown: function (e) { return handleKeyDownOnModal(e); }, onMouseEnter: function () { return setShowModalControls(true); }, onMouseLeave: function () { return setShowModalControls(false); }, onClick: function (e) { return e.target.tagName === "SECTION" && exitFullScreenAndDialog(); } }, React.createElement("span", { style: __assign({ opacity: showModalControls ? 1 : 0 }, modalSlideNumberStyle) }, "".concat(slideNumber, " / ").concat(playlistDataArray === null || playlistDataArray === void 0 ? void 0 : playlistDataArray.length)), React.createElement("span", { style: __assign({ opacity: showModalControls ? 1 : 0 }, modalToolbarStyle) }, React.createElement("button", { type: "button", "aria-label": "Go full screen (Keyboard shortcut f)", style: __assign({ display: fullscreen ? "none" : "block" }, modalToolbarBtnStyle), title: "Go full screen (f)", onClick: function () { return switchFullScreen(true); } }, SvgElement(React.createElement("path", { d: "M1.5 1a.5.5 0 0 0-.5.5v4a.5.5 0 0 1-1 0v-4A1.5 1.5 0 0 1 1.5 0h4a.5.5 0 0 1 0 1zM10 .5a.5.5 0 0 1 .5-.5h4A1.5 1.5 0 0 1 16 1.5v4a.5.5 0 0 1-1 0v-4a.5.5 0 0 0-.5-.5h-4a.5.5 0 0 1-.5-.5M.5 10a.5.5 0 0 1 .5.5v4a.5.5 0 0 0 .5.5h4a.5.5 0 0 1 0 1h-4A1.5 1.5 0 0 1 0 14.5v-4a.5.5 0 0 1 .5-.5m15 0a.5.5 0 0 1 .5.5v4a1.5 1.5 0 0 1-1.5 1.5h-4a.5.5 0 0 1 0-1h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 1 .5-.5" }))), React.createElement("button", { type: "button", "aria-label": "Exit full screen", style: __assign({ display: fullscreen ? "block" : "none" }, modalToolbarBtnStyle), title: "Exit full screen", onClick: function () { return switchFullScreen(false); } }, SvgElement(React.createElement("path", { d: "M5.5 0a.5.5 0 0 1 .5.5v4A1.5 1.5 0 0 1 4.5 6h-4a.5.5 0 0 1 0-1h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 1 .5-.5m5 0a.5.5 0 0 1 .5.5v4a.5.5 0 0 0 .5.5h4a.5.5 0 0 1 0 1h-4A1.5 1.5 0 0 1 10 4.5v-4a.5.5 0 0 1 .5-.5M0 10.5a.5.5 0 0 1 .5-.5h4A1.5 1.5 0 0 1 6 11.5v4a.5.5 0 0 1-1 0v-4a.5.5 0 0 0-.5-.5h-4a.5.5 0 0 1-.5-.5m10 1a1.5 1.5 0 0 1 1.5-1.5h4a.5.5 0 0 1 0 1h-4a.5.5 0 0 0-.5.5v4a.5.5 0 0 1-1 0z" }))), React.createElement("button", { type: "button", "aria-label": "Close lightbox", style: modalToolbarBtnStyle, title: "Close lightbox", onClick: function () { return exitFullScreenAndDialog(); } }, SvgElement(React.createElement("path", { d: "M2.146 2.854a.5.5 0 1 1 .708-.708L8 7.293l5.146-5.147a.5.5 0 0 1 .708.708L8.707 8l5.147 5.146a.5.5 0 0 1-.708.708L8 8.707l-5.146 5.147a.5.5 0 0 1-.708-.708L7.293 8z" })))), React.createElement("section", { style: modalSlideShowSectionStyle }, React.createElement("button", { type: "button", "aria-label": "Previous image", style: __assign({ opacity: showModalControls ? 1 : 0, left: 0 }, modalSlideBtnStyle), title: "Previous image", onClick: function () { return changeSlide(-1); } }, SvgElement(React.createElement("path", { fillRule: "evenodd", d: "M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8" }))), React.createElement("iframe", { style: modalIFrameStyle, src: "https://www.youtube.com/embed/".concat(videoId, "?v=").concat(videoId), title: "YouTube video player", referrerPolicy: "strict-origin-when-cross-origin", allowFullScreen: true }), React.createElement("button", { type: "button", "aria-label": "Next image", style: __assign({ opacity: showModalControls ? 1 : 0, right: 0 }, modalSlideBtnStyle), title: "Next image", onClick: function () { return changeSlide(1); } }, SvgElement(React.createElement("path", { fillRule: "evenodd", d: "M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8" }))))))); useEffect(function () { function saveInitialPlaylistData() { return __awaiter(this, void 0, void 0, function () { var newPlaylistData, e_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4, getPlaylistData(apiKey, playlistId)]; case 1: newPlaylistData = _a.sent(); setPlaylistDataArray(newPlaylistData); return [3, 3]; case 2: e_2 = _a.sent(); console.error("Error getting playlist data: ".concat(e_2)); return [3, 3]; case 3: return [2]; } }); }); } saveInitialPlaylistData(); }, [apiKey, playlistId]); useEffect(function () { function observeLastCard(entries) { var moreVideosAvailable = playlistDataArray && playlistDataArray.length < playlistDataArray[0].totalVideosAvailable; entries[0].isIntersecting && moreVideosAvailable && saveSubsequentPlaylistData(); } var videoCardObserver = new IntersectionObserver(observeLastCard); lastCardRef.current && videoCardObserver.observe(lastCardRef.current); return function () { return videoCardObserver.disconnect(); }; }, [playlistDataArray]); useEffect(function () { function handleFullscreenChange() { var _a; setFullscreen(Boolean(document.fullscreenElement)); (_a = lightboxRef.current) === null || _a === void 0 ? void 0 : _a.focus(); } document.addEventListener("fullscreenchange", handleFullscreenChange); return function () { return document.removeEventListener("fullscreenchange", handleFullscreenChange); }; }, []); useEffect(function () { var _a, _b; ((_a = dialogRef.current) === null || _a === void 0 ? void 0 : _a.open) && (document.documentElement.style.overflow = "hidden"); !((_b = dialogRef.current) === null || _b === void 0 ? void 0 : _b.open) && (document.documentElement.style.overflow = ""); }); return (React.createElement(React.Fragment, null, galleryElement, lightBoxElement)); }