From 87e6e2809e4da62616bc624d58c8e82bf81c7e16 Mon Sep 17 00:00:00 2001 From: Sam Date: Tue, 14 Mar 2023 23:59:02 +0100 Subject: [PATCH] feat: add toasts --- frontend/src/lib/components/Toast.svelte | 13 +++++++++ frontend/src/lib/toast.ts | 35 ++++++++++++++++++++++++ frontend/src/routes/+layout.svelte | 7 +++++ 3 files changed, 55 insertions(+) create mode 100644 frontend/src/lib/components/Toast.svelte create mode 100644 frontend/src/lib/toast.ts diff --git a/frontend/src/lib/components/Toast.svelte b/frontend/src/lib/components/Toast.svelte new file mode 100644 index 0000000..aae6233 --- /dev/null +++ b/frontend/src/lib/components/Toast.svelte @@ -0,0 +1,13 @@ + + + + {body} + diff --git a/frontend/src/lib/toast.ts b/frontend/src/lib/toast.ts new file mode 100644 index 0000000..70b14bb --- /dev/null +++ b/frontend/src/lib/toast.ts @@ -0,0 +1,35 @@ +import { writable } from "svelte/store"; + +export interface ToastData { + header?: string; + body: string; + duration?: number; +} + +interface IdToastData extends ToastData { + id: number; +} + +export const toastStore = writable([]); + +let maxId = 0; + +export const addToast = (data: ToastData) => { + const id = maxId++; + + console.log(id); + + toastStore.update((toasts) => (toasts = [...toasts, { ...data, id }])); + + if (data.duration !== -1) { + setTimeout(() => { + toastStore.update((toasts) => (toasts = toasts.filter((toast) => toast.id !== id))); + }, data.duration ?? 5000); + } + + return id; +}; + +export const delToast = (id: number) => { + toastStore.update((toasts) => (toasts = toasts.filter((toast) => toast.id !== id))); +}; diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte index 06675e5..e5e5bb7 100644 --- a/frontend/src/routes/+layout.svelte +++ b/frontend/src/routes/+layout.svelte @@ -5,6 +5,8 @@ import Navigation from "./nav/Navigation.svelte"; import type { LayoutData } from "./$types"; import { version } from "$app/environment"; + import { toastStore } from "$lib/toast"; + import Toast from "$lib/components/Toast.svelte"; export let data: LayoutData; @@ -24,6 +26,11 @@
+
+ {#each $toastStore as toast} + + {/each} +