comfycamp/src/components/Gallery.astro

132 lines
3.1 KiB
Plaintext
Raw Normal View History

2023-12-03 19:31:02 +05:00
---
interface Image {
src: string
alt: string
}
interface Props {
images: Image[]
}
const { images } = Astro.props
const rowCount = Math.ceil(images.length/3)
2023-12-03 19:31:02 +05:00
---
<div>
<div id="gallery" style={`grid-template-rows: repeat(${rowCount}, 263px);`}>
{images.map(img => (
<img src={img.src} alt={img.alt} loading="lazy" />
))}
</div>
<div id="fullscreenGallery" style="opacity: 0;">
<img id="fullscreenImage" />
<div id="fullscreenAlt"></div>
</div>
</div>
<style>
#gallery {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 5px;
width: 100%;
}
#gallery img {
width: 100%;
height: 100%;
object-fit: cover;
cursor: pointer;
}
#fullscreenGallery {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
display: flex;
background-color: #0008;
padding: 1em;
backdrop-filter: blur(42px);
justify-content: center;
align-items: center;
flex-direction: column;
gap: 1em;
pointer-events: none;
transition: opacity 0.1s ease-in-out;
}
#fullscreenAlt {
font-style: italic;
text-shadow: 0 0 4px rgba(0,0,0,.5);
}
#fullscreenImage {
width: 100%;
max-width: 1200px;
2023-12-03 19:31:02 +05:00
display: block;
object-fit: cover;
}
</style>
<script>
window.onload = () => {
const gallery = document.getElementById("gallery")
if (!gallery) return
const fsContainer = document.getElementById("fullscreenGallery")
if (!fsContainer) return
const fsImg = document.getElementById("fullscreenImage") as HTMLImageElement
if (!fsImg) return
const fsAlt = document.getElementById("fullscreenAlt")
if (!fsAlt) return
fsContainer.addEventListener("click", () => {
fsContainer.style.opacity = "0"
fsContainer.style.pointerEvents = "none"
})
const isOpen = () => fsContainer.style.opacity !== "0"
const images = Array.from(gallery.children) as HTMLImageElement[]
for (const img of images) {
2023-12-03 19:31:02 +05:00
img.addEventListener("click", () => {
if (!isOpen()) {
2023-12-03 19:31:02 +05:00
fsContainer.style.opacity = "1"
fsContainer.style.pointerEvents = "auto"
fsImg.src = img.src
fsAlt.innerHTML = img.alt
} else {
fsContainer.style.opacity = "0"
fsContainer.style.pointerEvents = "none"
}
})
}
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
}
})
2023-12-03 19:31:02 +05:00
}
</script>