Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/app/RouteContentTransition.tsx
T

76 lines
2.9 KiB
TypeScript

import { useEffect, useLayoutEffect, useMemo, useRef, type ReactNode } from "react";
import { useLocation } from "react-router";
import { useUiPreferences } from "./UiPreferencesContext";
const ROUTE_TRANSITION_DURATION_MS = 420;
const ROUTE_TRANSITION_TARGET_SELECTOR = '[data-route-transition-content="true"]';
// Tabs and view-mode routes render a genuinely different subpage while keeping
// the same pathname. Filters/search/pagination deliberately stay out: animating
// every query refinement would make dense working screens feel unstable.
const STRUCTURAL_SEARCH_PARAMS = ["tab", "view"] as const;
/**
* Adds a restrained transition after real pathname changes. The wrapper stays
* mounted, so route state, forms and dialogs are not reset by the animation.
*
* Blur plus a pronounced fade makes the route change clearly visible without
* moving or scaling the content column. Inner sidebars stay outside the marked
* page target and therefore remain visually stable.
*/
export function RouteContentTransition({ children }: { children: ReactNode }) {
const location = useLocation();
const { preferences } = useUiPreferences();
const contentRef = useRef<HTMLDivElement>(null);
const transitionKey = useMemo(() => {
const params = new URLSearchParams(location.search);
return `${location.pathname}?${STRUCTURAL_SEARCH_PARAMS.map((key) => `${key}=${params.get(key) ?? ""}`).join("&")}`;
}, [location.pathname, location.search]);
const previousTransitionKeyRef = useRef(transitionKey);
const animationRef = useRef<Animation | null>(null);
// Start before the browser paints the new route. useEffect runs one frame
// later, which made fast subpages briefly appear complete before fading in
// and was perceived as a missing/inconsistent transition.
useLayoutEffect(() => {
if (previousTransitionKeyRef.current === transitionKey) return;
previousTransitionKeyRef.current = transitionKey;
const content = contentRef.current;
const reduceMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;
if (!content || !preferences.visualEffectsEnabled || reduceMotion || typeof content.animate !== "function") return;
const target = content.querySelector<HTMLElement>(ROUTE_TRANSITION_TARGET_SELECTOR) ?? content;
animationRef.current?.cancel();
animationRef.current = target.animate(
[
{ opacity: 0.15, filter: "blur(5px)" },
{ opacity: 1, filter: "blur(0px)" },
],
{
duration: ROUTE_TRANSITION_DURATION_MS,
easing: "cubic-bezier(0.22, 1, 0.36, 1)",
fill: "both",
}
);
return () => {
animationRef.current?.cancel();
animationRef.current = null;
};
}, [transitionKey, preferences.visualEffectsEnabled]);
useEffect(
() => () => {
animationRef.current?.cancel();
},
[]
);
return (
<div ref={contentRef} className="pb-20 sm:pb-0" data-route-content-transition="true">
{children}
</div>
);
}