🦉

Astro の View transitions 機能使用時にローディングUIを挟む

に公開

Astro の View transitions 機能について

まずは View transitions について少し整理します。
View transitions とは、基本的に MPA でありながら、SPA のようなページ遷移を提供する機能です。

ただし、Astro は React / Next.js で実現できる SPA とかアプローチが異なり、ブラウザから提供されている View Transition API を使用・拡張する形で View transitions を実現しています。

View transitions の全体像としては、遷移準備 >> DOM スワップ >> 遷移完了という流れで構成されています。

  1. まず初回は通常のページロード(HTML を読み込み)
  2. ユーザーが <a> タグリンクをクリック(あくまで一例)
  3. 遷移準備
  4. DOM スワップ
  5. 遷移完了

初回ロード以降で、View transitions を使用できるユーザー状態・ブラウザ環境にある場合は、上記の流れで遷移が行われます。

厳密に述べると、ブラウザの API についても触れたりと割と複雑な話になりそうなので、本記事では省略させていただきます。

詳しくは、以下あたりを見ていただければイメージが着くかとおもいますので、興味がある方はぜひ。

View transitions で用意されているライフサイクルイベントについて

View Transitions 機能ですが、先に述べた通りブラウザの API を使用・拡張する実装されています。
Astro 側は View transitons 機能として、以下 5 つのライフサイクルイベントと呼ばれるポイントを用意しており、これらは様々な機能のトリガーとして使用することができます。

  1. astro:before-preparation
  2. astro:after-preparation
  3. astro:before-swap
  4. astro:after-swap
  5. astro:page-load

astro:before-preparation
ページ遷移が始まる直前、次のページの準備(データ取得や HTML 生成)に入る前に発火します。遷移の開始を検知して、UI を軽くリセットしたい時に使えます。

astro:after-preparation
次のページの準備が完了したタイミングで発火します。遷移アニメーションに入る前に、必
要な状態の反映や計測を行うのに便利です。

astro:before-swap
現在の DOM を新しい DOM に置き換える直前に発火します。置き換え前の要素に対して最後の処
理や後片付けを行えます。

astro:after-swap
DOM の置き換えが完了した直後に発火します。新しい要素へのイベント再バインドや初期化
処理をここで行えます。

astro:page-load
新しいページの読み込みとレンダリングが終わった後に発火します。ページ表示完了の合図
として、解析や UI の最終調整に使えます。

上記のイベントをフローとして整理すると以下のように整理できます。

[ユーザー操作]
↓
astro:before-preparation
↓ (HTML fetch / parse → newDocument 作成)
astro:after-preparation
↓
astro:before-swap ← ここで swap() を握れる(タイミング調整やカスタムの入口)
↓ (DOM を入れ替え)
astro:after-swap
↓
astro:page-load

また、これらのイベントは、View transitions 機能の中でいくと、以下のようなタイミングでの発火になるかと思います。

View transitions 利用時にローディング UI を挟み込む

先に示したライフサイクルイベントの内、今回はastro:before-preparation と astro:before-swap を使用しローディング UI を実装していきます。

先に完成系のものを置いておきます。ローディング UI を含んだリポジトリはこちら

zenn prefetch
ページ遷移時にアドレスバー下に一瞬表示される青いラインです。(少しみづらいかもですが...)

完成系のコード
---
export interface Props {
  color?: string;
  height?: string;
  class?: string;
  animationDuration?: number;
  threshold?: number | false;
}

const {
  color = '#0969da',
  height = '3px',
  class: className = 'astro-loading-indicator',
  animationDuration = 300,
  threshold: defaultThreshold = 200,
} = Astro.props;

const threshold = defaultThreshold;

const styles = `.${className} {
  pointer-events: none;
  background-color: ${color};
  position: fixed;
  z-index: 1031;
  top: 0;
  left: 0;
  width: 100%;
  height: ${height};
  transition: transform ${animationDuration}ms ease-out, opacity ${
    animationDuration / 2
  }ms ${animationDuration / 2}ms ease-in;
  transform: translate3d(0, 0, 0) scaleX(var(--progress, 0));
  transform-origin: 0;
}

[dir="rtl"] .${className} {
  transform-origin: 100% 0;
}
`;
---

<style set:html={styles}></style>

