Skip to content

Commit

Permalink
Allow ignoring routes in ConfirmLeaveDialog component. (Graylog2#20271
Browse files Browse the repository at this point in the history
)
  • Loading branch information
linuspahl authored Aug 27, 2024
1 parent 496233d commit 9b2fae4
Showing 1 changed file with 11 additions and 13 deletions.
24 changes: 11 additions & 13 deletions graylog2-web-interface/src/components/common/ConfirmLeaveDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
import PropTypes from 'prop-types';
import type { Location } from 'react-router-dom';
import { useBlocker } from 'react-router-dom';
import { useCallback, useEffect } from 'react';
Expand All @@ -23,17 +22,20 @@ import AppConfig from 'util/AppConfig';

/**
* This component should be conditionally rendered if you have a form that is in a "dirty" state. It will confirm with the user that they want to navigate away, refresh, or in any way unload the component.
* The `ignoredRoutes` prop is an array of routes that should not trigger the confirmation dialog.
*/
type Props = {
question: string,
question?: string,
ignoredRoutes?: Array<string>,
};

const locationHasChanged = (currentLocation: Location, newLocation: Location, question: string) => ((newLocation.pathname !== currentLocation.pathname)
// eslint-disable-next-line no-alert
? !window.confirm(question)
: false);
const locationHasChanged = (currentLocation: Location, newLocation: Location, question: string, ignoredRoutes: Array<string>) => (
(newLocation.pathname !== currentLocation.pathname && !ignoredRoutes.includes(newLocation.pathname))
// eslint-disable-next-line no-alert
? !window.confirm(question)
: false);

const ConfirmLeaveDialog = ({ question }: Props) => {
const ConfirmLeaveDialog = ({ question, ignoredRoutes }: Props) => {
const handleLeavePage = useCallback((e) => {
if (AppConfig.gl2DevMode()) {
return null;
Expand All @@ -52,18 +54,14 @@ const ConfirmLeaveDialog = ({ question }: Props) => {
};
}, [handleLeavePage]);

useBlocker((history) => !AppConfig.gl2DevMode() && locationHasChanged(history.currentLocation, history.nextLocation, question));
useBlocker((history) => !AppConfig.gl2DevMode() && locationHasChanged(history.currentLocation, history.nextLocation, question, ignoredRoutes));

return null;
};

ConfirmLeaveDialog.propTypes = {
/** Phrase used in the confirmation dialog. */
question: PropTypes.string,
};

ConfirmLeaveDialog.defaultProps = {
question: 'Are you sure?',
ignoredRoutes: [],
};

/** @component */
Expand Down

0 comments on commit 9b2fae4

Please sign in to comment.