|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { usePathname, useSearchParams } from 'next/navigation' |
| 4 | +import { |
| 5 | + createContext, |
| 6 | + Suspense, |
| 7 | + useCallback, |
| 8 | + useContext, |
| 9 | + useEffect, |
| 10 | + useRef, |
| 11 | + useState, |
| 12 | +} from 'react' |
| 13 | + |
| 14 | +import Loading from './Loading' |
| 15 | + |
| 16 | +type NavigationProgressContextType = { |
| 17 | + start(): void |
| 18 | +} |
| 19 | + |
| 20 | +const NavigationProgressContext = |
| 21 | + createContext<NavigationProgressContextType | null>(null) |
| 22 | + |
| 23 | +export function useNavigationProgress() { |
| 24 | + const context = useContext(NavigationProgressContext) |
| 25 | + if (!context) { |
| 26 | + throw new Error( |
| 27 | + 'useNavigationProgress must be used within <NavigationProgress>', |
| 28 | + ) |
| 29 | + } |
| 30 | + return context |
| 31 | +} |
| 32 | + |
| 33 | +// Watches pathname/searchParams changes to detect when |
| 34 | +// navigation has completed. Wrapped in Suspense because |
| 35 | +// useSearchParams() requires a Suspense boundary. |
| 36 | +function NavigationComplete({ onComplete }: { onComplete: () => void }) { |
| 37 | + const pathname = usePathname() |
| 38 | + const searchParams = useSearchParams() |
| 39 | + const currentUrl = useRef(pathname + searchParams.toString()) |
| 40 | + |
| 41 | + useEffect(() => { |
| 42 | + const newUrl = pathname + searchParams.toString() |
| 43 | + if (newUrl !== currentUrl.current) { |
| 44 | + currentUrl.current = newUrl |
| 45 | + onComplete() |
| 46 | + } |
| 47 | + }, [pathname, searchParams, onComplete]) |
| 48 | + |
| 49 | + return null |
| 50 | +} |
| 51 | + |
| 52 | +// Provides navigation progress state to the component |
| 53 | +// tree. Navigation start is signalled via the onNavigate |
| 54 | +// prop on a <ProgressLink>, and completion is detected by |
| 55 | +// watching usePathname()/useSearchParams(). |
| 56 | +export default function NavigationProgress({ |
| 57 | + children, |
| 58 | +}: { |
| 59 | + children: React.ReactNode |
| 60 | +}) { |
| 61 | + const [isRouteChanging, setIsRouteChanging] = useState(false) |
| 62 | + const [loadingKey, setLoadingKey] = useState(0) |
| 63 | + |
| 64 | + const contextValue = useRef<NavigationProgressContextType>({ |
| 65 | + start: () => { |
| 66 | + setIsRouteChanging(true) |
| 67 | + setLoadingKey((prev) => prev ^ 1) |
| 68 | + }, |
| 69 | + }).current |
| 70 | + |
| 71 | + const handleComplete = useCallback(() => setIsRouteChanging(false), []) |
| 72 | + |
| 73 | + return ( |
| 74 | + <NavigationProgressContext.Provider value={contextValue}> |
| 75 | + <Loading isRouteChanging={isRouteChanging} key={loadingKey} /> |
| 76 | + <Suspense> |
| 77 | + <NavigationComplete onComplete={handleComplete} /> |
| 78 | + </Suspense> |
| 79 | + {children} |
| 80 | + </NavigationProgressContext.Provider> |
| 81 | + ) |
| 82 | +} |
0 commit comments