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

46 lines
1.1 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:19:44 +01:00
const timeoutIds = new Set();
const _notifications = writable([], () => {
return () => {
// clear all the timers
timeoutIds.forEach(timeoutId => {
clearTimeout(timeoutId);
});
_notifications.set([]);
}
});
2021-01-22 12:44:43 +01:00
const send = (message, type = "default") => {
2021-03-02 14:19:44 +01:00
let _id = id();
_notifications.update(state => {
2021-03-02 14:19:44 +01:00
return [...state, { id: _id, type, message }]
});
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"),
}
2021-01-22 12:21:44 +01:00
}
2021-03-02 14:19:44 +01:00
function id() {
return '_' + Math.random().toString(36).substr(2, 9);
};
export const notificationStore = createNotificationStore()