Communitygithub.com

ページ遷移アニメーション (Next.js App Router)

Next.js App Router と一般的なSPAルーティングにおいて、View Transitions API と Framer Motion を使用したページの入退場トランジションアニメーションを実装します。特に、Framer Motion の AnimatePresence の exit アニメーションがナビゲーション時に動作しない問題を解決します。

ページ遷移アニメーション (Next.js App Router) とは?

このスキルは、Next.js App Router を中心に、ページ遷移時のアニメーションを実装するための包括的なガイドです。特に、多くの開発者が遭遇する「Framer Motion の AnimatePresence で exit アニメーションが動作しない」という問題を、その根本原因から解説し、2つの解決策を提供します。1つ目は、`template.tsx`、パス名をキーにした `AnimatePresence`、そして `LayoutRouterContext` をフリーズする `FrozenRouter` パターンを組み合わせた方法です。2つ目は、ブラウザネイティブの View Transitions API または `next-view-transitions` ライブラリを使用する方法です。また、アニメーションの検証用スタンドアロンHTMLファイルの作成方法や、`AnimatePresence` のデバッグチェックリスト、注意点や落とし穴についても詳しく解説しており、Next.js アプリケーションにスムーズなページトランジションを導入したい開発者にとって貴重なリソースです。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/nehakanjamala/personal_website/tree/HEAD/.agents/skills/page-transition-animation

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

ページ遷移アニメーション (Next.js App Router) は何をしますか?

Next.js App Router でページの入退場トランジションを実装し、最も一般的な障害である Framer Motion の AnimatePresence による exit アニメーションがナビゲーション時に全く動作しない問題を修正します。原因は構造的なものです。App Router ではナビゲーション時に、Next.js が古いルートのコンテンツをアンマウントし、新しいルートのコンテンツをほぼ即座にマウントします。AnimatePresence が exit アニメーションを実行できるのは、終了する要素がマウントされたまま、永続的な AnimatePresence ラッパーの下でアニメーションを実行するのに十分な時間がある場合のみです。ルーターが子要素を入れ替えるため、exit はスキップされます。この問題を解決するには、FrozenRouter パターンを使用したパス名キー付きの AnimatePresence、または View Transitions API(ネイティブ / next-view-transitions)の2つのアプローチがあります。

いつ使用するか

Next.js App Router アプリにアニメーションページトランジションを追加する場合、Framer Motion の exit プロパティがルート変更時に動作しない場合、古いページがアニメーションせずに瞬時に消える場合、Next.js で Framer Motion と View Transitions API のどちらを選ぶか迷っている場合、またはルート間で AnimatePresence がアニメーションしない理由をデバッグしている場合に使用します。

exit が動作しない理由(核となる問題)

AnimatePresence は 直接のキー付き子要素 の削除を検出します。App Router のナビゲーションでは:

  1. ラッパーはナビゲーション全体を通して永続する必要があります。AnimatePresence が自身もアンマウントされるコンポーネント内にある場合、exit を実行するものが何も残りません。
  2. AnimatePresence が「古いものが削除され、新しいものが追加された」と認識するために、子要素の key はルートごとに変更される必要があります。
  3. 一時的な重複期間中、出力側のサブツリーは古いコンテンツをレンダリングし続ける必要がありますが、App Router は既にルートコンテキストを交換しているため、出力側ツリーは新しいページのデータをレンダリングしてしまいます。これを修正するのが FrozenRouter です。

解決策A: template.tsx + キー付き AnimatePresence + FrozenRouter

template.tsx は、このための App Router の目的に特化したフックです。layout.tsx(永続する)とは異なり、テンプレートはナビゲーションのたびに再マウントされ、各ルートに新しいインスタンスを提供します。ルートごとのエンターアニメーションに最適です。これをパス名キー付きの AnimatePresence と FrozenRouter を組み合わせて、クリーンな exit + enter を実現します。

