From 76ded24e717d13f5cb988a7ab52ece76813eceb4 Mon Sep 17 00:00:00 2001 From: PauloUbirajara Date: Sun, 28 Apr 2024 19:53:01 -0300 Subject: [PATCH] feature: add auto closing timing logic for toasts --- src/components/Toast.svelte | 47 +++++++++++++++++++++++++++++++------ src/lib/toast.ts | 7 +----- src/stores/toast.ts | 2 +- 3 files changed, 42 insertions(+), 14 deletions(-) diff --git a/src/components/Toast.svelte b/src/components/Toast.svelte index cc8ad5a..d643834 100644 --- a/src/components/Toast.svelte +++ b/src/components/Toast.svelte @@ -3,7 +3,7 @@ import type { ToastMessage } from "../domain/models/toastMessage"; import { ToastType } from "../domain/models/toastMessage"; import { toastStore } from "../stores/toast"; - import { Toast } from "flowbite-svelte"; + import { Progressbar, Toast } from "flowbite-svelte"; import { fly } from "svelte/transition"; import { CheckCircleSolid, @@ -11,11 +11,36 @@ ExclamationCircleSolid, } from "flowbite-svelte-icons"; - let toasts: ToastMessage[] = []; + let toast: ToastMessage | null = null; + let showToast: boolean = true; + let currentDuration = 0; + let interval: NodeJS.Timeout; + const MAX_TOAST_DURATION_IN_MS = 30000; + + function removeToast() { + showToast = false; + currentDuration = 0; + toastStore.set(null); + } + + setInterval(() => { + if (toast === null) { + clearInterval(interval); + return; + } + currentDuration += 1000; + if (currentDuration < MAX_TOAST_DURATION_IN_MS) { + return; + } + currentDuration = 0; + removeToast(); + }, 1000); onMount(() => { const unsubscribe = toastStore.subscribe((value) => { - toasts = value; + toast = value; + showToast = true; + currentDuration = 0; }); return unsubscribe; @@ -24,8 +49,6 @@ type ToastColors = | "green" | "red" - | "orange" - | "none" | "gray" | "yellow" | "indigo" @@ -44,12 +67,14 @@ } -{#each toasts as toast} +{#if toast !== null} removeToast()} > {#if toast.type === ToastType.SUCCESS} @@ -69,5 +94,13 @@ {toast.title}
{toast.message}
+
-{/each} +{/if} diff --git a/src/lib/toast.ts b/src/lib/toast.ts index 53a9a66..e4c7747 100644 --- a/src/lib/toast.ts +++ b/src/lib/toast.ts @@ -1,11 +1,6 @@ import type { ToastMessage } from "../domain/models/toastMessage"; import { toastStore } from "../stores/toast"; -const MAX_TOASTS_SHOWN = 3; - export function showToast(message: ToastMessage) { - toastStore.update((toasts: ToastMessage[]) => [ - message, - ...toasts.slice(0, MAX_TOASTS_SHOWN), - ]); + toastStore.set(message); } diff --git a/src/stores/toast.ts b/src/stores/toast.ts index caa607d..732f35f 100644 --- a/src/stores/toast.ts +++ b/src/stores/toast.ts @@ -1,4 +1,4 @@ import { writable } from "svelte/store"; import type { Writable } from "svelte/store"; -export const toastStore: Writable = writable([]); +export const toastStore: Writable = writable(null);