🔔 Fixes notification bug

This commit is contained in:
Rune Harlyk
2024-05-02 18:47:39 +02:00
committed by Rune Harlyk
parent 95914ec334
commit fac760b709
+14 -24
View File
@@ -1,40 +1,30 @@
import { writable, derived, type Writable } from 'svelte/store'; import { writable, derived, type Writable } from 'svelte/store';
type NotificationType = 'info' | 'error' | 'warning' | 'success'; type StateType = 'info' | 'success' | 'warning' | 'error';
type State = { type State = {
id: string; id: string;
type: NotificationType; type: StateType;
message: string; message: string;
timeout: number;
}; };
function createNotificationStore() { function createNotificationStore() {
const state: State[] = []; const state: State[] = [];
const _notifications = writable(state); const notifications = writable(state);
const { subscribe } = notifications;
function send(message: string, type: NotificationType = 'info', timeout: number) { function send(message: string, type: StateType = 'info', timeout: number) {
_notifications.update((state) => { const id = generateId();
return [...state, { id: id(), type, message, timeout }]; setTimeout(() => {
notifications.update((state) => {
return state.filter((n) => n.id !== id);
});
}, timeout);
notifications.update((state) => {
return [...state, { id, type, message }];
}); });
} }
const notifications = derived(_notifications, ($_notifications, set) => {
set($_notifications);
if ($_notifications.length > 0) {
const timer = setTimeout(() => {
_notifications.update((state) => {
state.shift();
return state;
});
}, $_notifications[0].timeout);
return () => {
clearTimeout(timer);
};
}
}) as Writable<State[]>;
const { subscribe } = notifications;
return { return {
subscribe, subscribe,
send, send,
@@ -45,7 +35,7 @@ function createNotificationStore() {
}; };
} }
function id() { function generateId() {
return '_' + Math.random().toString(36).substr(2, 9); return '_' + Math.random().toString(36).substr(2, 9);
} }