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

89 lines
1.9 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 = () => {
2022-07-20 14:54:45 +02:00
const timeoutIds = new Set()
let block = false
const store = writable([], () => {
2021-03-02 14:26:37 +01:00
return () => {
2022-07-20 14:54:45 +02:00
timeoutIds.forEach(timeoutId => {
clearTimeout(timeoutId)
})
store.set([])
2021-03-02 14:26:37 +01:00
}
})
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-20 14:54:45 +02:00
const timeoutId = setTimeout(() => {
dismiss(_id)
}, NOTIFICATION_TIMEOUT)
2022-07-20 14:54:45 +02:00
timeoutIds.add(timeoutId)
}
}
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 => send(msg, "info", "Info"),
success: msg => send(msg, "success", "CheckmarkCircle"),
warning: msg => send(msg, "warning", "Alert"),
error: msg => send(msg, "error", "Alert", 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()