first commit
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
"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);
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user