-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Migrate Query Source page to React: unsaved changes alert (#4505)
- Loading branch information
1 parent
3d5f5b9
commit 2a06152
Showing
2 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import { useRef, useEffect } from "react"; | ||
import { $rootScope } from "@/services/ng"; | ||
|
||
// TODO: This should be revisited and probably re-implemented when replacing Angular router with sth else | ||
export default function useUnsavedChangesAlert(shouldShowAlert = false) { | ||
const shouldShowAlertRef = useRef(); | ||
shouldShowAlertRef.current = shouldShowAlert; | ||
|
||
useEffect(() => { | ||
const unloadMessage = "You will lose your changes if you leave"; | ||
const confirmMessage = `${unloadMessage}\n\nAre you sure you want to leave this page?`; | ||
// store original handler (if any) | ||
const savedOnBeforeUnload = window.onbeforeunload; | ||
|
||
window.onbeforeunload = function onbeforeunload() { | ||
return shouldShowAlertRef.current ? unloadMessage : undefined; | ||
}; | ||
|
||
const unsubscribe = $rootScope.$on("$locationChangeStart", (event, next, current) => { | ||
if (next.split("?")[0] === current.split("?")[0] || next.split("#")[0] === current.split("#")[0]) { | ||
return; | ||
} | ||
|
||
if (shouldShowAlertRef.current && !window.confirm(confirmMessage)) { | ||
event.preventDefault(); | ||
} | ||
}); | ||
|
||
return () => { | ||
window.onbeforeunload = savedOnBeforeUnload; | ||
unsubscribe(); | ||
}; | ||
}, []); | ||
} |