some ui updates

This commit is contained in:
Samuel Andert
2023-07-21 14:48:44 +02:00
parent 5be272d1f2
commit 207b154035
7 changed files with 109 additions and 81 deletions

View File

@ -0,0 +1,71 @@
import { writable } from 'svelte/store';
// Helper function to determine if we're running on the client side (browser) or server side.
function isClientSide() {
return typeof window !== "undefined";
}
// Safely get item from localStorage
function getFromLocalStorage(key: string, defaultValue: any) {
if (isClientSide()) {
return localStorage.getItem(key)
? JSON.parse(localStorage.getItem(key)!)
: defaultValue;
}
return defaultValue;
}
// Safely set item to localStorage
function setToLocalStorage(key: string, value: any) {
if (isClientSide()) {
localStorage.setItem(key, JSON.stringify(value));
}
}
// Define the updated Message interface
interface Message {
text: string;
timestamp: string;
sender: string;
type: string;
}
// Load messages from localStorage or set an empty array if not available
const initialMessages: Message[] = getFromLocalStorage('chat-messages', []);
export const messages = writable(initialMessages);
// Subscribe to messages store to watch for changes and save them to localStorage
messages.subscribe(currentMessages => {
setToLocalStorage('chat-messages', currentMessages);
});
// Dummy messages
const messagesList: Message[] = [
{ text: "Hello there!", timestamp: new Date().toLocaleString(), sender: "John", type: "text" },
{ text: "How are you?", timestamp: new Date().toLocaleString(), sender: "Alice", type: "text" },
// Add more dummy messages here with the timestamp and sender properties
];
export function addRandomMessage() {
const randomMessage = messagesList[Math.floor(Math.random() * messagesList.length)];
messages.update(oldMessages => [
...oldMessages,
{ ...randomMessage, timestamp: new Date().toLocaleString(), sender: "Bot", type: "chat" }
]);
}
export function createMessage(text: string, sender: string, type: string) {
const currentDate = new Date().toLocaleString();
const newMessageObj: Message = {
text: text,
timestamp: currentDate,
sender: sender,
type: type
};
messages.update(oldMessages => [...oldMessages, newMessageObj]);
}
export function clearMessages() {
messages.set([]);
}