diff --git a/packages/frontend/components/Sidebar/SandboxArea.tsx b/packages/frontend/components/Sidebar/SandboxArea.tsx index 74d0edda..9f7fdcaa 100644 --- a/packages/frontend/components/Sidebar/SandboxArea.tsx +++ b/packages/frontend/components/Sidebar/SandboxArea.tsx @@ -9,8 +9,8 @@ import { } from "@chakra-ui/react"; import { forwardRef, useEffect, useState } from "react"; import ResizeTextarea from "react-textarea-autosize"; +import { toast } from "react-toastify"; -// Still a bit buggy const AutoResizeTextarea = forwardRef( (props, ref) => { return ( @@ -33,28 +33,48 @@ interface SandboxAreaProps { planId: string | number; } +type StoredNotes = { + [planId: string]: string; +}; + +function getStoredNotes(): StoredNotes { + const storedNotes = localStorage.getItem("notes"); + if (!storedNotes) { + return {}; + } + + return JSON.parse(storedNotes); +} + +function setStoredNotes(notes: StoredNotes) { + try { + localStorage.setItem("notes", JSON.stringify(notes)); + } catch (e) { + toast.error("Maximum local storage quota exceed. Too many plans."); + } +} + +function getPlanNote(planId: string): string { + const notesObject = getStoredNotes(); + return notesObject[planId] || ""; +} + export const SandboxArea: React.FC = ({ planId }) => { const [notes, setNotes] = useState(""); + const handleNewNotes = (e: React.ChangeEvent) => { if (!planId) return; setNotes(e.target.value); - // Retrieve existing notes from localStorage - const storedNotes = localStorage.getItem("notes"); - const notesObject = storedNotes ? JSON.parse(storedNotes) : {}; - notesObject[planId] = notes; - // have a notes object plan_id (number | string) -> note (string) - localStorage.setItem("notes", JSON.stringify(notesObject)); - //console.log("New notes: ", e.target.value); + const notesObj = getStoredNotes(); + notesObj[planId] = e.target.value; + setStoredNotes(notesObj); }; useEffect(() => { if (!planId) return; - const storedNotes = localStorage.getItem("notes"); - const notesObject = storedNotes ? JSON.parse(storedNotes) : {}; - if (storedNotes) { - setNotes(notesObject[planId]); - } + setNotes(getPlanNote(String(planId))); }, [planId]); + return (