<script is:inline define:vars={{ className, animationDuration, threshold }}>
(() => {
  if (window.__astroLoadingIndicator) {
    return
  }
  window.__astroLoadingIndicator = true

  let progress = 0.25
  let opacity = 0
  let trickleInterval = undefined
  let thresholdTimeout = undefined
  let isActive = false

  const element = document.createElement("div")
  element.classList.add(className)
  element.setAttribute("aria-hidden", "true")

  const setProgress = (value) => {
    progress = value
    element.style.setProperty("--progress", String(progress))
  }

  const setOpacity = (value) => {
    opacity = value
    element.style.setProperty("opacity", String(opacity))
  }

  const mount = (doc) => {
    if (!doc.body) {
      return
    }
    doc.body.prepend(element)
  }

  setProgress(progress)
  setOpacity(opacity)

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", () => mount(document))
  } else {
    mount(document)
  }

  const startIndicator = () => {
    if (isActive) {
      return
    }
    isActive = true
    setOpacity(1)
    trickleInterval = window.setInterval(() => {
      setProgress(progress + Math.random() * 0.03)
    }, animationDuration)
  }

  document.addEventListener("astro:before-preparation", () => {
    if (threshold === false || threshold <= 0) {
      startIndicator()
      return
    }

    thresholdTimeout = window.setTimeout(() => {
      thresholdTimeout = undefined
      startIndicator()
    }, threshold)
  })

  document.addEventListener("astro:before-swap", (event) => {
    if (thresholdTimeout !== undefined) {
      window.clearTimeout(thresholdTimeout)
      thresholdTimeout = undefined
    }

    if (!isActive) {
      return
    }

    mount(event.newDocument)

    if (trickleInterval !== undefined) {
      window.clearInterval(trickleInterval)
      trickleInterval = undefined
    }

    setProgress(1)
    window.setTimeout(() => {
      setOpacity(0)
    }, animationDuration / 2)

    window.setTimeout(() => {
      setProgress(0.25)
      isActive = false
    }, animationDuration * 2)
  })
})()
</script>
----
// こんな感じで、Layout.astroなどで呼び出して使う。
import { ClientRouter } from 'astro:transitions';
import LoadingIndicator from '../components/LoadingIndicator.astro';
---

<!doctype html>
<html lang="ja">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width" />
		<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
		<meta name="generator" content={Astro.generator} />
		<title>Astro View Transition Loading</title>
		<ClientRouter />
	</head>
	<body>
		<slot />
		<LoadingIndicator threshold={0} />
	</body>
</html>

<style>
	html,
	body {
		margin: 0;
		width: 100%;
		height: 100%;
		padding-inline: 20px;
	}
</style>

この LoadingIndicator(以後:インジケーター)ですが、.astro ファイルで実装しています。
UI に関する 細かい内容は今回の趣旨と若干ズレるので、重要な部分だけ整理します。

今回動作フローとしては、以下のようになっています。

  1. 初期化時に div を生成して document.body の先頭に挿入。
  2. astro:before-preparation で遷移準備が始まると、しきい値用のタイマーをセット。
  3. 表示中は一定間隔で --progress を少しずつ増やし、擬似的な進捗を表現。
  4. astro:before-swap でタイマーを解除し、必要なら表示開始済みのバーを完了処理へ移行。
  5. 新しいドキュメント側にも要素を移し、progress=1 -> フェードアウト -> 初期状態へ戻す。

基本的に、しきい値(設定した時間を超えたかどうかで処理を分岐するための値)と View transitons のライフサイクルイベント 2 つを組み合わせた処理になっています。

ライフサイクルイベントと連動した動作の仕組み

インジケーターは初期化時に div 要素を生成し、document.body の先頭に挿入します。window.__astroLoadingIndicator フラグにより、複数回読み込まれても初期化は一度だけ行われます。

ページ遷移が始まると、まず astro:before-preparation イベントが発火します。このタイミングでしきい値用のタイマーをセットし、指定時間(デフォルト 200ms)が経過したらインジケーターの表示を開始します。表示中は trickleInterval を使って --progress の値を少しずつ増やし、擬似的な進捗を表現します。しきい値を設けることで、遷移が素早く完了する場合には表示をスキップし、体感速度を損なわないようにしています。

続いて、DOM の置き換え直前に astro:before-swap イベントが発火します。ここでしきい値タイマー(thresholdTimeout)をクリアし、まだ表示が始まっていなければそのまま何もしません。すでに表示中であれば、進捗を 100% にして完了処理へ移行します。新しいドキュメント側にも要素を移し替え、フェードアウト後に初期状態へ戻すことで、次回の遷移に備えます。

このように、2 つのライフサイクルイベントを組み合わせることで、実際の遷移時間に応じた適切なタイミングでローディング UI を制御しています。

また、今回はastro-loading-indicator を参考にさせていただいています。ありがとうございます 😌

まとめ

今回は、Astro の View transitions 機能アクティブ時に、どのようにローディング UI を実装するかについて整理してきました。

  • Astro の View transitions は 5 つのライフサイクルイベントを提供しており、遷移の各段階で任意の処理を挟み込める
  • ローディング UI は astro:before-preparation で表示開始、astro:before-swap で完了処理という 2 つのイベントの組み合わせで実現できる
  • しきい値を設けることで、遷移が素早い場合は表示をスキップし、ちらつきを防ぎつつ体感速度を損なわないようにできる

View transitons のライフルサイクルイベントが裏側でどのように動いていて、どのように実装されているのか。これらの View transitons がブラウザネイティブの View Transiton API と共に今後どのように変化していきそうかなど、Astro の設計哲学を軸にまだまだ深ぼっていきたい内容があるので、ぼちぼち別記事で作成していこうかと思います。

参考資料

Discussion