Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate Query Source page to React: unsaved changes alert #4505

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions client/app/pages/queries/QuerySource.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,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 "./query-source.less";

Expand All @@ -55,6 +56,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();
};
}, []);
}