Skip to content

Commit

Permalink
proposal - styled modal that warns the user is leaving a form. (#3966)
Browse files Browse the repository at this point in the history
Co-authored-by: Smith <[email protected]>
  • Loading branch information
devinleighsmith and Smith authored May 17, 2024
1 parent 0bb6ba9 commit 925c663
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
42 changes: 42 additions & 0 deletions source/frontend/src/components/common/ConfirmNavigation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Location } from 'history';
import { useEffect, useState } from 'react';
import { Prompt } from 'react-router-dom';

import { getCancelModalProps, useModalContext } from '@/hooks/useModalContext';

interface Props {
when?: boolean | undefined;
navigate: (path: string) => void;
shouldBlockNavigation: (location: Location) => boolean;
}

const ConfirmNavigation = ({ when, navigate, shouldBlockNavigation }: Props) => {
const { setDisplayModal, setModalContent } = useModalContext();
const [lastLocation, setLastLocation] = useState<Location | null>(null);
const [confirmedNavigation, setConfirmedNavigation] = useState(false);

const handleConfirmNavigationClick = () => {
setDisplayModal(false);
setConfirmedNavigation(true);
};

const handleBlockedNavigation = (nextLocation: Location): boolean => {
if (!confirmedNavigation && shouldBlockNavigation(nextLocation)) {
setModalContent({ ...getCancelModalProps(), handleOk: () => handleConfirmNavigationClick() });
setDisplayModal(true);
setLastLocation(nextLocation);
return false;
}
return true;
};

useEffect(() => {
if (confirmedNavigation && lastLocation) {
// Navigate to the previous blocked location with your navigate function
navigate(lastLocation.pathname);
}
}, [confirmedNavigation, lastLocation, navigate]);

return <Prompt when={when} message={handleBlockedNavigation} />;
};
export default ConfirmNavigation;
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useHistory } from 'react-router-dom';
import { toast } from 'react-toastify';
import styled from 'styled-components';

import ConfirmNavigation from '@/components/common/ConfirmNavigation';
import { useMapStateMachine } from '@/components/common/mapFSM/MapStateMachineContext';
import MapSideBarLayout from '@/features/mapSideBar/layout/MapSideBarLayout';
import { usePimsPropertyRepository } from '@/hooks/repositories/usePimsPropertyRepository';
Expand Down Expand Up @@ -213,6 +214,12 @@ export const AddResearchContainer: React.FunctionComponent<IAddResearchContainer
<StyledFormWrapper>
<AddResearchForm confirmBeforeAdd={confirmBeforeAdd} />
</StyledFormWrapper>
<ConfirmNavigation
navigate={history.push}
shouldBlockNavigation={() => {
return formikProps.dirty && !formikProps.isSubmitting && !initialForm.id;
}}
/>
</MapSideBarLayout>
)}
</Formik>
Expand Down

0 comments on commit 925c663

Please sign in to comment.