Advertisement
artemsemkin

Rhye HTML5 Template - gallery iFrame support

Oct 27th, 2020 (edited)
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* ======================================================================== */
  2. /* 4. Pswp */
  3. /* ======================================================================== */
  4. class Pswp extends BaseComponent {
  5.   constructor({
  6.     scope,
  7.     target,
  8.     options
  9.   }) {
  10.     super({
  11.       scope,
  12.       target
  13.     });
  14.     this.options = options || {
  15.       history: false,
  16.       showAnimationDuration: 300,
  17.     };
  18.     this._setGalleriesID();
  19.     this.$pswpEl = $('.pswp');
  20.     this.$container = this.$pswpEl.find('.pswp__container');
  21.     this.pswpEl = this.$pswpEl.get(0);
  22.   }
  23.  
  24.   _bindEvents() {
  25.     const eventTouchUp = new CustomEvent('arts/pswp/touchUp', {
  26.         detail: {
  27.           direction: 'all'
  28.         }
  29.       }),
  30.       eventTouchDown = new CustomEvent('arts/pswp/touchDown', {
  31.         detail: {
  32.           direction: 'all'
  33.         }
  34.       }),
  35.       eventClose = new CustomEvent('arts/pswp/close'),
  36.       eventSlideChange = new CustomEvent('arts/pswp/slideChange');
  37.  
  38.     this.$pswpEl
  39.       .off('click')
  40.       .on('click', '.pswp__button--arrow--left', (e) => {
  41.         e.preventDefault();
  42.         this.gallery.prev();
  43.       }).on('click', '.pswp__button--arrow--right', (e) => {
  44.         e.preventDefault();
  45.         this.gallery.next();
  46.       });
  47.  
  48.     window.$window.on('arts/barba/transition/start', () => {
  49.       if (typeof this.gallery === 'object' && this.gallery.destroy === 'function') {
  50.         this.gallery.destroy();
  51.       }
  52.     });
  53.  
  54.     // Dispatch cursor events
  55.     this.gallery.listen('preventDragEvent', (e, isDown, preventObj) => {
  56.       preventObj.prevent = false;
  57.       if ($(e.target).is('.pswp--zoomed-in .pswp__img')) {
  58.         if (isDown) {
  59.           document.dispatchEvent(eventTouchDown);
  60.         } else {
  61.           document.dispatchEvent(eventTouchUp);
  62.         }
  63.       }
  64.     });
  65.  
  66.     this.gallery.listen('close', () => {
  67.       document.dispatchEvent(eventClose);
  68.       this.$pswpEl.find('iframe, video').remove();
  69.     });
  70.  
  71.     this.gallery.listen('beforeChange', (e) => {
  72.       document.dispatchEvent(eventSlideChange);
  73.       this._stopVideo();
  74.     });
  75.   }
  76.  
  77.   _openPhotoSwipe({
  78.     index = 0,
  79.     galleryElement = null,
  80.     disableAnimation = false,
  81.     fromURL = false
  82.   }) {
  83.     const
  84.       items = this._getItems(galleryElement),
  85.       options = {
  86.         galleryUID: galleryElement.attr('data-pswp-uid')
  87.       };
  88.  
  89.     if (typeof items[index] !== 'undefined' && 'el' in items[index]) {
  90.       options.getThumbBoundsFn = function (index) {
  91.         let
  92.           pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
  93.           img = items[index].el.querySelector('img'),
  94.           rect;
  95.  
  96.         if (img) {
  97.           rect = img.getBoundingClientRect();
  98.           return {
  99.             x: rect.left,
  100.             y: rect.top + pageYScroll,
  101.             w: rect.width
  102.           }
  103.         }
  104.       }
  105.     }
  106.  
  107.     // PhotoSwipe opened from URL
  108.     if (fromURL) {
  109.       if (options.galleryPIDs) {
  110.         // parse real index when custom PIDs are used
  111.         // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
  112.         for (let j = 0; j < items.length; j++) {
  113.           if (items[j].pid == index) {
  114.             options.index = j;
  115.             break;
  116.           }
  117.         }
  118.       } else {
  119.         // in URL indexes start from 1
  120.         options.index = parseInt(index, 10) - 1;
  121.       }
  122.     } else {
  123.       options.index = parseInt(index, 10);
  124.     }
  125.  
  126.     // exit if index not found
  127.     if (isNaN(options.index)) {
  128.       return;
  129.     }
  130.  
  131.     if (disableAnimation) {
  132.       options.showAnimationDuration = 0;
  133.     }
  134.  
  135.     // Pass data to PhotoSwipe and initialize it
  136.     this.gallery = new PhotoSwipe(this.pswpEl, PhotoSwipeUI_Default, items, $.extend(options, this.options));
  137.     this.gallery.init();
  138.  
  139.     this._bindEvents();
  140.   }
  141.  
  142.   _getMediaTypeFromURL(url, size, autoplay = false) {
  143.     const
  144.       result = {
  145.         type: false,
  146.         html: null
  147.       },
  148.       iframeSize = size ? size.split('x') : [640, 360],
  149.       attr = {
  150.         video: autoplay ? 'muted playsinline loop autoplay' : '',
  151.       },
  152.       param = {
  153.         youtube: autoplay ? 'autoplay=1' : '',
  154.         vimeo: autoplay ? 'autoplay=1' : ''
  155.       },
  156.       pattern = {
  157.         image: /([-a-zA-Z0-9@:%_\+.~#?&\/\/=]{2,256}(\/[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)?\.(?:jpg|jpeg|jfif|pjpeg|pjp|bmp|gif|png|apng|webp|svg))/gi,
  158.         video: /([-a-zA-Z0-9@:%_\+.~#?&\/\/=]{2,256}(\/[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)?\.(?:mp4|ogv|webm))/gi,
  159.         youtube: /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=|embed\/)([^&|?|\/]*)/g,
  160.         vimeo: /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/(?:.*\/)?(.+)/g,
  161.       };
  162.  
  163.     /**
  164.      * Image
  165.      */
  166.     if (pattern.image.test(url)) {
  167.       result.type = 'image';
  168.       return result;
  169.     }
  170.  
  171.     /**
  172.      * HTML5 video
  173.      */
  174.     if (pattern.video.test(url)) {
  175.       result.type = 'video';
  176.       result.html = `<video src="${url}" controls ${attr.video}></video>`;
  177.       return result;
  178.     }
  179.  
  180.     /**
  181.      * YouTube link
  182.      */
  183.     if (pattern.youtube.test(url)) {
  184.       result.type = 'youtube';
  185.       result.html = url.replace(pattern.youtube, `<iframe class="iframe-youtube" width="${parseInt(iframeSize[0])}" height="${parseInt(iframeSize[1])}" src="https://www.youtube.com/embed/$1?${param.youtube}&enablejsapi=1" frameborder="0" allow="autoplay; accelerometer; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`);
  186.       return result;
  187.     }
  188.  
  189.     /**
  190.      * Vimeo link
  191.      */
  192.     if (pattern.vimeo.test(url)) {
  193.       result.type = 'vimeo';
  194.       result.html = url.replace(pattern.vimeo, `<iframe class="iframe-vimeo" width="${parseInt(iframeSize[0])}" height="${parseInt(iframeSize[1])}" src="https://player.vimeo.com/video/$1?${param.vimeo}" frameborder="0" allow="autoplay; fullscreen" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>`);
  195.       return result;
  196.     }
  197.  
  198.     /**
  199.      * Fallback iFrame
  200.      */
  201.     result.type = 'iframe';
  202.     result.html = `<iframe width="${parseInt(iframeSize[0])}" height="${parseInt(iframeSize[1])}" src=${url} frameborder="0" allowfullscreen></iframe>`;
  203.  
  204.     return result;
  205.   }
  206.  
  207.   _getItems($galleryElement) {
  208.     const
  209.       self = this,
  210.       $items = $galleryElement.find('a'),
  211.       items = [];
  212.  
  213.     $items.each(function () {
  214.       const $el = $(this),
  215.         item = {},
  216.         size = $el.attr('data-size'),
  217.         autoplay = $el.attr('data-autoplay'),
  218.         src = $el.attr('href'),
  219.         media = self._getMediaTypeFromURL(src, size, autoplay),
  220.         title = $el.attr('data-title');
  221.  
  222.       if (size) {
  223.         const sizeSplit = size.split('x');
  224.         item.w = parseInt(sizeSplit[0], 10);
  225.         item.h = parseInt(sizeSplit[1], 10);
  226.       }
  227.  
  228.       if (title) {
  229.         item.title = title;
  230.       }
  231.  
  232.       switch (media.type) {
  233.         case 'youtube':
  234.           item.html = `<div class="pswp__wrapper-embed">${media.html}</div>`;
  235.           break;
  236.         case 'vimeo':
  237.           item.html = `<div class="pswp__wrapper-embed">${media.html}</div>`;
  238.           break;
  239.         case 'video':
  240.           item.html = `<div class="pswp__wrapper-embed">${media.html}</div>`;
  241.           break;
  242.         case 'image':
  243.           item.el = $el.get(0);
  244.           item.src = src;
  245.           item.msrc = $el.find('img').attr('src');
  246.           break;
  247.         default:
  248.           item.html = `<div class="pswp__wrapper-embed">${media.html}</div>`;
  249.       }
  250.       items.push(item);
  251.     });
  252.  
  253.     return items;
  254.   }
  255.  
  256.   _photoswipeParseHash() {
  257.     const
  258.       hash = window.location.hash.substring(1),
  259.       params = {};
  260.  
  261.     if (hash.length < 5) {
  262.       return params;
  263.     }
  264.  
  265.     const vars = hash.split('&');
  266.     for (let i = 0; i < vars.length; i++) {
  267.       if (!vars[i]) {
  268.         continue;
  269.       }
  270.       let pair = vars[i].split('=');
  271.       if (pair.length < 2) {
  272.         continue;
  273.       }
  274.       params[pair[0]] = pair[1];
  275.     }
  276.  
  277.     if (params.gid) {
  278.       params.gid = parseInt(params.gid, 10);
  279.     }
  280.  
  281.     return params;
  282.   }
  283.  
  284.   _setGalleriesID() {
  285.     this.$target.each(function (index) {
  286.       $(this).attr('data-pswp-uid', index + 1);
  287.     });
  288.   }
  289.  
  290.   _stopVideo() {
  291.     const
  292.       $iframeYoutube = this.$pswpEl.find('.iframe-youtube'),
  293.       $iframeVimeo = this.$pswpEl.find('.iframe-vimeo'),
  294.       $video = this.$pswpEl.find('video');
  295.  
  296.     if ($iframeYoutube.length) {
  297.       $iframeYoutube.each(function () {
  298.         $(this).get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
  299.       });
  300.     }
  301.  
  302.     if ($iframeVimeo.length) {
  303.       $iframeVimeo.each(function () {
  304.         $(this).get(0).contentWindow.postMessage('{"method":"pause"}', '*');
  305.       });
  306.     }
  307.  
  308.     if ($video.length) {
  309.       $video.each(function () {
  310.         $(this).get(0).pause();
  311.       });
  312.     }
  313.   }
  314. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement