Open davelsan opened 1 month ago
The latest updates on your projects. Learn more about Vercel for Git ↗︎
Name | Status | Preview | Comments | Updated (UTC) |
---|---|---|---|---|
next-view-transitions-example | ✅ Ready (Inspect) | Visit Preview | 💬 Add feedback | Jun 4, 2024 10:29pm |
Some additional thoughts after tinkering further with this.
router
object is probably the way to go.onReady
callback on both the push
and replace
methods would be an easy way to support controlling the animations with JS.useTransitionsRouter
.I thought I'd give more context on what this PR does by adding a clear example. Sometimes it's hard to see it in the code.
The changes so far are two:
router
object, instead of using the <Link />
component.The follow snippet provides a simple example of using programatic navigation.
import { useTransitionRouter } from 'next-view-transitions'
import { useState } from "react";
export default function Page() {
const [withCustomTransition, setWithCustomTransition] = useState(true)
const router = useTransitionRouter();
const routerNavigate = () => {
router.push('/path/to/page', {
onTransitionReady: withCustomTransition ? slideInOut: undefined,
});
}
return (
// Markup with an onWhatever event that calls `routerNavigate`
)
}
In the example, regular useState
sets the flag to either use a custom slide animation (slideInOut
), or use the default defined in CSS (undefined
). The slideInOut
function follows the MDN documentation for the View Transitions API and Web Animations API. It can be defined outside of the React component tree.
function slideInOut() {
// Outgoing page slides out towards the left while fading out.
document.documentElement.animate(
[
{
opacity: 1,
transform: 'translate(0, 0)',
},
{
opacity: 0,
transform: 'translate(-100%, 0)',
},
],
{
duration: 500,
easing: 'ease-in-out',
fill: 'forwards',
pseudoElement: '::view-transition-old(root)',
}
);
// Incoming page slides from the right while fading in.
document.documentElement.animate(
[
{
opacity: 0,
transform: 'translate(100%, 0)',
},
{
opacity: 1,
transform: 'translate(0, 0)',
},
],
{
duration: 500,
easing: 'ease-in-out',
fill: 'forwards',
pseudoElement: '::view-transition-new(root)',
}
);
}
That's pretty much it. This code is already in the repo example
of this branch. Feedback very welcome.
Related to #17
This PR is a quick POC to check whether extending the Next.js
useRouter
hook to enable transitions would work.So far I've tried it only on the example demo and a very quick project I'm developing where I want to use programmatic transitions.
Would it be interesting to develop this further?
Some things I'm thinking:
useRouter
, just likeLink
. Acceptable or confusing naming?~push
andreplace
only. Anything else would make sense?push
andreplace
stable withuseCallback
, assuming the original Next.js methods are also stable, but maybe it's preferrable to memoize the returned "router" object.~Link
supports custom key modifiers, which I assume are Next-specific.