otterdev-io / astro-sanity-picture

Asto component for rendering Sanity images in picture element
21 stars 2 forks source link

Component not compatible with view transitions. #2

Open wrux opened 1 year ago

wrux commented 1 year ago

Problem

LQIP images are handled on initial page load. When using the view transition API, images are loaded into the DOM after page load. This resulted in images loading, but not fading in.

Solution

Astro fires an event astro:after-swap, so the on load event can be bound to new images.

Here's a temporary script I added to my app to get images working:

<script>
  document.addEventListener('astro:after-swap', () => {
    document
      .querySelectorAll<HTMLImageElement>('img[data-x-lqip="true"]')
      .forEach((img) => {
        img.addEventListener('load', () => {
          img.animate([{ opacity: 0 }, { opacity: 1 }], {
            duration: parseInt(img.dataset['xLqipTransitionDuration']!),
            fill: 'forwards',
          });
        });
        if (img.complete) {
          img.style.opacity = '1';
        }
      });
  });
</script>