- Added BackButton component to standardize back navigation across pages. - Integrated BackButton into various pages, replacing custom back buttons for consistency. - Updated PageHeader to accept backTo prop for displaying BackButton when navigating from subpages. - Created useGoBack hook to handle navigation logic, determining whether to go back in history or redirect to a fallback page. - Added tests for BackButton and its integration with PageHeader to ensure expected behavior.
25 lines
1.2 KiB
TypeScript
25 lines
1.2 KiB
TypeScript
import { useCallback } from 'react';
|
|
import { useLocation, useNavigate } from 'react-router-dom';
|
|
|
|
/**
|
|
* رفتار یکسانِ «بازگشت» در کل پنل: اگر کاربر از صفحهٔ دیگری داخل خود پنل آمده باشد،
|
|
* یک قدم در تاریخچه برمیگردد؛ اگر صفحه مستقیم باز شده باشد (لینک مستقیم، رفرش،
|
|
* بوکمارک) تاریخچهای برای برگشتن نیست و به صفحهٔ والدِ همان بخش میرود.
|
|
*
|
|
* تشخیص «ورود مستقیم» با `location.key === 'default'` انجام میشود — همان چیزی که
|
|
* React Router برای اولین ورودیِ تاریخچه میگذارد؛ `history.length` قابل اتکا نیست
|
|
* چون تبهای قبلی مرورگر هم در آن شمرده میشوند.
|
|
*/
|
|
export function useGoBack(fallback: string): () => void {
|
|
const navigate = useNavigate();
|
|
const location = useLocation();
|
|
|
|
return useCallback(() => {
|
|
if (location.key !== 'default') {
|
|
navigate(-1);
|
|
return;
|
|
}
|
|
navigate(fallback, { replace: true });
|
|
}, [navigate, location.key, fallback]);
|
|
}
|