From 555a715e8f2060d54d6e79c21eda29db1b1b7bec Mon Sep 17 00:00:00 2001
From: Michael Kessler <michael.kessler@sgalinski.de>
Date: Thu, 11 Nov 2021 11:06:25 +0100
Subject: [PATCH] [TASK] Add disable lightbox functionality

---
 .../Public/JavaScript/sgYoutubeLightbox.js    | 62 +++++++++++++++++++
 1 file changed, 62 insertions(+)

diff --git a/Resources/Public/JavaScript/sgYoutubeLightbox.js b/Resources/Public/JavaScript/sgYoutubeLightbox.js
index d4f760f..0f3e237 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';
+	}
 }
 
-- 
GitLab