Communitygithub.com

nehakanjamala/personal_website

此技能用于在Next.js App Router中实现页面进入/退出过渡动画,并修复Framer Motion AnimatePresence退出动画在导航时不触发的常见问题。

personal_website 是什么?

此技能主要解决Next.js App Router中页面过渡动画的一个核心痛点:当使用Framer Motion的`AnimatePresence`组件时,退出动画(exit animation)在路由导航时不会触发。原因是App Router在导航时会立即卸载旧路由内容并挂载新路由内容,导致`AnimatePresence`无法捕获退出动画。技能提供了两种解决方案:方案A使用`template.tsx`、基于路径名的`AnimatePresence`和`FrozenRouter`组件来正确实现进入/退出动画;方案B则利用原生的View Transitions API或`next-view-transitions`库来实现简单的页面间淡入淡出和元素过渡。技能还包含了详细的调试清单、独立的HTML验证方法和一个完整的参考文件列表,帮助开发者快速定位并解决问题。该技能适用于Next.js App Router项目,支持Framer Motion和View Transitions API两种技术路线。

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

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

页面过渡动画(Next.js App Router)

在 Next.js App Router 中实现页面进入/退出过渡,并解决最常遇到的故障:Framer Motion AnimatePresence 退出动画在导航时不触发。其根本原因在于结构——在 App Router 中,导航时 Next.js 会立即卸载旧路由的内容并几乎同时挂载新路由的内容。AnimatePresence 只有在退出元素保持挂载在持久化的 AnimatePresence 包装器内足够长的时间来运行动画时,才能对退出进行动画。由于路由器在其下直接交换子组件,退出动画被跳过。两种方法可以解决:使用 FrozenRouter 模式的基于路径名的 AnimatePresence,或者使用 View Transitions API(原生 / next-view-transitions)。

何时使用

在 Next.js App Router 应用中添加动画页面过渡时使用;当 Framer Motion 的 exit 属性在路由变化时不起作用时;当旧页面瞬间消失而不是以动画形式退出时;当需要在 Next.js 中选择 Framer Motion 还是 View Transitions API 时;或者调试为什么 AnimatePresence 无法在路由之间运行动画时。

退出动画不触发的原因(核心问题)

AnimatePresence 检测到直接带 key 的子组件被移除。在 App Router 导航中:

  1. 包装器必须在导航过程中保持挂载。如果 AnimatePresence 位于一个自身也会卸载的组件中,那么就没有任何东西来运行退出动画。
  2. 子组件的 key 必须随每个路由变化,以便 AnimatePresence 识别出“旧组件被移除,新组件被添加”。
  3. 在短暂的叠加期间,正在退出的子树必须仍然渲染其旧内容——但 App Router 已经交换了路由上下文,因此退出的树将渲染新页面的数据。这就是 FrozenRouter 要解决的问题。

解决方案 A:template.tsx + 带 key 的 AnimatePresence + FrozenRouter

template.tsx 是 App Router 为这个目的而设计的钩子:与 layout.tsx(持久化)不同,模板在每次导航时都会重新挂载,为每个路由提供一个新的实例——非常适合每个路由的进入动画。将其与基于路径名的 AnimatePresence 和 FrozenRouter 结合使用,以实现清晰的退出和进入动画。

// 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,以便 AnimatePresence 识别出旧组件被移除/新组件被添加 */}
      <PageTransition key={pathname}>
        {/* FrozenRouter 使正在退出的树在退出动画期间渲染其旧内容 */}
        <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';

// 冻结路由器上下文,使退出页面在退出动画期间保持渲染其
// 自身的内容,而不是下一个路由的内容。
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 在挂载新页面之前完全完成退出动画。(如果需要进入/退出叠加/交叉淡入淡出,请使用默认模式。)
  • initial={false} 可选地跳过首次加载时的进入动画。
  • key={pathname} 是使 AnimatePresence 将每个路由视为不同存在体的关键。
  • FrozenRouter 快照 LayoutRouterContext,使退出的子树在整个退出期间渲染前一个路由的内容,而不是闪烁新路由的内容。没有它,退出要么被跳过,要么显示错误的内容。