// app/template.tsx
'use client';
import { AnimatePresence } from 'framer-motion';
import { usePathname } from 'next/navigation';
import { FrozenRouter } from './frozen-router';
import { PageTransition } from './page-transition';

export default function Template({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  return (
    <AnimatePresence mode="wait" initial={false}>
      {/* key on pathname so AnimatePresence sees old removed / new added */}
      <PageTransition key={pathname}>
        {/* FrozenRouter keeps the OUTGOING tree rendering its old content
            while it animates out */}
        <FrozenRouter>{children}</FrozenRouter>
      </PageTransition>
    </AnimatePresence>
  );
}
// app/page-transition.tsx
'use client';
import { motion } from 'framer-motion';

export function PageTransition({ children }: { children: React.ReactNode }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -12 }}
      transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
    >
      {children}
    </motion.div>
  );
}
// app/frozen-router.tsx
'use client';
import { useContext, useRef } from 'react';
import {
  LayoutRouterContext,
} from 'next/dist/shared/lib/app-router-context.shared-runtime';

// Freezes the router context so the exiting page keeps rendering its
// OWN content during the exit animation instead of the next route's.
export function FrozenRouter({ children }: { children: React.ReactNode }) {
  const context = useContext(LayoutRouterContext ?? {});
  const frozen = useRef(context).current;

  return (
    <LayoutRouterContext.Provider value={frozen}>
      {children}
    </LayoutRouterContext.Provider>
  );
}

仕組みの全体像:

  • mode="wait" により、AnimatePresence は exit を完全に終了してから新しいページをマウントします。(入退場を重ねたりクロスフェードさせたい場合はデフォルトモードを使用してください。)
  • initial={false} は初回ロード時のエンターアニメーションをスキップします(オプション)。
  • key={pathname} により、AnimatePresence は各ルートを個別の存在として扱います。
  • FrozenRouter は LayoutRouterContext をスナップショットするため、出力側サブツリーは exit 全体を通して前のルートのコンテンツをレンダリングし、新しいルートのコンテンツが一瞬表示されるのを防ぎます。これがないと、exit がスキップされるか、誤ったコンテンツが表示されます。

注意: LayoutRouterContext は Next.js の内部実装です。そのインポートパスは Next のバージョン間で変更される可能性があります。アップグレード後にインポートが壊れた場合は、そのパスを更新する必要があります。

解決策B: ネイティブ View Transitions API

View Transitions API は、ブラウザが前後のスナップショットをキャプチャして2つのDOM状態間をアニメーションします。要素ごとの exit コンポーネントは必要ありません。

/* globals.css */
@view-transition { navigation: auto; } /* opt MPA-style in (where supported) */

::view-transition-old(root) { animation: fade 0.25s both reverse; }
::view-transition-new(root) { animation: fade 0.25s both; }
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }

SPAスタイルの App Router ナビゲーションでは、ルーターの更新をラップします:

if (document.startViewTransition) {
  document.startViewTransition(() => router.push(href));
} else {
  router.push(href);
}

next-view-transitions ライブラリ

next-view-transitions は View Transitions API を App Router のクライアントナビゲーションと統合し、すぐに使えるようにします:

// app/layout.tsx
import { ViewTransitions } from 'next-view-transitions';
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <ViewTransitions>
      <html lang="en"><body>{children}</body></html>
    </ViewTransitions>
  );
}
// use the library's Link instead of next/link
import { Link } from 'next-view-transitions';
<Link href="/about">About</Link>;

シンプルなページ間フェード/モーフや、最小限のJavaScriptで共有要素トランジションを行う場合は View Transitions を選択してください。きめ細かく、オーケストレーションされ、中断可能な、または千鳥状の exit アニメーションが必要な場合は Framer Motion を選択してください。View Transitions API のブラウザサポートはまだ均一ではないため、適切なフォールバック(if (document.startViewTransition) ガード)を提供してください。

