kontenhumas-fe/lib/swal.ts

131 lines
2.9 KiB
TypeScript

import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
const MySwal = withReactContent(Swal);
const Toast = MySwal.mixin({
toast: true,
position: "top-end",
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener("mouseenter", Swal.stopTimer);
toast.addEventListener("mouseleave", Swal.resumeTimer);
},
});
export function loading(msg?: any) {
let timerInterval: any;
MySwal.fire({
title: msg || "Loading...",
allowOutsideClick: false,
timerProgressBar: true,
didOpen: () => {
MySwal.showLoading();
timerInterval = setInterval(() => {}, 100);
},
willClose: () => {
clearInterval(timerInterval);
},
});
}
export function error(msg?: any) {
MySwal.fire({
icon: "error",
title: "Failed...",
text: msg || "Unknown Error",
});
}
export function successRouter(redirect: string, router?: any) {
MySwal.fire({
title: "Success!",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "Ok",
allowOutsideClick: false,
}).then((result) => {
if (result.isConfirmed) {
router.push(redirect);
}
});
}
export function success(title: string) {
MySwal.fire({
title: title || "Success!",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then((result) => {
if (result.isConfirmed) {
return true;
}
});
}
export function close() {
MySwal.close();
}
export function warning(text: string, redirect: string, router?: any) {
MySwal.fire({
title: text,
icon: "warning",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then((result) => {
if (result.isConfirmed) {
router.push(redirect);
}
});
}
export function successToast(title: string, text: string) {
Toast.fire({
icon: "error",
title: title,
text: text,
});
}
// ✅ Notifikasi sukses auto-close
export function successAutoClose(message: string, duration = 3000) {
Swal.fire({
title: "Sukses!",
text: message,
icon: "success",
timer: duration,
showConfirmButton: false,
timerProgressBar: true,
allowOutsideClick: false,
allowEscapeKey: false,
didOpen: () => {
const popup = Swal.getPopup();
popup?.addEventListener("mouseenter", Swal.stopTimer);
popup?.addEventListener("mouseleave", Swal.resumeTimer);
},
});
}
// ❌ Notifikasi error auto-close
export function errorAutoClose(message: string, duration = 3000) {
Swal.fire({
title: "Gagal!",
text: message,
icon: "error",
timer: duration,
showConfirmButton: false,
timerProgressBar: true,
allowOutsideClick: false,
allowEscapeKey: false,
didOpen: () => {
const popup = Swal.getPopup();
popup?.addEventListener("mouseenter", Swal.stopTimer);
popup?.addEventListener("mouseleave", Swal.resumeTimer);
},
});
}