some ui updates
This commit is contained in:
71
src/lib/services/messages.ts
Normal file
71
src/lib/services/messages.ts
Normal 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([]);
|
||||
}
|
Reference in New Issue
Block a user