import { Box, Button, Card, CardContent, TextField, Typography, useTheme, } from "@mui/material" import React, { FC, createRef, useState, useEffect } from "react" import LoadingButton from "@mui/lab/LoadingButton" import SaveIcon from "@mui/icons-material/Save" import { actionCreator } from "../action" export const Note: FC<{ studyId: number latestNote: Note }> = ({ studyId, latestNote }) => { const theme = useTheme() const [saving, setSaving] = useState(false) const [edited, setEdited] = useState(false) const [curNote, setCurNote] = useState({ version: 0, body: "" }) const textAreaRef = createRef() const action = actionCreator() const notLatest = latestNote.version > curNote.version useEffect(() => { setCurNote(latestNote) }, []) useEffect(() => { if (edited) { window.onbeforeunload = (e) => { e.returnValue = "Are you okay to discard your changes?" } } else { window.onbeforeunload = null } }, [edited]) const handleSave = () => { const nextVersion = curNote.version + 1 const newNote = { version: nextVersion, body: textAreaRef.current ? textAreaRef.current.value : "", } setSaving(true) action .saveNote(studyId, newNote) .then(() => { setCurNote(newNote) window.onbeforeunload = null }) .finally(() => { setSaving(false) }) } const handleRefresh = () => { if (!textAreaRef.current) { console.log("Unexpectedly, textarea is not found.") return } textAreaRef.current.value = latestNote.body setCurNote(latestNote) window.onbeforeunload = null } return ( Note { const cur = textAreaRef.current ? textAreaRef.current.value : "" setEdited(cur !== curNote.body) }} /> {notLatest && !saving && ( <> The text you are editing has updated. Do you want to discard your changes and refresh the textarea? )} } variant="contained" disabled={!edited} > Save ) }