From 5c5910f1fc661ec3dce203ac961c7f64f1991895 Mon Sep 17 00:00:00 2001 From: Cotes Chung <11371340+cotes2020@users.noreply.github.com> Date: Mon, 29 Jul 2024 12:17:11 +0800 Subject: [PATCH] fix: remove extra dual-mode images from lightbox (#1883) --- _javascript/modules/components/img-popup.js | 41 +++++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/_javascript/modules/components/img-popup.js b/_javascript/modules/components/img-popup.js index b5c7c6e..6c3e733 100644 --- a/_javascript/modules/components/img-popup.js +++ b/_javascript/modules/components/img-popup.js @@ -4,12 +4,47 @@ * Dependencies: https://github.com/biati-digital/glightbox */ -const IMG_CLASS = 'popup'; +const html = document.documentElement; +const lightImages = '.popup:not(.dark)'; +const darkImages = '.popup:not(.light)'; +let selector = lightImages; + +function updateImages(lightbox) { + if (selector === lightImages) { + selector = darkImages; + } else { + selector = lightImages; + } + + lightbox.destroy(); + lightbox = GLightbox({ selector: `${selector}` }); +} export function imgPopup() { - if (document.getElementsByClassName(IMG_CLASS).length === 0) { + if (document.querySelector('.popup') === null) { return; } - GLightbox({ selector: `.${IMG_CLASS}` }); + if ( + (html.hasAttribute('data-mode') && + html.getAttribute('data-mode') === 'dark') || + (!html.hasAttribute('data-mode') && + window.matchMedia('(prefers-color-scheme: dark)').matches) + ) { + selector = darkImages; + } + + let lightbox = GLightbox({ selector: `${selector}` }); + + if (document.getElementById('mode-toggle')) { + window.addEventListener('message', (event) => { + if ( + event.source === window && + event.data && + event.data.direction === ModeToggle.ID + ) { + updateImages(lightbox); + } + }); + } }