about summary refs log tree commit diff
path: root/assets/src/state/toast.ts
blob: 8eba306a487ae74d70b8da66c1096147d45bf693 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { writable } from "svelte/store";
import generateId from "../utils/generateId";

export enum ToastType {
    INFO,
    ERROR,
}

export type ToastData = {
    type: ToastType;
    message: string;
    title?: string;
};

export type Toast = {
    id: string;
} & ToastData;

export const toasts = writable<Toast[]>([]);

export function toast(toast: ToastData): Toast {
    const toastWithId: Toast = {
        ...toast,
        id: generateId(8),
    };

    toasts.update(toasts => [...toasts, toastWithId]);

    // Dissmiss toast after 5 seconds.
    setTimeout(() => {
        dismissToast(toastWithId);
    }, 5000);

    return toastWithId;
}

// @ts-ignore
window.toast = toast;

export function dismissToast(toast: Toast) {
    toasts.update(toasts => toasts.filter(t => t.id !== toast.id));
}