ConceptPortal-public/rsconcept/frontend/src/app/Navigation/NavigationContext.tsx

96 lines
2.3 KiB
TypeScript
Raw Normal View History

'use client';
2023-09-05 00:23:53 +03:00
import { createContext, useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
2023-12-28 14:04:44 +03:00
interface INavigationContext {
push: (path: string, newTab?: boolean) => void;
2023-12-28 14:04:44 +03:00
replace: (path: string) => void;
back: () => void;
forward: () => void;
canBack: () => boolean;
isBlocked: boolean;
setIsBlocked: (value: boolean) => void;
2023-09-05 00:23:53 +03:00
}
2023-12-26 14:23:51 +03:00
const NavigationContext = createContext<INavigationContext | null>(null);
2023-09-05 00:23:53 +03:00
export const useConceptNavigation = () => {
2023-12-26 14:23:51 +03:00
const context = useContext(NavigationContext);
2023-09-05 00:23:53 +03:00
if (!context) {
throw new Error('useConceptNavigation has to be used within <NavigationState>');
2023-09-05 00:23:53 +03:00
}
return context;
2023-12-28 14:04:44 +03:00
};
2023-09-05 00:23:53 +03:00
2024-09-19 17:49:25 +03:00
export const NavigationState = ({ children }: React.PropsWithChildren) => {
const router = useNavigate();
2023-12-28 14:04:44 +03:00
const [isBlocked, setIsBlocked] = useState(false);
function validate() {
2023-12-28 14:04:44 +03:00
return !isBlocked || confirm('Изменения не сохранены. Вы уверены что хотите совершить переход?');
}
2023-12-13 15:03:58 +03:00
function canBack() {
return !!window.history && window.history?.length !== 0;
}
function push(path: string, newTab?: boolean) {
if (newTab) {
window.open(`${path}`, '_blank');
return;
2023-09-05 00:23:53 +03:00
}
if (validate()) {
Promise.resolve(router(path, { viewTransition: true })).catch(console.error);
setIsBlocked(false);
}
}
2023-12-28 14:04:44 +03:00
function replace(path: string) {
2023-12-13 15:03:58 +03:00
if (validate()) {
Promise.resolve(router(path, { replace: true, viewTransition: true })).catch(console.error);
2023-12-13 15:03:58 +03:00
setIsBlocked(false);
}
}
function back() {
2023-12-13 15:03:58 +03:00
if (validate()) {
Promise.resolve(router(-1)).catch(console.error);
2023-12-13 15:03:58 +03:00
setIsBlocked(false);
}
}
2023-09-05 00:23:53 +03:00
function forward() {
if (validate()) {
Promise.resolve(router(1)).catch(console.error);
setIsBlocked(false);
}
}
2023-09-05 00:23:53 +03:00
return (
2024-12-12 21:58:19 +03:00
<NavigationContext
2023-12-28 14:04:44 +03:00
value={{
push,
replace,
back,
forward,
canBack,
isBlocked,
setIsBlocked
}}
>
{children}
2024-12-12 21:58:19 +03:00
</NavigationContext>
2023-12-28 14:04:44 +03:00
);
};
2023-12-13 15:03:58 +03:00
export function useBlockNavigation(isBlocked: boolean) {
const router = useConceptNavigation();
2023-12-28 14:04:44 +03:00
useEffect(() => {
2023-12-13 15:03:58 +03:00
router.setIsBlocked(isBlocked);
return () => router.setIsBlocked(false);
}, [router, isBlocked]);
2023-12-28 14:04:44 +03:00
}