|
| 1 | +import { useEffect } from 'react'; |
| 2 | +import { useBlocker } from 'react-router-dom'; |
| 3 | + |
| 4 | +interface UsePreventNavigationOptions { |
| 5 | + /** Block app-internal navigation (sidebar links, back button). Default: true */ |
| 6 | + blockInternalNavigation?: boolean; |
| 7 | + /** Block browser operations (reload, close tab). Default: true */ |
| 8 | + blockBrowserNavigation?: boolean; |
| 9 | +} |
| 10 | + |
| 11 | +/** |
| 12 | + * Prevents page navigation when there are unsaved changes |
| 13 | + * @param hasUnsavedChanges - Boolean indicating if there are unsaved changes |
| 14 | + * @param options - Customization options for blocking behavior |
| 15 | + * @returns Blocker object from useBlocker |
| 16 | + */ |
| 17 | +const usePreventNavigation = ( |
| 18 | + hasUnsavedChanges: boolean, |
| 19 | + options: UsePreventNavigationOptions = {} |
| 20 | +) => { |
| 21 | + const { blockInternalNavigation = true, blockBrowserNavigation = true } = |
| 22 | + options; |
| 23 | + |
| 24 | + // Block app-internal navigation (sidebar links, back button) |
| 25 | + const blocker = useBlocker( |
| 26 | + ({ currentLocation, nextLocation }) => |
| 27 | + blockInternalNavigation && |
| 28 | + hasUnsavedChanges && |
| 29 | + currentLocation.pathname !== nextLocation.pathname |
| 30 | + ); |
| 31 | + |
| 32 | + // Block browser operations (reload, close tab, navigate to external URL) |
| 33 | + useEffect(() => { |
| 34 | + if (!blockBrowserNavigation || !hasUnsavedChanges) return; |
| 35 | + |
| 36 | + const handleBeforeUnload = (e: BeforeUnloadEvent) => { |
| 37 | + e.preventDefault(); |
| 38 | + e.returnValue = ''; |
| 39 | + }; |
| 40 | + |
| 41 | + window.addEventListener('beforeunload', handleBeforeUnload); |
| 42 | + |
| 43 | + return () => { |
| 44 | + window.removeEventListener('beforeunload', handleBeforeUnload); |
| 45 | + }; |
| 46 | + }, [hasUnsavedChanges, blockBrowserNavigation]); |
| 47 | + |
| 48 | + return blocker; |
| 49 | +}; |
| 50 | + |
| 51 | +export default usePreventNavigation; |
0 commit comments