🔔 Fixes notification bug
This commit is contained in:
@@ -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);
|
||||||
|
|
||||||
function send(message: string, type: NotificationType = 'info', timeout: number) {
|
|
||||||
_notifications.update((state) => {
|
|
||||||
return [...state, { id: id(), type, message, timeout }];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
const { subscribe } = notifications;
|
||||||
|
|
||||||
|
function send(message: string, type: StateType = 'info', timeout: number) {
|
||||||
|
const id = generateId();
|
||||||
|
setTimeout(() => {
|
||||||
|
notifications.update((state) => {
|
||||||
|
return state.filter((n) => n.id !== id);
|
||||||
|
});
|
||||||
|
}, timeout);
|
||||||
|
notifications.update((state) => {
|
||||||
|
return [...state, { id, type, message }];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user