From 2d70d0cd18d33a2fd6159d14fc26fad21934f41e Mon Sep 17 00:00:00 2001 From: Ivan Reshetnikov Date: Tue, 5 Mar 2024 23:42:38 +0500 Subject: [PATCH] feat(gallery): add keyboard control support --- src/components/Gallery.astro | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/src/components/Gallery.astro b/src/components/Gallery.astro index 58060c7..21977b2 100644 --- a/src/components/Gallery.astro +++ b/src/components/Gallery.astro @@ -86,9 +86,12 @@ const rowCount = Math.ceil(images.length/3) fsContainer.style.pointerEvents = "none" }) - for (const img of Array.from(gallery.children) as HTMLImageElement[]) { + const isOpen = () => fsContainer.style.opacity !== "0" + const images = Array.from(gallery.children) as HTMLImageElement[] + + for (const img of images) { img.addEventListener("click", () => { - if (fsContainer.style.opacity === "0") { + if (!isOpen()) { fsContainer.style.opacity = "1" fsContainer.style.pointerEvents = "auto" fsImg.src = img.src @@ -99,5 +102,30 @@ const rowCount = Math.ceil(images.length/3) } }) } + + let index = 0 + + document.addEventListener("keydown", function(event) { + if (!isOpen()) return + + switch (event.key) { + case "Escape": + fsContainer.style.opacity = "0" + fsContainer.style.pointerEvents = "none" + break + case "ArrowLeft": + index = images.findIndex(el => el.src === fsImg.src) + index = index > 0 ? index - 1 : images.length - 1 + fsImg.src = images[index]?.src || "???" + fsAlt.innerHTML = images[index]?.alt || "???" + break + case "ArrowRight": + index = images.findIndex(el => el.src === fsImg.src) + index = index < images.length - 1 ? index + 1 : 0 + fsImg.src = images[index]?.src || "???" + fsAlt.innerHTML = images[index]?.alt || "???" + break + } + }) }