46 lines
796 B
TypeScript
46 lines
796 B
TypeScript
type ToastType = "info" | "error";
|
|
|
|
interface Toast {
|
|
id: number;
|
|
message: string;
|
|
type: ToastType;
|
|
}
|
|
|
|
const DEFAULT_TIMEOUT = 4000;
|
|
|
|
function createToasts() {
|
|
let items = $state<Toast[]>([]);
|
|
let nextId = 0;
|
|
|
|
function dismiss(id: number) {
|
|
items = items.filter((toast) => toast.id !== id);
|
|
}
|
|
|
|
function show(
|
|
message: string,
|
|
type: ToastType = "info",
|
|
timeout = DEFAULT_TIMEOUT
|
|
) {
|
|
nextId += 1;
|
|
const id = nextId;
|
|
items = [...items, { id, message, type }];
|
|
if (timeout > 0) {
|
|
setTimeout(() => dismiss(id), timeout);
|
|
}
|
|
return id;
|
|
}
|
|
|
|
return {
|
|
dismiss,
|
|
error(message: string) {
|
|
return show(message, "error");
|
|
},
|
|
get items() {
|
|
return items;
|
|
},
|
|
show,
|
|
};
|
|
}
|
|
|
|
export const toasts = createToasts();
|