68 lines
1.6 KiB
TypeScript
68 lines
1.6 KiB
TypeScript
"use client";
|
|
|
|
import {
|
|
toast as hotToast,
|
|
type ToastOptions,
|
|
type ToastPosition,
|
|
} from "react-hot-toast";
|
|
|
|
import { FALLBACK_LOCALE, resolveLocale } from "@/lib/locale";
|
|
|
|
type ToastVariant = "default" | "success" | "error" | "loading";
|
|
|
|
type ToastMessage = string;
|
|
|
|
function getCurrentLocale() {
|
|
if (typeof window === "undefined") {
|
|
return FALLBACK_LOCALE;
|
|
}
|
|
|
|
const pathname = window.location.pathname;
|
|
const maybeLocale = pathname.split("/")[1] || FALLBACK_LOCALE;
|
|
|
|
return resolveLocale(maybeLocale, FALLBACK_LOCALE);
|
|
}
|
|
|
|
function getToastPosition(isArabic: boolean): ToastPosition {
|
|
return isArabic ? "top-right" : "top-left";
|
|
}
|
|
|
|
function getToastOptions(): ToastOptions {
|
|
const locale = getCurrentLocale();
|
|
const isArabic = locale === "ar";
|
|
|
|
return {
|
|
duration: 1800,
|
|
position: getToastPosition(isArabic),
|
|
};
|
|
}
|
|
|
|
function showToast(message: ToastMessage, variant: ToastVariant = "default") {
|
|
const options = getToastOptions();
|
|
|
|
if (variant === "success") {
|
|
return hotToast.success(message, options);
|
|
}
|
|
|
|
if (variant === "error") {
|
|
return hotToast.error(message, options);
|
|
}
|
|
|
|
if (variant === "loading") {
|
|
return hotToast.loading(message, options);
|
|
}
|
|
|
|
return hotToast(message, options);
|
|
}
|
|
|
|
export const toast = Object.assign(
|
|
(message: ToastMessage) => showToast(message, "default"),
|
|
{
|
|
success: (message: ToastMessage) => showToast(message, "success"),
|
|
error: (message: ToastMessage) => showToast(message, "error"),
|
|
loading: (message: ToastMessage) => showToast(message, "loading"),
|
|
dismiss: hotToast.dismiss,
|
|
remove: hotToast.remove,
|
|
},
|
|
);
|