AnimatePresence デバッグチェックリスト

exit がまだ動作しない場合は、次の順序で確認してください:

  1. ラッパーがマウントされたままであること。 AnimatePresence は永続的なもの(理想的には template.tsx、またはレイアウトレベルのクライアントコンポーネント)に配置する必要があります。アンマウントされるページの内部ではありません。
  2. 安定した、変更されるキー。 アニメーション化する子要素には key={pathname}(または同様のもの)が必要です。これにより削除が検出されます。キーがない、または変更されないキーがあると、exit は発生しません。
  3. 直接の motion 子孫。 exit プロパティを持つ要素は motion.* コンポーネントであり、AnimatePresence の子である必要があります(間に非 motion ラッパーがあると検出をブロックする可能性があります)。
  4. mode="wait" 古いものと新しいものを重ねたくない場合に使用します。これがないと両方が同時にレンダリングされ、ジャンプする可能性があります。
  5. FrozenRouter が存在すること 出力側ページが exit 中に新しいルートのコンテンツを一瞬表示する場合。
  6. 'use client' AnimatePresence/usePathname/motion を使用するすべてのファイルに必要です。
  7. mode="wait" の下では一度に1つの子要素 AnimatePresence は1つのキー付き存在の入れ替えを想定しています。

納品と検証(スタンドアロンHTML)

パッケージ化されたヘルパー(scripts/): scripts/seek-shot.sh anim.html 0 1.5 3 は ?t=N ハーネスをフリーズし、各瞬間をスクリーンショットします。scripts/contact-sheet.sh sheet.png frame-*.png はそれらをタイル表示して一目で確認できるようにします。scripts/README.md を参照してください。

実際のターゲットは Next.js アプリですが、トランジションの形状(入退場のカーブ、方向、クロスフェード)を証明するために、ブラウザで直接開く1つのHTMLファイルを提供できます。2つのスタブ「ページ」をトグルし、CDN からの motion またはネイティブの View Transitions API を使用してアニメーション化します。1つのファイルは、ルーターを配線する前にモーションを検証するのに適したレベルです。フェードを目視確認するためだけに Next を立ち上げる必要はありません。

出力契約:

  • 1つの .html ファイル:2つのビュースタブとトグルがあり、CDN から motion/React をインポートするインライン <script type="module">、または document.startViewTransition + ::view-transition-* CSS のいずれかでアニメーション化されています。
  • 解決された最終状態をフリーズする方法。ルートトランジションは状態駆動型(どのビューか、スワップ途中か)であるため、時間ではなく状態をスクリーンショットします。

探索用ハーネス — トランジションフェーズを固定する。 ?view=b は遷移先ビューをマウントします(または ?phase=exit は出力側ツリーをアニメーション途中で保持します)。これにより、スクリーンショットは確定したフェーズに着地します:

<script>
  const p = new URLSearchParams(location.search);
  document.documentElement.dataset.view = p.get("view") || "a";   // CSS/React keys off this
  // Framer Motion: set the controlled key/route from ?view; for mode="wait" the resolved end is the new page
  // View Transitions: screenshot the END state (snapshots are transient); or pause via emulate slow animations
  window.__ready = true;
</script>

検証ループ — レンダリング → フェーズ設定 → スクリーンショット → 確認: 開始地点、中間、目的地(?view=a、?phase=exit、?view=b)を開き、それぞれをスクリーンショットし、忠実度(exit が実際に実行される、方向/クロスフェードが指示と一致する、mode="wait" による遅延がない)とアーティファクト(出力側ツリーが新しいページのコンテンツを一瞬表示する、二重マウント、FOUC、カクツキ)を確認します。任意のヘッドレスツールで動作します:

npx playwright screenshot --wait-for-timeout=500 "file://$PWD/transition.html?view=b" dest.png

