CI / quality (push) Canceled after 0s
Wrap the template in AnimatePresence (mode="wait") with a FrozenRouter that pins the layout-router context, so the outgoing page animates out (blur + rise) before the incoming page animates in.
49 lines
1.9 KiB
TypeScript
49 lines
1.9 KiB
TypeScript
"use client";
|
|
|
|
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
|
|
import { LayoutRouterContext } from "next/dist/shared/lib/app-router-context.shared-runtime";
|
|
import { usePathname } from "next/navigation";
|
|
import { useContext, useState, type ReactNode } from "react";
|
|
|
|
/**
|
|
* App Router swaps in the new page's content as soon as you navigate, so the
|
|
* outgoing page would normally vanish before it can animate out. `FrozenRouter`
|
|
* pins the layout-router context to the value it had when this instance
|
|
* mounted, keeping the *old* subtree rendered while its exit animation plays.
|
|
*/
|
|
function FrozenRouter({ children }: { children: ReactNode }) {
|
|
const context = useContext(LayoutRouterContext);
|
|
// Freeze the context captured at mount so the outgoing subtree keeps
|
|
// rendering (with its old route data) while its exit animation plays.
|
|
const [frozen] = useState(context);
|
|
|
|
if (!frozen) {
|
|
return <>{children}</>;
|
|
}
|
|
|
|
return <LayoutRouterContext.Provider value={frozen}>{children}</LayoutRouterContext.Provider>;
|
|
}
|
|
|
|
/**
|
|
* One unified page transition on every navigation: the old page animates out
|
|
* (blur + rise up) before the new page animates in (blur + rise from below).
|
|
*/
|
|
export default function SiteTemplate({ children }: { children: ReactNode }) {
|
|
const reducedMotion = useReducedMotion();
|
|
const pathname = usePathname();
|
|
|
|
return (
|
|
<AnimatePresence mode="wait" initial={false}>
|
|
<motion.div
|
|
key={pathname}
|
|
initial={reducedMotion ? false : { opacity: 0, y: 18, filter: "blur(10px)" }}
|
|
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
|
|
exit={reducedMotion ? { opacity: 0 } : { opacity: 0, y: -18, filter: "blur(10px)" }}
|
|
transition={reducedMotion ? { duration: 0 } : { duration: 0.4, ease: [0.22, 1, 0.36, 1] }}
|
|
>
|
|
<FrozenRouter>{children}</FrozenRouter>
|
|
</motion.div>
|
|
</AnimatePresence>
|
|
);
|
|
}
|