diff --git a/src/modules/messages.ts b/src/modules/messages.ts index a8bf5cf..d1329bf 100644 --- a/src/modules/messages.ts +++ b/src/modules/messages.ts @@ -1,10 +1,13 @@ import { ref } from 'vue'; import { RenderMessage, Annotation } from "@/types/message/index"; +const messagesKey = "CRIMATA_MESSAGES"; +const sizeLimit = 200; + +// list of messages where the first item is the oldest message. const messages = ref(new Map()); -const messagesKey = "CRIMATA_MESSAGES"; - +// get stored messages. const messagesString = window.localStorage.getItem(messagesKey); if (messagesString) { @@ -14,22 +17,31 @@ if (messagesString) { messages.value = new Map(Object.entries(parsed)); } +// utility function to remove oldest message from the messages map. +function deleteOldest() { + // create array of map keys and get the key of the oldest message. + const lastKey = Array.from(messages.value.keys()).shift(); + + messages.value.delete(lastKey); +} + export default function useMessages() { - // Add new message and update previous message if nessesary. const addMessage = (m: RenderMessage) => { console.log(`Adding message: ${m.content.text}`) + + // check for message limit before setting a new message. + if (messages.value.size >= sizeLimit) deleteOldest(); + messages.value.set(m.uid, m); } - const updateMessage = (a: Annotation) => { - console.log("Updating message...") - - const m = messages.value.get(a.uid) - m.context = a.context - m.text = a.text - - return m + const updateMessage = (m: Annotation) => { + // update message if in the map. + if (messages.value.has(m.uid)) { + messages.value.get(m.uid).context = m.context; + messages.value.get(m.uid).content.text = m.text; + } } const saveMessages = () => {