終了前の確認事項:

  1. スタンドアロンで開くこと。コンソールエラーがなく、CDN の motion/React(使用する場合)が解決し、startViewTransition がガードされていること。
  2. ?view=/?phase= フリーズにより、決定論的なトランジションフェーズに着地すること。
  3. 開始地点 / 中間 / 目的地でスクリーンショットが撮影され、指示と一致し、コンテンツのフラッシュや exit のスキップがないこと。
  4. prefers-reduced-motion が尊重されていること — スライド/移動が短いクロスフェードに置き換えられていること。
  5. イージングが意図的であること — 入場はイーズアウト、退場はイーズイン、継続時間は約0.2〜0.4秒(mode="wait" で遅く感じない程度)。

クイックリファレンス

ニーズアプローチ
ルートごとのエンターアニメーションapp/template.tsx(ナビゲーションごとに再マウント)
ナビゲーション時の exit アニメーションキー付き AnimatePresence mode="wait" + FrozenRouter
出力側ページに古いコンテンツを表示FrozenRouter(LayoutRouterContext をスナップショット)
ルート変更の検出usePathname() を key として使用
シンプルなページ間フェード/モーフView Transitions API / next-view-transitions
共有要素トランジションview-transition-name CSS
初回ロードアニメーションをスキップinitial={false}

落とし穴

  • layout.tsx は永続化され、ルートごとに再マウントされません。ルートごとのエンターアニメーションには template.tsx を使用してください。
  • FrozenRouter を省略すると、exit 中のページが新しいルートのコンテンツをレンダリングする(目に見えるフラッシュ)か、exit が完全にスキップされます。
  • LayoutRouterContext のインポートパスは Next の内部実装です。バージョン間で変更される可能性があります。アップグレード後に最初に修正すべき点です。
  • key={pathname} がないと、AnimatePresence は同じ子要素と見なし、exit をトリガーしません。
  • mode="wait" は enter の前に exit を待機します。低速な exit で使いすぎるとナビゲーションが遅く感じられます。継続時間は約0.2〜0.4秒に調整してください。
  • View Transitions API はブラウザの完全なサポートがありません。常に document.startViewTransition をガードしてください。
  • すべてのトランジションファイルに 'use client' が必要です。サーバーコンポーネントは AnimatePresence/usePathname を使用できません。

参考ファイル

  • references/full-examples.md — 方向性/スライドトランジション、view-transition-name を使用した共有要素 View Transitions、mode="wait" を使用しないクロスフェードバリアント、loading.tsx を使用したローディング状態トランジション、および完全に動作する App Router フォルダレイアウト。

Individual skills in this repo

This repo contains 13 individual skills — each has its own dedicated page.

nehakanjamala/personal_website

This skill should be used when the user asks to "fix janky CSS animation", "make animation 60fps", "stop layout thrashing", "animate width/height/top/left smoothly", "convert animation to transform", "animate box-shadow performantly", "animate height auto", "FLIP animation", or "why is my scroll/hover animation choppy".

nehakanjamala/personal_website

This skill should be used when the user asks to "respect prefers-reduced-motion", "honor reduced motion", "make my animations accessible", "fix vestibular / motion-sickness issues", "add a useReducedMotion hook", "gate GSAP / Framer Motion / Lenis for reduced motion", or "meet WCAG 2.3.3 / C39". Provides tiered (not all-or-nothing) reduced-motion patterns in CSS and JS.

nehakanjamala/personal_website

Create, modify, debug, and deploy Apify Actors, and write their input and output schemas. Use when building an Actor from scratch, changing or troubleshooting Actor code, generating or updating .actor schema files, or pushing an Actor to the Apify platform. To wrap an existing non-Actor project, use apify-actorization instead.

nehakanjamala/personal_website

Convert existing projects into Apify Actors - serverless cloud programs. Actorize JavaScript/TypeScript (SDK with Actor.init/exit), Python (async context manager), or any language (CLI wrapper). Use when migrating code to Apify, wrapping CLI tools as Actors, or adding Actor SDK to existing projects.

