2021-04-09 12:02:53 +02:00
|
|
|
import { writable } from "svelte/store"
|
2021-03-31 11:59:07 +02:00
|
|
|
|
|
|
|
const NOTIFICATION_TIMEOUT = 3000
|
|
|
|
|
2021-04-09 12:02:53 +02:00
|
|
|
export const createNotificationStore = () => {
|
|
|
|
const timeoutIds = new Set()
|
|
|
|
const _notifications = writable([], () => {
|
|
|
|
return () => {
|
|
|
|
// clear all the timers
|
2021-05-04 12:32:22 +02:00
|
|
|
timeoutIds.forEach(timeoutId => {
|
2021-04-09 12:02:53 +02:00
|
|
|
clearTimeout(timeoutId)
|
|
|
|
})
|
|
|
|
_notifications.set([])
|
|
|
|
}
|
|
|
|
})
|
|
|
|
let block = false
|
|
|
|
|
|
|
|
const blockNotifications = (timeout = 1000) => {
|
|
|
|
block = true
|
|
|
|
setTimeout(() => (block = false), timeout)
|
|
|
|
}
|
2021-03-31 11:59:07 +02:00
|
|
|
|
2022-02-07 16:24:46 +01:00
|
|
|
const send = (message, type = "default", icon = "", autoDismiss = true) => {
|
2021-04-09 12:02:53 +02:00
|
|
|
if (block) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
let _id = id()
|
2021-05-04 12:32:22 +02:00
|
|
|
_notifications.update(state => {
|
2022-02-07 16:24:46 +01:00
|
|
|
return [
|
|
|
|
...state,
|
|
|
|
{ id: _id, type, message, icon, dismissable: !autoDismiss },
|
|
|
|
]
|
2022-02-07 16:15:28 +01:00
|
|
|
})
|
2022-02-07 16:24:46 +01:00
|
|
|
if (autoDismiss) {
|
2022-02-07 16:15:28 +01:00
|
|
|
const timeoutId = setTimeout(() => {
|
|
|
|
dismissNotification(_id)
|
|
|
|
}, NOTIFICATION_TIMEOUT)
|
|
|
|
timeoutIds.add(timeoutId)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const dismissNotification = id => {
|
|
|
|
_notifications.update(state => {
|
|
|
|
return state.filter(n => n.id !== id)
|
2021-03-31 11:59:07 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-04-09 12:02:53 +02:00
|
|
|
const { subscribe } = _notifications
|
2021-03-31 11:59:07 +02:00
|
|
|
|
|
|
|
return {
|
|
|
|
subscribe,
|
|
|
|
send,
|
2021-05-04 12:32:22 +02:00
|
|
|
info: msg => send(msg, "info", "Info"),
|
2022-02-07 16:15:28 +01:00
|
|
|
error: msg => send(msg, "error", "Alert", false),
|
2021-05-04 12:32:22 +02:00
|
|
|
warning: msg => send(msg, "warning", "Alert"),
|
|
|
|
success: msg => send(msg, "success", "CheckmarkCircle"),
|
2021-04-09 12:02:53 +02:00
|
|
|
blockNotifications,
|
2022-02-07 16:15:28 +01:00
|
|
|
dismiss: dismissNotification,
|
2021-03-31 11:59:07 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function id() {
|
2022-02-20 15:28:39 +01:00
|
|
|
return "_" + Math.random().toString(36).slice(2, 9)
|
2021-03-31 11:59:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export const notifications = createNotificationStore()
|