| 1 | import { useContext, useEffect, useState } from "react"; |
| 2 | import { UNSAFE_DataRouterContext, useNavigation } from "react-router"; |
| 3 | |
| 4 | import { stuckTarget } from "../lib/stuck"; |
| 5 | import { watchBuildNavigation } from "../lib/resilient-fetch"; |
| 6 | import { Button } from "./ui/button"; |
| 7 | |
| 8 | /** A document load of the destination, while the router still shows the old page. */ |
| 9 | export function NavigationRecovery() { |
| 10 | const context = useContext(UNSAFE_DataRouterContext); |
| 11 | useEffect(() => watchBuildNavigation(() => context?.router.state.navigation.location), [context?.router]); |
| 12 | const navigation = useNavigation(); |
| 13 | const target = stuckTarget(navigation); |
| 14 | const key = navigation.location?.key; |
| 15 | const [slow, setSlow] = useState<string | null>(null); |
| 16 | useEffect(() => { |
| 17 | setSlow(null); |
| 18 | if (!target || !key) return; |
| 19 | const timer = window.setTimeout(() => setSlow(key), 5_000); |
| 20 | return () => window.clearTimeout(timer); |
| 21 | }, [target, key]); |
| 22 | if (!target || !key || slow !== key) return null; |
| 23 | return ( |
| 24 | <div className="fixed inset-x-0 bottom-20 z-65 flex justify-center px-4"> |
| 25 | <div className="flex max-w-full flex-wrap items-center justify-center gap-3 rounded-xl bg-surface px-4 py-3 text-sm shadow-xl ring-1 ring-line-strong"> |
| 26 | <span role="status">This page is taking a while.</span> |
| 27 | <Button asChild variant="outline" size="sm"> |
| 28 | <a href={target}>Reload destination</a> |
| 29 | </Button> |
| 30 | </div> |
| 31 | </div> |
| 32 | ); |
| 33 | } |