Files
admin-panel-hokm/lib/toast.ts
T
2026-08-07 09:40:16 +03:30

38 lines
1.1 KiB
TypeScript

"use client";
// سیستمِ توستِ سبک (بدونِ وابستگی): یک pub/sub ساده که پیام‌ها را به Toaster می‌دهد.
export type ToastType = "error" | "success" | "info";
export type ToastItem = { id: number; msg: string; type: ToastType };
type Listener = (items: ToastItem[]) => void;
let items: ToastItem[] = [];
let seq = 1;
const listeners = new Set<Listener>();
function emit() {
for (const l of listeners) l(items);
}
/** یک توست نشان می‌دهد (پیش‌فرض: خطا). پس از چند ثانیه خودش محو می‌شود. */
export function toast(msg: string, type: ToastType = "error") {
const id = seq++;
items = [...items, { id, msg, type }];
emit();
setTimeout(() => {
items = items.filter((t) => t.id !== id);
emit();
}, type === "error" ? 5000 : 3000);
}
export const toastError = (msg: string) => toast(msg, "error");
export const toastSuccess = (msg: string) => toast(msg, "success");
export function subscribe(l: Listener) {
listeners.add(l);
l(items);
return () => {
listeners.delete(l);
};
}