From 92ad28a160f03f2fbc53d0e2c0908e288ea591d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Keviin=20=C3=85berg=20Kultalahti?= Date: Tue, 2 Mar 2021 14:19:44 +0100 Subject: [PATCH] fix notification store timers --- packages/client/src/store/notification.js | 60 ++++++++++------------- 1 file changed, 27 insertions(+), 33 deletions(-) diff --git a/packages/client/src/store/notification.js b/packages/client/src/store/notification.js index 64757569ed..b3a8ffefc3 100644 --- a/packages/client/src/store/notification.js +++ b/packages/client/src/store/notification.js @@ -1,42 +1,33 @@ -import { writable, derived } from "svelte/store" -import { generate } from "shortid" +import { writable } from "svelte/store" const NOTIFICATION_TIMEOUT = 3000 const createNotificationStore = () => { - const _notifications = writable([]) - let block = false + const timeoutIds = new Set(); + const _notifications = writable([], () => { + return () => { + // clear all the timers + timeoutIds.forEach(timeoutId => { + clearTimeout(timeoutId); + }); + _notifications.set([]); + } + }); const send = (message, type = "default") => { - if (block) { - return - } + let _id = id(); _notifications.update(state => { - return [...state, { id: generate(), type, message }] - }) - } + return [...state, { id: _id, type, message }] + }); + const timeoutId = setTimeout(() => { + _notifications.update(state => { + return state.filter(({ id }) => id !== _id); + }); + }, NOTIFICATION_TIMEOUT); + timeoutIds.add(timeoutId); + } - const blockNotifications = (timeout = 1000) => { - block = true - setTimeout(() => (block = false), timeout) - } - - const notifications = derived(_notifications, ($_notifications, set) => { - set($_notifications) - if ($_notifications.length > 0) { - const timeout = setTimeout(() => { - _notifications.update(state => { - state.shift() - return state - }) - set($_notifications) - }, NOTIFICATION_TIMEOUT) - return () => { - clearTimeout(timeout) - } - } - }) - const { subscribe } = notifications + const { subscribe } = _notifications return { subscribe, @@ -45,8 +36,11 @@ const createNotificationStore = () => { warning: msg => send(msg, "warning"), info: msg => send(msg, "info"), success: msg => send(msg, "success"), - blockNotifications, } } -export const notificationStore = createNotificationStore() +function id() { + return '_' + Math.random().toString(36).substr(2, 9); +}; + +export const notificationStore = createNotificationStore() \ No newline at end of file