UNPKG

react-next-toast

Version:
59 lines (58 loc) 2.59 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = __importDefault(require("react")); const client_1 = require("react-dom/client"); const interfaces_1 = require("./interfaces"); const ToastNotification_1 = __importDefault(require("../ToastNotification")); const DEFAULT_DURATION = 5000; const showToast = { success: (message, duration) => showToastComponent({ type: interfaces_1.ToastType.SUCCESS, message: message || interfaces_1.DefaultMessage.SUCCESS, duration: duration || DEFAULT_DURATION, }), error: (message, duration) => showToastComponent({ type: interfaces_1.ToastType.ERROR, message: message || interfaces_1.DefaultMessage.ERROR, duration: duration || DEFAULT_DURATION, }), warning: (message, duration) => showToastComponent({ type: interfaces_1.ToastType.WARNING, message: message || interfaces_1.DefaultMessage.WARNING, duration: duration || DEFAULT_DURATION, }), info: (message, duration) => showToastComponent({ type: interfaces_1.ToastType.INFO, message: message || interfaces_1.DefaultMessage.INFO, duration: duration || DEFAULT_DURATION, }), }; const showToastComponent = (toastDetail) => { const { duration } = toastDetail; const toastContainer = document.createElement("div"); const root = (0, client_1.createRoot)(toastContainer); // Render the ToastNotification component inside the container element root.render(react_1.default.createElement(ToastNotification_1.default, Object.assign({}, toastDetail))); // Find and remove any existing toasts const existingToasts = document.querySelectorAll("[data-toast-container]"); existingToasts.forEach((existingToast) => { if (document.body.contains(existingToast)) { document.body.removeChild(existingToast); } }); // Append the new toast container to the DOM document.body.appendChild(toastContainer); toastContainer.setAttribute("data-toast-container", "true"); // set a timeout to remove the toast notification after a certain time duration && setTimeout(() => { // Check if the toastContainer is still a child of document.body if (document.body.contains(toastContainer)) { document.body.removeChild(toastContainer); } }, duration); }; exports.default = showToast;