Skip to content

Commit

Permalink
Migrate Query Source page to React: unsaved changes alert (#4505)
Browse files Browse the repository at this point in the history
  • Loading branch information
kravets-levko authored Dec 29, 2019
1 parent 3d5f5b9 commit 2a06152
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
3 changes: 3 additions & 0 deletions client/app/pages/queries/QuerySource.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import useDeleteVisualization from "./hooks/useDeleteVisualization";
import useFormatQuery from "./hooks/useFormatQuery";
import useUpdateQuery from "./hooks/useUpdateQuery";
import useUpdateQueryDescription from "./hooks/useUpdateQueryDescription";
import useUnsavedChangesAlert from "./hooks/useUnsavedChangesAlert";

import "./QuerySource.less";

Expand All @@ -56,6 +57,8 @@ function QuerySource(props) {
const [parameters, areParametersDirty, updateParametersDirtyFlag] = useQueryParameters(query);
const [selectedVisualization, setSelectedVisualization] = useVisualizationTabHandler(query.visualizations);

useUnsavedChangesAlert(isDirty);

const {
queryResult,
queryResultData,
Expand Down
34 changes: 34 additions & 0 deletions client/app/pages/queries/hooks/useUnsavedChangesAlert.js
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();
};
}, []);
}

0 comments on commit 2a06152

Please sign in to comment.