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

CRDCDH-826 Submission Request Auto Save #292

Merged
merged 4 commits into from
Mar 11, 2024
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
2 changes: 1 addition & 1 deletion src/components/Questionnaire/UnsavedChangesDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const UnsavedChangesDialog: FC<Props> = ({
title={title || "Unsaved Changes"}
message={
message
|| "You have unsaved changes. Your changes will be lost if you leave this section without saving. Do you want to save your data?"
|| "Validation errors have been detected. Do you wish to save your changes or discard them before leaving this page?"
}
actions={(
<>
Expand Down
56 changes: 27 additions & 29 deletions src/content/questionnaire/FormView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import {
import { isEqual, cloneDeep } from "lodash";
import {
Alert,
AlertColor,
Container,
Divider,
Stack,
styled,
} from "@mui/material";
import { LoadingButton } from "@mui/lab";
import { useSnackbar } from 'notistack';
import { ReactComponent as ChevronLeft } from "../../assets/icons/chevron_left.svg";
import { ReactComponent as ChevronRight } from "../../assets/icons/chevron_right.svg";
import {
Expand All @@ -34,7 +34,6 @@ import RejectFormDialog from "../../components/Questionnaire/RejectFormDialog";
import ApproveFormDialog from "../../components/Questionnaire/ApproveFormDialog";
import PageBanner from "../../components/PageBanner";
import bannerPng from "../../assets/banner/submission_banner.png";
import GenericAlert from "../../components/GenericAlert";
import {
Status as AuthStatus,
useAuthContext,
Expand Down Expand Up @@ -142,11 +141,6 @@ export type SaveForm =
| { status: "success"; id: string }
| { status: "failed"; errorMessage: string };

type AlertState = {
message: string;
severity: AlertColor;
};

type Props = {
section?: string;
};
Expand All @@ -159,6 +153,7 @@ type Props = {
*/
const FormView: FC<Props> = ({ section } : Props) => {
const navigate = useNavigate();
const { enqueueSnackbar } = useSnackbar();
const { status, data, setData, submitData, approveForm, inquireForm, rejectForm, reopenForm, reviewForm, error } = useFormContext();
const { user, status: authStatus } = useAuthContext();
const [activeSection, setActiveSection] = useState<string>(validateSection(section) ? section : "A");
Expand All @@ -169,7 +164,6 @@ const FormView: FC<Props> = ({ section } : Props) => {
const [openRejectDialog, setOpenRejectDialog] = useState<boolean>(false);
const [hasError, setHasError] = useState<boolean>(false);
const { formMode, readOnlyInputs } = useFormMode();
const [changesAlert, setChangesAlert] = useState<AlertState>(null);
const [allSectionsComplete, setAllSectionsComplete] = useState<boolean>(false);

const sectionKeys = Object.keys(map);
Expand All @@ -182,7 +176,6 @@ const FormView: FC<Props> = ({ section } : Props) => {
const lastSectionRef = useRef(null);
const hasReopenedFormRef = useRef(false);
const hasUpdatedReviewStatusRef = useRef(false);
const alertTimeoutRef = useRef(null);

const refs = {
saveFormRef: createRef<HTMLButtonElement>(),
Expand Down Expand Up @@ -242,21 +235,37 @@ const FormView: FC<Props> = ({ section } : Props) => {
if (formMode === "Unauthorized" && status === FormStatus.LOADED && authStatus === AuthStatus.LOADED) {
return false;
}
if (!readOnlyInputs && isDirty()) {
setBlockedNavigate(true);
return true;
if (!isDirty() || readOnlyInputs) {
return false;
}

// If there are no validation errors, save form data without a prompt
const { ref } = refs.getFormObjectRef.current?.() || {};
if (ref?.current?.checkValidity() === true) {
saveForm();
return false;
}

return false;
setBlockedNavigate(true);
return true;
});

// Intercept browser navigation actions (e.g. closing the tab) with unsaved changes
useEffect(() => {
const unloadHandler = (event: BeforeUnloadEvent) => {
if (isDirty()) {
event.preventDefault();
event.returnValue = 'You have unsaved form changes. Are you sure you want to leave?';
if (!isDirty()) {
return;
}

// If there are no validation errors, save form data without a prompt
const { ref } = refs.getFormObjectRef.current?.() || {};
if (ref?.current?.checkValidity() === true) {
saveForm();
return;
}

event.preventDefault();
event.returnValue = 'You have unsaved form changes. Are you sure you want to leave?';
};

window.addEventListener('beforeunload', unloadHandler);
Expand Down Expand Up @@ -507,16 +516,11 @@ const FormView: FC<Props> = ({ section } : Props) => {
if (!isEqual(data.questionnaireData, newData) || error === ErrorCodes.DUPLICATE_STUDY_ABBREVIATION) {
const res = await setData(newData);
if (res?.status === "failed" && res?.errorMessage === ErrorCodes.DUPLICATE_STUDY_ABBREVIATION) {
setChangesAlert({ severity: "error", message: `The Study Abbreviation already existed in the system. Your changes were unable to be saved.` });
enqueueSnackbar("The Study Abbreviation already existed in the system. Your changes were unable to be saved.", { variant: 'error' });
} else {
setChangesAlert({ severity: "success", message: `Your changes for the ${map[activeSection].title} section have been successfully saved.` });
enqueueSnackbar(`Your changes for the ${map[activeSection].title} section have been successfully saved.`, { variant: 'success' });
}

if (alertTimeoutRef.current) {
clearTimeout(alertTimeoutRef.current);
}
alertTimeoutRef.current = setTimeout(() => setChangesAlert(null), 10000);

if (!blockedNavigate && res?.status === "success" && data["_id"] === "new" && res.id !== data?.['_id']) {
// NOTE: This currently triggers a form data refetch, which is not ideal
navigate(`/submission/${res.id}/${activeSection}`, { replace: true });
Expand Down Expand Up @@ -681,12 +685,6 @@ const FormView: FC<Props> = ({ section } : Props) => {

return (
<>
<GenericAlert open={!!changesAlert} severity={changesAlert?.severity} key="formview-changes-alert">
<span>
{changesAlert?.message}
</span>
</GenericAlert>

<PageBanner
title="Submission Request Form"
subTitle="The following set of high-level questions are intended to provide insight to the CRDC, related to data storage, access, secondary sharing needs and other requirements of data submitters."
Expand Down
Loading