lightbox.js (2316B)
1 let lightboxInit = false; 2 const lightboxHandlers = { 3 keydown: null, 4 }; 5 6 export function initLightbox() { 7 if (lightboxInit) return; 8 9 const lightbox = document.getElementById("image-lightbox"); 10 const lightboxImage = lightbox?.querySelector(".lightbox-image"); 11 const lightboxOverlay = lightbox?.querySelector(".lightbox-overlay"); 12 const lightboxClose = lightbox?.querySelector(".lightbox-close"); 13 if (!lightbox || !lightboxImage) return; 14 15 let lightboxImages = []; 16 let currentLightboxIndex = 0; 17 18 window.isLightboxOpen = () => !lightbox.classList.contains("hidden"); 19 window.openLightbox = (images, startIndex = 0) => { 20 if (!Array.isArray(images) || images.length === 0) return; 21 22 lightboxImages = images; 23 currentLightboxIndex = startIndex; 24 lightboxImage.src = images[startIndex]; 25 lightbox.classList.remove("hidden"); 26 }; 27 28 function closeLightbox() { 29 lightbox.classList.add("hidden"); 30 lightboxImages = []; 31 currentLightboxIndex = 0; 32 } 33 34 function navigateLightboxImage(direction) { 35 if (lightboxImages.length <= 1) return; 36 37 let delta = 0; 38 switch (direction) { 39 case "left": 40 delta = -1; 41 break; 42 case "right": 43 delta = 1; 44 break; 45 default: 46 return; 47 } 48 49 currentLightboxIndex = 50 (currentLightboxIndex + delta + lightboxImages.length) % lightboxImages.length; 51 lightboxImage.src = lightboxImages[currentLightboxIndex]; 52 } 53 54 window.navigateLightboxImage = navigateLightboxImage; 55 56 lightboxOverlay?.addEventListener("click", closeLightbox); 57 lightboxClose?.addEventListener("click", closeLightbox); 58 59 if (lightboxHandlers.keydown) { 60 document.removeEventListener("keydown", lightboxHandlers.keydown); 61 } 62 63 lightboxHandlers.keydown = (e) => { 64 if (lightbox.classList.contains("hidden")) return; 65 66 switch (e.key) { 67 case "Escape": 68 closeLightbox(); 69 break; 70 case "ArrowLeft": 71 e.preventDefault(); 72 e.stopPropagation(); 73 navigateLightboxImage("left"); 74 break; 75 case "ArrowRight": 76 e.preventDefault(); 77 e.stopPropagation(); 78 navigateLightboxImage("right"); 79 break; 80 default: 81 break; 82 } 83 }; 84 85 document.addEventListener("keydown", lightboxHandlers.keydown); 86 lightboxInit = true; 87 }