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

84 lines
1.8 KiB
JavaScript
Raw Normal View History

import { writable, get } from "svelte/store"
import { routeStore } from "./routes"
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 = () => {
let block = false
2022-07-28 10:39:24 +02:00
const store = writable([])
const blockNotifications = (timeout = 1000) => {
block = true
setTimeout(() => (block = false), timeout)
}
2021-01-22 12:44:43 +01:00
const send = (message, type = "info", icon, autoDismiss = true) => {
if (block) {
return
}
// If peeking, pass notifications back to parent window
if (get(routeStore).queryParams?.peek) {
2021-11-04 17:22:02 +01:00
window.parent.postMessage({
type: "notification",
detail: {
message,
type,
icon,
autoDismiss,
2021-11-04 17:22:02 +01:00
},
})
return
}
2022-07-20 14:54:45 +02:00
const _id = id()
store.update(state => {
2022-07-20 14:54:45 +02:00
return [
...state,
{
id: _id,
type,
message,
icon,
dismissable: !autoDismiss,
delay: get(store) != null,
2022-07-20 14:55:12 +02:00
},
]
})
if (autoDismiss) {
2022-07-28 10:39:24 +02:00
setTimeout(() => {
2022-07-20 14:54:45 +02:00
dismiss(_id)
}, NOTIFICATION_TIMEOUT)
}
}
const dismiss = id => {
store.update(state => {
return state.filter(n => n.id !== id)
})
2021-03-02 14:26:37 +01:00
}
return {
subscribe: store.subscribe,
actions: {
send,
info: (msg, autoDismiss) =>
send(msg, "info", "Info", autoDismiss ?? true),
success: (msg, autoDismiss) =>
send(msg, "success", "CheckmarkCircle", autoDismiss ?? true),
warning: (msg, autoDismiss) =>
send(msg, "warning", "Alert", autoDismiss ?? true),
error: (msg, autoDismiss) =>
send(msg, "error", "Alert", autoDismiss ?? false),
blockNotifications,
dismiss,
},
}
2022-07-20 14:54:45 +02:00
function id() {
return "_" + Math.random().toString(36).slice(2, 9)
}
2021-01-22 12:21:44 +01:00
}
2021-03-02 14:26:37 +01:00
export const notificationStore = createNotificationStore()