56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
'use client';
|
|
|
|
import React, { createContext, useContext, useState, useCallback, ReactNode } from 'react';
|
|
import { useRouter } from 'next/navigation';
|
|
|
|
interface TransitionContextType {
|
|
isTransitioning: boolean;
|
|
startTransition: (href: string) => void;
|
|
}
|
|
|
|
const TransitionContext = createContext<TransitionContextType | undefined>(undefined);
|
|
|
|
export function TransitionProvider({ children }: { children: ReactNode }) {
|
|
const [isTransitioning, setIsTransitioning] = useState(false);
|
|
const router = useRouter();
|
|
|
|
const startTransition = useCallback((href: string) => {
|
|
// Wenn wir bereits navigieren, nichts tun
|
|
if (isTransitioning) return;
|
|
|
|
// Aktuelle URL prüfen, falls es dieselbe ist, nicht navigieren
|
|
if (typeof window !== 'undefined' && window.location.pathname === href) {
|
|
// Optional: Wir könnten weich nach oben scrollen
|
|
window.scrollTo({ top: 0, behavior: 'smooth' });
|
|
return;
|
|
}
|
|
|
|
setIsTransitioning(true);
|
|
|
|
// Die Animation des Shutters abwarten (ca. 700ms), dann pushen
|
|
setTimeout(() => {
|
|
router.push(href);
|
|
|
|
// Den Shutter wieder einfahren lassen, nachdem die Seite gewechselt hat
|
|
// Next.js Route-Changes sind fast sofort da, aber wir geben dem Cache kurz Zeit
|
|
setTimeout(() => {
|
|
setIsTransitioning(false);
|
|
}, 300);
|
|
}, 700);
|
|
}, [isTransitioning, router]);
|
|
|
|
return (
|
|
<TransitionContext.Provider value={{ isTransitioning, startTransition }}>
|
|
{children}
|
|
</TransitionContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useTransition() {
|
|
const context = useContext(TransitionContext);
|
|
if (!context) {
|
|
throw new Error('useTransition must be used within a TransitionProvider');
|
|
}
|
|
return context;
|
|
}
|