fix notification store timers

This commit is contained in:
Keviin Åberg Kultalahti 2021-03-02 14:19:44 +01:00
parent 4575285d5f
commit 92ad28a160
1 changed files with 27 additions and 33 deletions

View File

@ -1,42 +1,33 @@
import { writable, derived } from "svelte/store" import { writable } from "svelte/store"
import { generate } from "shortid"
const NOTIFICATION_TIMEOUT = 3000 const NOTIFICATION_TIMEOUT = 3000
const createNotificationStore = () => { const createNotificationStore = () => {
const _notifications = writable([]) const timeoutIds = new Set();
let block = false const _notifications = writable([], () => {
return () => {
// clear all the timers
timeoutIds.forEach(timeoutId => {
clearTimeout(timeoutId);
});
_notifications.set([]);
}
});
const send = (message, type = "default") => { const send = (message, type = "default") => {
if (block) { let _id = id();
return
}
_notifications.update(state => { _notifications.update(state => {
return [...state, { id: generate(), type, message }] return [...state, { id: _id, type, message }]
}) });
} const timeoutId = setTimeout(() => {
_notifications.update(state => {
return state.filter(({ id }) => id !== _id);
});
}, NOTIFICATION_TIMEOUT);
timeoutIds.add(timeoutId);
}
const blockNotifications = (timeout = 1000) => { const { subscribe } = _notifications
block = true
setTimeout(() => (block = false), timeout)
}
const notifications = derived(_notifications, ($_notifications, set) => {
set($_notifications)
if ($_notifications.length > 0) {
const timeout = setTimeout(() => {
_notifications.update(state => {
state.shift()
return state
})
set($_notifications)
}, NOTIFICATION_TIMEOUT)
return () => {
clearTimeout(timeout)
}
}
})
const { subscribe } = notifications
return { return {
subscribe, subscribe,
@ -45,8 +36,11 @@ const createNotificationStore = () => {
warning: msg => send(msg, "warning"), warning: msg => send(msg, "warning"),
info: msg => send(msg, "info"), info: msg => send(msg, "info"),
success: msg => send(msg, "success"), success: msg => send(msg, "success"),
blockNotifications,
} }
} }
function id() {
return '_' + Math.random().toString(36).substr(2, 9);
};
export const notificationStore = createNotificationStore() export const notificationStore = createNotificationStore()