diff --git a/Resources/Public/JavaScript/sgYoutubeLightbox.js b/Resources/Public/JavaScript/sgYoutubeLightbox.js index d4f760f48b395f311bc8b0292bc21ba58f9bb4ff..0f3e2377f45f714d0d218618b38c8a98f7e53918 100644 --- a/Resources/Public/JavaScript/sgYoutubeLightbox.js +++ b/Resources/Public/JavaScript/sgYoutubeLightbox.js @@ -8,7 +8,69 @@ export default class SgYoutubeLightbox { * Initializes the LightboxManager with the necessary parameters. */ constructor() { + const youtubeItems = document.querySelectorAll('.sg-youtube-item'); + const isMobile = window.matchMedia('(max-width: 679px)').matches; + + youtubeItems.forEach((item) => { + if (item.dataset.disableLightboxMobile === '1' && isMobile || item.dataset.disableLightbox === '1' && !isMobile) { + item.classList.remove('sg-youtube-item'); + item.addEventListener('click', this.disableLightbox.bind(this)); + } + }); + LightboxManager.init({type: 'video', glightbox: {selector: '.sg-youtube-item'}}); } + + /** + * Replace the image with an iframe + * + * @param event + */ + disableLightbox(event) { + event.preventDefault(); + const item = event.currentTarget; + item.classList.add('no-lightbox'); + + const videoId = this.getVideoIdFromUrl(item.href); + const videoImage = item.querySelector('.sg-video__image'); + const height = videoImage.offsetHeight; + const width = videoImage.offsetWidth; + + const iframe = document.createElement('iframe'); + iframe.width = width; + iframe.height = height; + iframe.style.border = 'none'; + iframe.allowFullscreen = true; + iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture'; + iframe.src = `https://www.youtube-nocookie.com/embed/${videoId}`; + + item.replaceChild(iframe, videoImage); + } + + /** + * Prepares the given url, or returns null. + * + * @param {string} url + * @return {string|null} + */ + getVideoIdFromUrl(url) { + let matches = url.match(/watch\?v=(.*)&list=(.*)/); + if (!matches) { + // check if the list parameter is missing + matches = url.match(/watch\?v=([^?&]*)/); + if (!matches) { + return null; + } + } + let [, videoString] = matches, + queryParameterSeparator = '?'; + if (matches[2]) { + videoString += '?list=' + matches[2]; + queryParameterSeparator = '&'; + + } + + return videoString + queryParameterSeparator + 'autoplay=1&rel=0'; + } }