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

62 lines
1.3 KiB
JavaScript
Raw Normal View History

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 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([])
}
})
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") => {
if (block) {
return
}
2021-03-02 14:26:37 +01:00
let _id = id()
_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-03-02 14:19: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-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()