2021-03-02 14:19:44 +01:00
|
|
|
import { writable } from "svelte/store"
|
2021-01-22 12:21:44 +01:00
|
|
|
|
2021-01-22 13:11:38 +01:00
|
|
|
const NOTIFICATION_TIMEOUT = 3000
|
2021-01-22 11:37:34 +01:00
|
|
|
|
2021-01-22 12:21:44 +01:00
|
|
|
const createNotificationStore = () => {
|
2021-03-02 14:26:37 +01:00
|
|
|
const timeoutIds = new Set()
|
2021-03-02 14:19:44 +01:00
|
|
|
const _notifications = writable([], () => {
|
2021-03-02 14:26:37 +01:00
|
|
|
return () => {
|
|
|
|
// clear all the timers
|
|
|
|
timeoutIds.forEach(timeoutId => {
|
|
|
|
clearTimeout(timeoutId)
|
|
|
|
})
|
|
|
|
_notifications.set([])
|
|
|
|
}
|
|
|
|
})
|
2021-03-15 08:50:51 +01:00
|
|
|
let block = false
|
|
|
|
|
|
|
|
const blockNotifications = (timeout = 1000) => {
|
|
|
|
block = true
|
|
|
|
setTimeout(() => (block = false), timeout)
|
|
|
|
}
|
2021-01-22 12:44:43 +01:00
|
|
|
|
|
|
|
const send = (message, type = "default") => {
|
2021-03-15 08:50:51 +01:00
|
|
|
if (block) {
|
|
|
|
return
|
|
|
|
}
|
2021-03-02 14:26:37 +01:00
|
|
|
let _id = id()
|
2021-01-22 11:37:34 +01:00
|
|
|
_notifications.update(state => {
|
2021-03-02 14:19:44 +01:00
|
|
|
return [...state, { id: _id, type, message }]
|
2021-03-02 14:26:37 +01:00
|
|
|
})
|
|
|
|
const timeoutId = setTimeout(() => {
|
|
|
|
_notifications.update(state => {
|
|
|
|
return state.filter(({ id }) => id !== _id)
|
|
|
|
})
|
|
|
|
}, NOTIFICATION_TIMEOUT)
|
|
|
|
timeoutIds.add(timeoutId)
|
|
|
|
}
|
2021-02-11 10:39:35 +01:00
|
|
|
|
2021-03-02 14:19:44 +01:00
|
|
|
const { subscribe } = _notifications
|
2021-01-22 11:37:34 +01:00
|
|
|
|
|
|
|
return {
|
|
|
|
subscribe,
|
2021-01-22 12:44:43 +01:00
|
|
|
send,
|
2021-01-22 11:37:34 +01:00
|
|
|
danger: msg => send(msg, "danger"),
|
2021-01-22 12:44:43 +01:00
|
|
|
warning: msg => send(msg, "warning"),
|
|
|
|
info: msg => send(msg, "info"),
|
|
|
|
success: msg => send(msg, "success"),
|
2021-03-15 08:50:51 +01:00
|
|
|
blockNotifications,
|
2021-01-22 11:37:34 +01:00
|
|
|
}
|
2021-01-22 12:21:44 +01:00
|
|
|
}
|
|
|
|
|
2021-03-02 14:19:44 +01:00
|
|
|
function id() {
|
2021-03-02 14:26:37 +01:00
|
|
|
return (
|
|
|
|
"_" +
|
|
|
|
Math.random()
|
|
|
|
.toString(36)
|
|
|
|
.substr(2, 9)
|
|
|
|
)
|
|
|
|
}
|
2021-03-02 14:19:44 +01:00
|
|
|
|
2021-03-02 14:26:37 +01:00
|
|
|
export const notificationStore = createNotificationStore()
|