| 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( |
| 12 | (to: To, options?: NavigateOptions) => { |
| 13 | if (owns()) return navigate(to, options); |
| 14 | }, |
| 15 | [navigate, owns], |
| 16 | ); |
| 17 | return { owns, navigate: automaticNavigate }; |
| 18 | } |