blog/src/components/Widgets/PhotoSwipe.astro
radishzz 47e1df9b3d
feat: performance optimizations and ui improvements (#26)
* test: remove astro-compress

* test: remove astro-compress

* perf: add astro-compress, optimize resource preloading

* perf: moving photoswipe styles to head with non-blocking preload strategy

* test: disable astro-compress

* test: enable astro-compress

* fix: typescript hints

* chore: adjust toc style and gsap animation

* style: optimize gsap animation logic, adjust toc style

* chore: adjust toc style

* fix: photoswipe transition position offset caused by scrollbar-gutter
2025-05-26 20:21:38 +01:00

73 lines
1.8 KiB
Text

<script>
import PhotoSwipeLightbox from 'photoswipe/lightbox'
let lightbox: PhotoSwipeLightbox
const pswp = import('photoswipe')
function setupPhotoSwipe() {
const bodyElement = document.body
if (bodyElement.hasAttribute('data-photoswipe-initialized'))
return
const article = document.querySelector('article.heti')
const images = article ? article.getElementsByTagName('img') : []
if (images.length === 0)
return
lightbox = new PhotoSwipeLightbox({
gallery: 'article.heti img',
pswpModule: () => pswp,
bgOpacity: 0.9,
padding: {
top: window.innerHeight * 0.1,
bottom: window.innerHeight * 0.1,
left: window.innerWidth * 0.073,
right: window.innerWidth * 0.073,
},
zoom: false,
close: false,
wheelToZoom: true,
imageClickAction: 'close',
tapAction: 'close',
})
// Set image dimensions
lightbox.addFilter('domItemData', (itemData, element) => {
if (element instanceof HTMLImageElement) {
// Set image source
itemData.src = element.src
// Set dimensions with fallback to window size
itemData.w = Number(element.naturalWidth || window.innerWidth)
itemData.h = Number(element.naturalHeight || window.innerHeight)
// Set thumbnail source
itemData.msrc = element.src
}
return itemData
})
lightbox.init()
bodyElement.setAttribute('data-photoswipe-initialized', 'true')
}
function lazySetupPhotoSwipe() {
if (typeof window.requestIdleCallback === 'function') {
window.requestIdleCallback(() => setupPhotoSwipe(), { timeout: 1000 })
}
else {
requestAnimationFrame(() => {
setupPhotoSwipe()
})
}
}
lazySetupPhotoSwipe()
document.addEventListener('astro:page-load', lazySetupPhotoSwipe)
</script>
<style is:global>
.pswp .pswp__bg {
--at-apply: 'bg-background!'
}
</style>