diff --git a/.changeset/cold-maps-report.md b/.changeset/cold-maps-report.md new file mode 100644 index 000000000..081d13ad5 --- /dev/null +++ b/.changeset/cold-maps-report.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fix race condition when performing swap for fallback diff --git a/packages/astro/components/ViewTransitions.astro b/packages/astro/components/ViewTransitions.astro index 78c723efc..4f43171f9 100644 --- a/packages/astro/components/ViewTransitions.astro +++ b/packages/astro/components/ViewTransitions.astro @@ -168,13 +168,18 @@ const { fallback = 'animate' } = Astro.props as Props; // Trigger the animations document.documentElement.dataset.astroTransitionFallback = 'old'; - doc.documentElement.dataset.astroTransitionFallback = 'new'; + const fallbackSwap = () => { + removeEventListener('animationend', fallbackSwap); + clearTimeout(timeout); + swap(); + document.documentElement.dataset.astroTransitionFallback = 'new'; + }; // If there are any animations, want for the animationend event. - addEventListener('animationend', swap, { once: true }); + addEventListener('animationend', fallbackSwap, { once: true }); // If there are no animations, go ahead and swap on next tick // This is necessary because we do not know if there are animations. // The setTimeout is a fallback in case there are none. - setTimeout(() => !isAnimating && swap()); + let timeout = setTimeout(() => !isAnimating && fallbackSwap()); } else { swap(); }