2022-02-01 09:58:06 +00:00
|
|
|
import { ExitFormDialogContext } from "@saleor/components/Form/ExitFormDialogProvider";
|
|
|
|
import { useContext } from "react";
|
2019-06-19 14:40:52 +00:00
|
|
|
import useRouter from "use-react-router";
|
|
|
|
|
|
|
|
export type UseNavigatorResult = (
|
|
|
|
url: string,
|
2021-10-21 08:34:56 +00:00
|
|
|
opts?: {
|
|
|
|
replace?: boolean;
|
|
|
|
preserveQs?: boolean;
|
|
|
|
resetScroll?: boolean;
|
2022-06-21 09:36:55 +00:00
|
|
|
},
|
2019-06-19 14:40:52 +00:00
|
|
|
) => void;
|
|
|
|
function useNavigator(): UseNavigatorResult {
|
|
|
|
const {
|
|
|
|
location: { search },
|
2022-06-21 09:36:55 +00:00
|
|
|
history,
|
2019-06-19 14:40:52 +00:00
|
|
|
} = useRouter();
|
|
|
|
|
2022-02-01 09:58:06 +00:00
|
|
|
const { shouldBlockNavigation } = useContext(ExitFormDialogContext);
|
|
|
|
|
2021-10-21 08:34:56 +00:00
|
|
|
return (
|
|
|
|
url: string,
|
2022-06-21 09:36:55 +00:00
|
|
|
{ replace = false, preserveQs = false, resetScroll = false } = {},
|
2021-10-21 08:34:56 +00:00
|
|
|
) => {
|
2022-02-01 09:58:06 +00:00
|
|
|
if (shouldBlockNavigation()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-06-19 14:40:52 +00:00
|
|
|
const targetUrl = preserveQs ? url + search : url;
|
2022-02-01 09:58:06 +00:00
|
|
|
|
2019-12-02 10:49:14 +00:00
|
|
|
if (replace) {
|
|
|
|
history.replace(targetUrl);
|
|
|
|
} else {
|
|
|
|
history.push(targetUrl);
|
|
|
|
}
|
2021-10-21 08:34:56 +00:00
|
|
|
if (resetScroll) {
|
|
|
|
window.scrollTo({ behavior: "smooth", top: 0 });
|
|
|
|
}
|
2019-06-19 14:40:52 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export default useNavigator;
|