budibase/packages/client/src/store/notification.js

53 lines
1.2 KiB
JavaScript
Raw Normal View History

import { writable, derived } from "svelte/store"
2021-01-22 12:21:44 +01:00
import { generate } from "shortid"
2021-01-22 13:11:38 +01:00
const NOTIFICATION_TIMEOUT = 3000
2021-01-22 12:21:44 +01:00
const createNotificationStore = () => {
const _notifications = writable([])
let block = false
2021-01-22 12:44:43 +01:00
const send = (message, type = "default") => {
if (block) {
return
}
_notifications.update(state => {
2021-01-22 12:44:43 +01:00
return [...state, { id: generate(), type, message }]
})
}
2021-01-22 12:44:43 +01:00
const blockNotifications = (timeout = 1000) => {
block = true
setTimeout(() => (block = false), timeout)
}
const notifications = derived(_notifications, ($_notifications, set) => {
2021-01-22 12:21:44 +01:00
set($_notifications)
if ($_notifications.length > 0) {
const timeout = setTimeout(() => {
_notifications.update(state => {
state.shift()
return state
})
set($_notifications)
}, NOTIFICATION_TIMEOUT)
return () => {
2021-01-22 12:44:43 +01:00
clearTimeout(timeout)
}
2021-01-22 12:21:44 +01:00
}
2021-01-22 12:44:43 +01:00
})
2021-01-22 12:21:44 +01:00
const { subscribe } = notifications
return {
subscribe,
2021-01-22 12:44:43 +01:00
send,
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"),
blockNotifications,
}
2021-01-22 12:21:44 +01:00
}
2021-01-22 12:44:43 +01:00
export const notificationStore = createNotificationStore()