69 lines
1.9 KiB
JavaScript
69 lines
1.9 KiB
JavaScript
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, 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 }
|
|
]);
|
|
}
|
|
|
|
export function createMessage(text) {
|
|
const currentDate = new Date().toLocaleString();
|
|
messages.update(oldMessages => [
|
|
...oldMessages,
|
|
{ text: text, timestamp: currentDate }
|
|
]);
|
|
}
|
|
|
|
export function clearMessages() {
|
|
messages.set([]);
|
|
}
|