Moved Toast logic into own directory

This commit is contained in:
2023-09-19 14:22:00 +01:00
parent f31f180687
commit 1b33bd398d
9 changed files with 6 additions and 9 deletions

28
src/lib/store.ts Normal file
View File

@ -0,0 +1,28 @@
import { ToastType, type Toast } from "$lib/toast";
import { writable, type Writable } from "svelte/store";
export const toasts: Writable<Toast[]> = writable([]);
export const addToast = (toast: Toast) => {
// Create a unique ID so we can easily find/remove it
// if it is dismissible/has a timeout.
toast.id = Math.floor(Math.random() * 10000);
// Setup some sensible defaults for a toast.
const defaults = {
id: toast.id,
type: ToastType.Info,
dismissible: true,
timeout: 3000,
};
// Push the toast to the top of the list of toasts
toasts.update((all) => [{ ...defaults, ...toast }, ...all]);
// If toast is dismissible, dismiss it after "timeout" amount of time.
if (toast.timeout) setTimeout(() => dismissToast(toast.id), toast.timeout);
};
export const dismissToast = (id: number) => {
toasts.update((all) => all.filter((t) => t.id !== id));
};