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

54 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"
let NOTIFICATION_TIMEOUT = 3000
2021-01-22 12:21:44 +01:00
const createNotificationStore = () => {
const _notifications = writable([])
const send = (message, type = "default") => {
_notifications.update(state => {
2021-01-22 12:21:44 +01:00
return [
...state,
2021-01-22 12:21:44 +01:00
{ id: generate(), type, message },
]
})
}
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 () => {
clearTimeout(timeout);
};
}
})
2021-01-22 12:21:44 +01:00
const { subscribe } = notifications
return {
subscribe,
send,
danger: msg => send(msg, "danger"),
warning: msg => send(msg, "warning"),
info: msg => send(msg, "info"),
success: msg => send(msg, "success"),
}
2021-01-22 12:21:44 +01:00
}
export const notificationStore = createNotificationStore()
// setTimeout(() => {
// notificationStore.update(state => {
// state.notifications.shift()
// state.notifications = state.notifications
// return state
// })
// }, timeout)