Skip to content

Commit

Permalink
feat: make client router support view transitions
Browse files Browse the repository at this point in the history
  • Loading branch information
pmelab committed Feb 3, 2025
1 parent 44b8f5f commit 8a87982
Showing 1 changed file with 46 additions and 21 deletions.
67 changes: 46 additions & 21 deletions packages/waku/src/router/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,17 +349,25 @@ const InnerRouter = ({
const changeRoute: ChangeRoute = useCallback(
(route, options) => {
const { skipRefetch } = options || {};
startTransition(() => {
if (!staticPathSet.has(route.path) && !skipRefetch) {
const rscPath = encodeRoutePath(route.path);
const rscParams = createRscParams(route.query);
refetch(rscPath, rscParams);
}
if (options.shouldScroll) {
handleScroll();
}
setRoute(route);
});
const performChange = () => {
startTransition(() => {
if (!staticPathSet.has(route.path) && !skipRefetch) {
const rscPath = encodeRoutePath(route.path);
const rscParams = createRscParams(route.query);
refetch(rscPath, rscParams);
}
if (options.shouldScroll) {
handleScroll();
}
setRoute(route);
});
};

if ('startViewTransition' in document && !skipRefetch) {
document.startViewTransition(performChange);
} else {
performChange();
}
},
[refetch, staticPathSet],
);
Expand All @@ -380,7 +388,13 @@ const InnerRouter = ({
useEffect(() => {
const callback = () => {
const route = parseRoute(new URL(window.location.href));
changeRoute(route, { shouldScroll: true });
if ('startViewTransition' in document) {
(document as any).startViewTransition(() => {
changeRoute(route, { shouldScroll: true });
});
} else {
changeRoute(route, { shouldScroll: true });
}
};
window.addEventListener('popstate', callback);
return () => {
Expand All @@ -395,16 +409,27 @@ const InnerRouter = ({
url.search = query;
url.hash = '';
if (path !== '/404') {
window.history.pushState(
{
...window.history.state,
waku_new_path: url.pathname !== window.location.pathname,
},
'',
url,
);
const performNavigation = () => {
window.history.pushState(
{
...window.history.state,
waku_new_path: url.pathname !== window.location.pathname,
},
'',
url,
);
changeRoute(parseRoute(url), {
skipRefetch: true,
shouldScroll: false,
});
};

if ('startViewTransition' in document) {
(document as any).startViewTransition(performNavigation);
} else {
performNavigation();
}
}
changeRoute(parseRoute(url), { skipRefetch: true, shouldScroll: false });
};
locationListeners.add(callback);
return () => {
Expand Down

0 comments on commit 8a87982

Please sign in to comment.