2021-07-30 15:01:01 +02:00
|
|
|
import { writable, get } from "svelte/store"
|
|
|
|
import { generate } from "shortid"
|
2021-08-02 16:12:38 +02:00
|
|
|
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 11:37:34 +01:00
|
|
|
|
2021-01-22 12:21:44 +01:00
|
|
|
const createNotificationStore = () => {
|
2021-07-30 15:01:01 +02:00
|
|
|
let timeout
|
|
|
|
let block = false
|
|
|
|
|
|
|
|
const store = writable(null, () => {
|
2021-03-02 14:26:37 +01:00
|
|
|
return () => {
|
2021-07-30 15:01:01 +02:00
|
|
|
clearTimeout(timeout)
|
2021-03-02 14:26:37 +01:00
|
|
|
}
|
|
|
|
})
|
2021-03-15 08:50:51 +01:00
|
|
|
|
|
|
|
const blockNotifications = (timeout = 1000) => {
|
|
|
|
block = true
|
|
|
|
setTimeout(() => (block = false), timeout)
|
|
|
|
}
|
2021-01-22 12:44:43 +01:00
|
|
|
|
2021-07-30 15:01:01 +02:00
|
|
|
const send = (message, type = "info", icon) => {
|
2021-03-15 08:50:51 +01:00
|
|
|
if (block) {
|
|
|
|
return
|
|
|
|
}
|
2021-08-02 16:12:38 +02:00
|
|
|
|
|
|
|
// If peeking, pass notifications back to parent window
|
|
|
|
if (get(routeStore).queryParams?.peek) {
|
|
|
|
window.dispatchEvent(
|
|
|
|
new CustomEvent("notification", {
|
|
|
|
detail: { message, type, icon },
|
|
|
|
})
|
|
|
|
)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-07-30 15:01:01 +02:00
|
|
|
store.set({
|
|
|
|
id: generate(),
|
|
|
|
type,
|
|
|
|
message,
|
|
|
|
icon,
|
|
|
|
delay: get(store) != null,
|
2021-03-02 14:26:37 +01:00
|
|
|
})
|
2021-07-30 15:01:01 +02:00
|
|
|
clearTimeout(timeout)
|
|
|
|
timeout = setTimeout(() => {
|
|
|
|
store.set(null)
|
2021-03-02 14:26:37 +01:00
|
|
|
}, NOTIFICATION_TIMEOUT)
|
|
|
|
}
|
2021-02-11 10:39:35 +01:00
|
|
|
|
2021-01-22 11:37:34 +01:00
|
|
|
return {
|
2021-07-30 15:01:01 +02:00
|
|
|
subscribe: store.subscribe,
|
|
|
|
actions: {
|
2021-08-02 16:12:38 +02:00
|
|
|
send,
|
2021-07-30 15:01:01 +02:00
|
|
|
info: msg => send(msg, "info", "Info"),
|
|
|
|
success: msg => send(msg, "success", "CheckmarkCircle"),
|
|
|
|
warning: msg => send(msg, "warning", "Alert"),
|
|
|
|
error: msg => send(msg, "error", "Alert"),
|
|
|
|
blockNotifications,
|
|
|
|
},
|
2021-01-22 11:37:34 +01:00
|
|
|
}
|
2021-01-22 12:21:44 +01:00
|
|
|
}
|
|
|
|
|
2021-03-02 14:26:37 +01:00
|
|
|
export const notificationStore = createNotificationStore()
|