publish: prevent leaving note with unsaved changes

Fixes #3838
This commit is contained in:
Tyler Brown Cifu Shuster 2020-10-29 20:03:39 -07:00
parent e279b08049
commit 61442c4c2e
2 changed files with 26 additions and 2 deletions

View File

@ -1,3 +1,4 @@
import React from 'react';
import _ from 'lodash';
import f from 'lodash/fp';
import bigInt from 'big-integer';
@ -325,3 +326,12 @@ export function numToUd(num) {
f.join('.')
)(num.toString())
}
export function usePreventWindowUnload(shouldPreventDefault) {
React.useEffect(() => {
if (!shouldPreventDefault) return;
const handleBeforeUnload = event => event.preventDefault();
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [shouldPreventDefault]);
}

View File

@ -1,7 +1,9 @@
import React, { useCallback } from "react";
import { UnControlled as CodeEditor } from "react-codemirror2";
import { MOBILE_BROWSER_REGEX } from "~/logic/lib/util";
import { useFormikContext } from 'formik';
import { Prompt } from 'react-router-dom';
import { MOBILE_BROWSER_REGEX, usePreventWindowUnload } from "~/logic/lib/util";
import { PropFunc } from "~/types/util";
import CodeMirror from "codemirror";
@ -22,6 +24,17 @@ interface MarkdownEditorProps {
onBlur?: (e: any) => void;
}
const PromptIfDirty = () => {
const formik = useFormikContext();
usePreventWindowUnload(formik.dirty);
return (
<Prompt
when={formik.dirty}
message="Are you sure you want to leave? You have with unsaved changes."
/>
);
};
export function MarkdownEditor(
props: MarkdownEditorProps & PropFunc<typeof Box>
) {
@ -63,6 +76,7 @@ export function MarkdownEditor(
height={['calc(100% - 22vh)', '100%']}
{...boxProps}
>
<PromptIfDirty />
<CodeEditor
autoCursor={false}
onBlur={onBlur}