2023-07-21 11:47:09 +00:00
|
|
|
import { writable } from 'svelte/store';
|
2023-07-21 11:13:45 +00:00
|
|
|
|
2023-07-21 11:47:09 +00:00
|
|
|
// 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, defaultValue) {
|
|
|
|
if (isClientSide()) {
|
|
|
|
return localStorage.getItem(key)
|
|
|
|
? JSON.parse(localStorage.getItem(key))
|
|
|
|
: defaultValue;
|
|
|
|
}
|
|
|
|
return defaultValue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Safely set item to localStorage
|
|
|
|
function setToLocalStorage(key, value) {
|
|
|
|
if (isClientSide()) {
|
|
|
|
localStorage.setItem(key, JSON.stringify(value));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Load messages from localStorage or set an empty array if not available
|
|
|
|
const initialMessages = 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 = [
|
|
|
|
"Hello there!",
|
|
|
|
"How are you?",
|
|
|
|
"What's your favorite color?",
|
|
|
|
"Nice weather today!",
|
|
|
|
"Have a great day!",
|
|
|
|
"I love Svelte!",
|
|
|
|
"Svelte is awesome!",
|
|
|
|
"Learning Svelte is fun!",
|
|
|
|
"Greetings from Svelte!",
|
|
|
|
"Keep coding and stay awesome!"
|
|
|
|
];
|
|
|
|
|
|
|
|
export function addRandomMessage() {
|
|
|
|
const randomMessage = messagesList[Math.floor(Math.random() * messagesList.length)];
|
|
|
|
const currentDate = new Date().toLocaleString();
|
|
|
|
messages.update(oldMessages => [
|
|
|
|
...oldMessages,
|
|
|
|
{ text: randomMessage, timestamp: currentDate }
|
|
|
|
]);
|
2023-07-21 11:13:45 +00:00
|
|
|
}
|
|
|
|
|
2023-07-21 12:16:42 +00:00
|
|
|
export function createMessage(text) {
|
|
|
|
const currentDate = new Date().toLocaleString();
|
|
|
|
messages.update(oldMessages => [
|
|
|
|
...oldMessages,
|
|
|
|
{ text: text, timestamp: currentDate }
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
2023-07-21 11:13:45 +00:00
|
|
|
export function clearMessages() {
|
2023-07-21 11:47:09 +00:00
|
|
|
messages.set([]);
|
2023-07-21 11:13:45 +00:00
|
|
|
}
|