1
0
Fork 0
mirror of synced 2024-10-01 01:28:51 +13:00

Add notification store timeouts

This commit is contained in:
Mel O'Hagan 2022-07-20 13:54:45 +01:00
parent 4e2dea375a
commit 63d3f0117e

View file

@ -1,16 +1,17 @@
import { writable, get } from "svelte/store" import { writable, get } from "svelte/store"
import { generate } from "shortid"
import { routeStore } from "./routes" import { routeStore } from "./routes"
const NOTIFICATION_TIMEOUT = 3000 const NOTIFICATION_TIMEOUT = 3000
const createNotificationStore = () => { const createNotificationStore = () => {
let timeout const timeoutIds = new Set()
let block = false let block = false
const store = writable([], () => { const store = writable([], () => {
return () => { return () => {
clearTimeout(timeout) timeoutIds.forEach(timeoutId => {
clearTimeout(timeoutId)
})
store.set([]) store.set([])
} }
}) })
@ -38,10 +39,12 @@ const createNotificationStore = () => {
}) })
return return
} }
const _id = id()
store.update(state => { store.update(state => {
return [...state, return [
...state,
{ {
id: generate(), id: _id,
type, type,
message, message,
icon, icon,
@ -49,16 +52,15 @@ const createNotificationStore = () => {
delay: get(store) != null, delay: get(store) != null,
} }
]}) ]})
clearTimeout(timeout)
if (autoDismiss) { if (autoDismiss) {
timeout = setTimeout(() => { const timeoutId = setTimeout(() => {
store.set(null) dismiss(_id)
}, NOTIFICATION_TIMEOUT) }, NOTIFICATION_TIMEOUT)
timeoutIds.add(timeoutId)
} }
} }
const dismiss = id => { const dismiss = id => {
clearTimeout(timeout)
store.update(state => { store.update(state => {
return state.filter(n => n.id !== id) return state.filter(n => n.id !== id)
}) })
@ -76,6 +78,10 @@ const createNotificationStore = () => {
dismiss, dismiss,
}, },
} }
function id() {
return "_" + Math.random().toString(36).slice(2, 9)
}
} }
export const notificationStore = createNotificationStore() export const notificationStore = createNotificationStore()