注意:LayoutRouterContext 是 Next.js 内部 API;其导入路径可能在不同 Next 版本之间发生变化。如果在升级后导入中断,需要更新该路径。

解决方案 B:原生 View Transitions API

View Transitions API 通过浏览器捕获前后快照,在两个 DOM 状态之间进行动画——无需按元素设置退出组件。

/* globals.css */
@view-transition { navigation: auto; } /* 在支持的地方选择 MPA 风格 */

::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>
  );
}
// 使用该库的 Link 替代 next/link
import { Link } from 'next-view-transitions';
<Link href="/about">About</Link>;

对于简单的跨页面淡入淡出/变形和共享元素过渡,且 JavaScript 代码量最小,请选择 View Transitions;当需要细粒度、协调、可中断或交错退出动画时,请选择 Framer Motion。View Transitions API 的浏览器支持仍不均匀,因此请提供一个优雅的回退方案(if (document.startViewTransition) 守卫)。

AnimatePresence 调试清单

当退出动画仍不触发时,按顺序检查:

  1. 包装器保持挂载。 AnimatePresence 必须位于持久化的组件中——理想情况下是 template.tsx,或布局级别的客户端组件——而不是位于正在卸载的页面内部。
  2. 稳定且变化的 key。 动画子组件需要 key={pathname}(或类似),以便检测到移除。没有 key,或 key 不变化 → 无退出动画。
  3. 直接的 motion 后代。 带有 exit 属性的元素必须是 motion.* 组件,并且是 AnimatePresence 的子组件(中间的非 motion 包装器可能会阻止检测)。
  4. mode="wait" 如果新旧组件不应重叠;没有它,两者会同时渲染,可能导致跳跃。
  5. 存在 FrozenRouter 如果退出页面在退出期间闪烁新路由的内容。
  6. 每个使用 AnimatePresence/usePathname/motion 的文件都需要 'use client'。
  7. mode="wait" 下每次只有一个子组件——AnimatePresence 期望一次交换一个带 key 的存在体。

交付与验证(独立 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 应用,但为了证明过渡的形状(进入/退出曲线、方向、交叉淡入淡出),你可以提供一个可直接在浏览器中打开的 HTML 文件——两个可以切换的虚拟“页面”,使用来自 CDN 的 motion 或原生 View Transitions API 进行动画。一个文件足以在连接路由器之前验证运动效果;不要仅仅为了目测一个淡入淡出效果而启动 Next。

输出约定:

  • 一个 .html 文件:两个视图存根和一个切换开关,使用内联 <script type="module"> 从 CDN 导入 motion/React,或使用 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 依赖于此
  // Framer Motion: 从 ?view 设置受控的 key/route;对于 mode="wait",解析后的结束状态是新页面
  // View Transitions: 截图 END 状态(快照是瞬态的);或通过模拟慢速动画暂停
  window.__ready = true;
</script>

验证循环——渲染 → 设置阶段 → 截图 → 检查: 打开源、中间和目标状态(?view=a、?phase=exit、?view=b),截图每个状态,并检查保真度(退出动画实际运行,方向/交叉淡入淡出是否符合要求,无 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. 在源 / 中间 / 目标状态截图——符合预期,无内容闪烁或跳过退出。
  4. 尊重 prefers-reduced-motion——滑动/平移降级为短暂的交叉淡入淡出。
  5. 缓动函数是有意为之的——进入时缓出,退出时缓入,持续时间为 ~0.2–0.4s(在 mode="wait" 下不会感觉延迟)。

快速参考

需求方法
按路由进入动画app/template.tsx(每次导航重新挂载)
导航时退出动画带 key 的 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 会使退出页面在动画中间渲染新路由的内容(可见闪烁)或完全跳过退出。
  • LayoutRouterContext 的导入路径是 Next 内部 API;可能在不同版本之间变化——升级后首先要检查的就是这个。
  • 没有 key={pathname},AnimatePresence 会将子组件视为相同,永远不会触发退出。
  • mode="wait" 会等待退出完成后再进入;在缓慢的退出上过度使用它会让人感觉导航有延迟——调整持续时间(~0.2-0.4s)。
  • 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.

相关技能