nehakanjamala/personal_website

Deprecated. Output schema generation moved to the apify-actor-development skill; prefer that skill whenever it is available.

nehakanjamala/personal_website

Design and build an official Apify integration for a company's product - workflow-automation apps (Zapier/n8n-style), AI agent plugins (coding-agent skills+MCP bundles or OpenClaw/Hermes-style harnesses), AI framework packages (LangChain/LlamaIndex-style), or direct application clients via apify-client. Use when planning, creating, or reviewing an integration that exposes Apify Actors, runs, datasets, or key-value stores inside another product.

nehakanjamala/personal_website

Universal AI-powered web scraper for any platform. Scrape data from Instagram, Facebook, TikTok, YouTube, LinkedIn, X/Twitter, Google Maps, Google Search, Google Trends, Reddit, Airbnb, Yelp, and 15+ more platforms. Use for lead generation, brand monitoring, competitor analysis, influencer discovery, trend research, content analytics, audience analysis, review analysis, SEO intelligence, recruitment, or any data extraction task.

nehakanjamala/personal_website

This skill should be used when the user asks to "add a glassmorphism effect", "frosted glass UI", "Apple liquid glass style", "frosted blur card", "translucent glass panel animation", "make a frosted nav bar", "build a glass modal/dialog", "animate a glass card on hover", or "add a refracting liquid-glass hero". Covers frosted translucent panels with backdrop-filter blur, edge/specular highlights, SVG liquid-glass refraction, motion on hover/scroll/enter, and accessible reduced-transparency fallbacks.

nehakanjamala/personal_website

This skill should be used when the user asks to "build a scroll animation", "add ScrollTrigger", "pin a section while scrolling", "scrub an animation to scroll", "create a hero timeline", "do a horizontal scroll section", "split text and animate words", "animate a layout change with GSAP Flip", "sync ScrollTrigger with Lenis", "Lenis smooth scroll jittery", "ScrollTrigger markers drift", "ScrollTrigger pins break with Lenis/Locomotive", or "set up smooth scroll with GSAP pinning". Covers GSAP timelines, ScrollTrigger, SplitText, Flip, and Lenis/Locomotive smooth-scroll sync for code-driven web motion.

nehakanjamala/personal_website

This skill should be used when the user asks to "add a Lottie animation", "play a .lottie or .json animation", "integrate a Bodymovin/After Effects animation on web or mobile", "control Lottie playback / segments", "make a scroll-driven Lottie", "recolor a Lottie at runtime", or "export an AE animation to Lottie". Covers dotLottie/lottie-web integration, playback control, interactivity, theming, and the AE export checklist.

nehakanjamala/personal_website

This skill should be used when the user asks to "add a hover/press effect", "animate a toggle or switch", "build an animated like button", "make a toast/snackbar slide in", "animate a drawer or modal", "animate list reordering or add/remove", "do a shared-element layout transition", or "polish UI feedback". Covers UI motion with Framer Motion (motion/react) and modern CSS.

nehakanjamala/personal_website

Scrape web pages using Scrapling with anti-bot bypass (like Cloudflare Turnstile), stealth headless browsing, spiders framework, adaptive scraping, and JavaScript rendering. Use when asked to scrape, crawl, or extract data from websites; web_fetch fails; the site has anti-bot protections; write Python code to scrape/crawl; or write spiders.

nehakanjamala/personal_website

This skill should be used when the user asks to "animate an SVG", "make a line draw itself on", "do a stroke draw-on / signature animation", "morph one shape into another", "move an element along a path", "animate an icon/logo", or "animate an SVG gradient or filter". Covers stroke-dashoffset draw-on, path morphing, motion-along-path, and animated icons/gradients/filters via CSS, SMIL, and GSAP.

関連スキル