161 lines
5.0 KiB
TypeScript
161 lines
5.0 KiB
TypeScript
import { createContext, useContext, useEffect, useMemo, useState } from "react";
|
||
import type { ReactNode } from "react";
|
||
import { createPortal } from "react-dom";
|
||
import type { ToastPayload, ToastVariant } from "../../lib/toast";
|
||
|
||
type ToastItem = {
|
||
id: string;
|
||
variant: ToastVariant;
|
||
title: string;
|
||
message: string;
|
||
durationMs: number;
|
||
};
|
||
|
||
type ToastContextType = {
|
||
notify: (payload: ToastPayload) => void;
|
||
};
|
||
|
||
const ToastContext = createContext<ToastContextType | undefined>(undefined);
|
||
|
||
const DEFAULT_TITLES: Record<ToastVariant, string> = {
|
||
success: "Berhasil",
|
||
error: "Gagal",
|
||
warning: "Perhatian",
|
||
info: "Info",
|
||
};
|
||
|
||
const VARIANT_STYLES: Record<
|
||
ToastVariant,
|
||
{ container: string; dot: string }
|
||
> = {
|
||
success: {
|
||
container:
|
||
"border-success-500 bg-success-50 text-success-700 dark:border-success-500/30 dark:bg-success-500/15 dark:text-success-300",
|
||
dot: "bg-success-500",
|
||
},
|
||
error: {
|
||
container:
|
||
"border-error-500 bg-error-50 text-error-700 dark:border-error-500/30 dark:bg-error-500/15 dark:text-error-300",
|
||
dot: "bg-error-500",
|
||
},
|
||
warning: {
|
||
container:
|
||
"border-warning-500 bg-warning-50 text-warning-700 dark:border-warning-500/30 dark:bg-warning-500/15 dark:text-warning-300",
|
||
dot: "bg-warning-500",
|
||
},
|
||
info: {
|
||
container:
|
||
"border-blue-light-500 bg-blue-light-50 text-blue-light-700 dark:border-blue-light-500/30 dark:bg-blue-light-500/15 dark:text-blue-light-300",
|
||
dot: "bg-blue-light-500",
|
||
},
|
||
};
|
||
|
||
function makeId() {
|
||
if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
|
||
return crypto.randomUUID();
|
||
}
|
||
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||
}
|
||
|
||
function normalizeMessage(message: string) {
|
||
const text = String(message || "").trim();
|
||
return text || "Terjadi kesalahan.";
|
||
}
|
||
|
||
export function ToastProvider({ children }: { children: ReactNode }) {
|
||
const [items, setItems] = useState<ToastItem[]>([]);
|
||
|
||
const notify = (payload: ToastPayload) => {
|
||
const variant = payload.variant ?? "info";
|
||
const title = payload.title ?? DEFAULT_TITLES[variant];
|
||
const message = normalizeMessage(payload.message);
|
||
const durationMs = payload.durationMs ?? 4000;
|
||
const id = makeId();
|
||
|
||
setItems((prev) => [
|
||
...prev,
|
||
{ id, variant, title, message, durationMs },
|
||
]);
|
||
|
||
window.setTimeout(() => {
|
||
setItems((prev) => prev.filter((item) => item.id !== id));
|
||
}, durationMs);
|
||
};
|
||
|
||
useEffect(() => {
|
||
const onToast = (event: Event) => {
|
||
const detail = (event as CustomEvent<ToastPayload>).detail;
|
||
if (!detail || !detail.message) return;
|
||
notify(detail);
|
||
};
|
||
|
||
const onUnhandledRejection = (event: PromiseRejectionEvent) => {
|
||
const reason = event.reason;
|
||
const message =
|
||
typeof reason === "string"
|
||
? reason
|
||
: reason?.message || "Terjadi kesalahan.";
|
||
notify({ variant: "error", title: "Gagal", message });
|
||
};
|
||
|
||
window.addEventListener("app-toast", onToast as EventListener);
|
||
window.addEventListener("unhandledrejection", onUnhandledRejection);
|
||
return () => {
|
||
window.removeEventListener("app-toast", onToast as EventListener);
|
||
window.removeEventListener("unhandledrejection", onUnhandledRejection);
|
||
};
|
||
}, []);
|
||
|
||
const value = useMemo(() => ({ notify }), []);
|
||
|
||
const container = (
|
||
<div className="fixed right-4 top-4 z-[100000] flex w-[min(380px,calc(100vw-32px))] flex-col gap-3">
|
||
{items.map((item) => (
|
||
<div
|
||
key={item.id}
|
||
className={`rounded-xl border p-4 shadow-theme-lg ${VARIANT_STYLES[item.variant].container}`}
|
||
>
|
||
<div className="flex items-start gap-3">
|
||
<span
|
||
className={`mt-1 h-2.5 w-2.5 shrink-0 rounded-full ${VARIANT_STYLES[item.variant].dot}`}
|
||
/>
|
||
<div className="flex-1">
|
||
<div className="flex items-start justify-between gap-2">
|
||
<h4 className="text-sm font-semibold text-gray-900 dark:text-white/90">
|
||
{item.title}
|
||
</h4>
|
||
<button
|
||
type="button"
|
||
onClick={() =>
|
||
setItems((prev) => prev.filter((t) => t.id !== item.id))
|
||
}
|
||
className="rounded-md px-1 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
|
||
aria-label="Tutup"
|
||
>
|
||
×
|
||
</button>
|
||
</div>
|
||
<p className="mt-1 text-sm text-gray-700 dark:text-gray-300">
|
||
{item.message}
|
||
</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
);
|
||
|
||
return (
|
||
<ToastContext.Provider value={value}>
|
||
{children}
|
||
{typeof document !== "undefined" ? createPortal(container, document.body) : container}
|
||
</ToastContext.Provider>
|
||
);
|
||
}
|
||
|
||
export function useToast() {
|
||
const ctx = useContext(ToastContext);
|
||
if (!ctx) throw new Error("useToast must be used within a ToastProvider");
|
||
return ctx;
|
||
}
|