This commit is contained in:
44
frontend/src/hooks/useToast.ts
Normal file
44
frontend/src/hooks/useToast.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { signal } from '@preact/signals';
|
||||
|
||||
export type ToastType = 'success' | 'error' | 'info' | 'warning';
|
||||
|
||||
export interface ToastMessage {
|
||||
id: string;
|
||||
type: ToastType;
|
||||
message: string;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
export const toastMessages = signal<ToastMessage[]>([]);
|
||||
|
||||
function getToastMessages(): ToastMessage[] {
|
||||
return Array.isArray(toastMessages.value) ? toastMessages.value : [];
|
||||
}
|
||||
|
||||
function nextId(): string {
|
||||
return `${Date.now()}-${Math.floor(Math.random() * 100000)}`;
|
||||
}
|
||||
|
||||
export function removeToast(id: string): void {
|
||||
toastMessages.value = getToastMessages().filter((toast) => toast.id !== id);
|
||||
}
|
||||
|
||||
export function pushToast(
|
||||
message: string,
|
||||
type: ToastType = 'info',
|
||||
durationMs = 3000
|
||||
): string {
|
||||
const id = nextId();
|
||||
toastMessages.value = [{ id, type, message, durationMs }, ...getToastMessages()].slice(0, 5);
|
||||
return id;
|
||||
}
|
||||
|
||||
export function useToast() {
|
||||
return {
|
||||
success: (message: string, durationMs?: number) => pushToast(message, 'success', durationMs),
|
||||
error: (message: string, durationMs?: number) => pushToast(message, 'error', durationMs),
|
||||
info: (message: string, durationMs?: number) => pushToast(message, 'info', durationMs),
|
||||
warning: (message: string, durationMs?: number) => pushToast(message, 'warning', durationMs),
|
||||
dismiss: removeToast,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user