| 1 | import { useCallback, useContext } from "react"; |
| 2 | import { UNSAFE_DataRouterContext, useLocation, useNavigate, type NavigateOptions, type To } from "react-router"; |
| 3 | import { pageOwnsNavigation } from "./navigation-owner"; |
| 4 | |
| 5 | /** For automatic redirects and delayed work, never for an explicit link click. */ |
| 6 | export function usePageNavigation() { |
| 7 | const context = useContext(UNSAFE_DataRouterContext); |
| 8 | const { key } = useLocation(); |
| 9 | const navigate = useNavigate(); |
| 10 | const owns = useCallback(() => context != null && pageOwnsNavigation(context.router.state, key), [context?.router, key]); |
| 11 | const automaticNavigate = useCallback((to: To, options?: NavigateOptions) => { |
| 12 | if (owns()) return navigate(to, options); |
| 13 | }, [navigate, owns]); |
| 14 | return { owns, navigate: automaticNavigate }; |
| 15 | } |