import { ref } from 'vue';
import { RenderMessage, Annotation } from "@/types/message/index";
-const messages = ref(new Map());
-
const messagesKey = "CRIMATA_MESSAGES";
+const sizeLimit = 200;
+
+// list of messages where the first item is the oldest message.
+const messages = ref(new Map());
+// get stored messages.
const messagesString = window.localStorage.getItem(messagesKey);
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() {
- const addMessage = (m: RenderMessage) => messages.value.set(m.uid, m);
+ const addMessage = (m: RenderMessage) => {
+ // check for message limit before setting a new message.
+ if (messages.value.size >= sizeLimit) deleteOldest();
+
+ messages.value.set(m.uid, m);
+ }
const updateMessage = (m: Annotation) => {
// update message if in the map.