From fac760b709fa7e2a83f061abcd066aa4164b5596 Mon Sep 17 00:00:00 2001 From: Rune Harlyk Date: Thu, 2 May 2024 18:47:39 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=94=20Fixes=20notification=20bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/components/toasts/notifications.ts | 38 +++++++------------ 1 file changed, 14 insertions(+), 24 deletions(-) diff --git a/app/src/lib/components/toasts/notifications.ts b/app/src/lib/components/toasts/notifications.ts index 7bf7546..6659a1c 100644 --- a/app/src/lib/components/toasts/notifications.ts +++ b/app/src/lib/components/toasts/notifications.ts @@ -1,40 +1,30 @@ import { writable, derived, type Writable } from 'svelte/store'; -type NotificationType = 'info' | 'error' | 'warning' | 'success'; +type StateType = 'info' | 'success' | 'warning' | 'error'; type State = { id: string; - type: NotificationType; + type: StateType; message: string; - timeout: number; }; function createNotificationStore() { const state: State[] = []; - const _notifications = writable(state); + const notifications = writable(state); + const { subscribe } = notifications; - function send(message: string, type: NotificationType = 'info', timeout: number) { - _notifications.update((state) => { - return [...state, { id: id(), type, message, timeout }]; + function send(message: string, type: StateType = 'info', timeout: number) { + const id = generateId(); + setTimeout(() => { + notifications.update((state) => { + return state.filter((n) => n.id !== id); + }); + }, timeout); + notifications.update((state) => { + return [...state, { id, type, message }]; }); } - const notifications = derived(_notifications, ($_notifications, set) => { - set($_notifications); - if ($_notifications.length > 0) { - const timer = setTimeout(() => { - _notifications.update((state) => { - state.shift(); - return state; - }); - }, $_notifications[0].timeout); - return () => { - clearTimeout(timer); - }; - } - }) as Writable; - const { subscribe } = notifications; - return { subscribe, send, @@ -45,7 +35,7 @@ function createNotificationStore() { }; } -function id() { +function generateId() { return '_' + Math.random().toString(36).substr(2, 9); }