budibase/packages/bbui/src/Stores/notifications.js

62 lines
1.4 KiB
JavaScript
Raw Normal View History

import { writable } from "svelte/store"
2021-03-31 11:59:07 +02:00
const NOTIFICATION_TIMEOUT = 3000
export const createNotificationStore = () => {
const timeoutIds = new Set()
const _notifications = writable([], () => {
return () => {
// clear all the timers
timeoutIds.forEach(timeoutId => {
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
const send = (message, type = "default", icon = "") => {
if (block) {
return
}
let _id = id()
2021-03-31 11:59:07 +02:00
_notifications.update(state => {
return [...state, { id: _id, type, message, icon }]
2021-03-31 11:59:07 +02:00
})
const timeoutId = setTimeout(() => {
_notifications.update(state => {
return state.filter(({ id }) => id !== _id)
})
}, NOTIFICATION_TIMEOUT)
timeoutIds.add(timeoutId)
2021-03-31 11:59:07 +02:00
}
const { subscribe } = _notifications
2021-03-31 11:59:07 +02:00
return {
subscribe,
send,
info: msg => send(msg, "info", "Info"),
error: msg => send(msg, "error", "Alert"),
warning: msg => send(msg, "warning", "Alert"),
success: msg => send(msg, "success", "CheckmarkCircle"),
blockNotifications,
2021-03-31 11:59:07 +02:00
}
}
function id() {
return (
"_" +
Math.random()
.toString(36)
.substr(2, 9)
)
}
export const notifications = createNotificationStore()