ziko-toaster
Version:
🎉 Professional toast notification library with RTL support, animations, and zero dependencies
1 lines • 2.9 kB
JavaScript
class AdvancedToast{constructor(){this.containers={},this.defaultOptions={type:"info",title:"",message:"",duration:3e3,position:"top-right",animation:"slide",showProgress:!0,pauseOnHover:!0,closeOnClick:!0,rtl:!1}}getContainer(t){if(!this.containers[t]){const e=document.createElement("div");e.className=`toast-container ${t}`,document.body.appendChild(e),this.containers[t]=e}return this.containers[t]}getIcon(t){const e={success:"fa-check-circle",error:"fa-times-circle",warning:"fa-exclamation-triangle",info:"fa-info-circle"};return e[t]||e.info}getTitle(t,e=!1){const s=e?{success:"نجاØ!",error:"خطأ!",warning:"ØªØØ°ÙŠØ±!",info:"معلومة"}:{success:"Success!",error:"Error!",warning:"Warning!",info:"Info"};return s[t]||s.info}show(t){const e={...this.defaultOptions,...t},s=this.getContainer(e.position),i=document.createElement("div"),n="slide"===e.animation?e.position.includes("left")?"slide-left":"slide-right":e.animation,o=e.rtl?"toast-rtl":"toast-ltr";i.className=`my-toast ${e.type} ${n} ${o}`,i.setAttribute("dir",e.rtl?"rtl":"ltr");const r=e.title||this.getTitle(e.type,e.rtl);let a;i.innerHTML=`\n <div class="toast-icon-wrapper">\n <i class="fas ${this.getIcon(e.type)}"></i>\n </div>\n <div class="toast-content">\n <div class="toast-title">${r}</div>\n ${e.message?`<div class="toast-message">${e.message}</div>`:""}\n </div>\n <div class="toast-close">\n <i class="fas fa-times"></i>\n </div>\n ${e.showProgress?`<div class="toast-progress" style="animation-duration: ${e.duration}ms;"></div>`:""}\n `,s.appendChild(i);let c=!1;const l=()=>{i.classList.remove("show"),setTimeout(()=>{i.remove(),0===s.children.length&&(s.remove(),delete this.containers[e.position])},400)};requestAnimationFrame(()=>{i.classList.add("show"),a=setTimeout(l,e.duration)}),e.pauseOnHover&&(i.addEventListener("mouseenter",()=>{if(!c){clearTimeout(a),c=!0;const t=i.querySelector(".toast-progress");t&&(t.style.animationPlayState="paused")}}),i.addEventListener("mouseleave",()=>{if(c){const t=i.querySelector(".toast-progress");if(t){const s=parseFloat(getComputedStyle(t).width)/parseFloat(getComputedStyle(i).width)*e.duration;clearTimeout(a),a=setTimeout(l,s),t.style.animationPlayState="running"}c=!1}}));return i.querySelector(".toast-close").addEventListener("click",t=>{t.stopPropagation(),clearTimeout(a),l()}),e.closeOnClick&&i.addEventListener("click",()=>{clearTimeout(a),l()}),i}success(t,e={}){return this.show({...e,type:"success",message:t})}error(t,e={}){return this.show({...e,type:"error",message:t})}warning(t,e={}){return this.show({...e,type:"warning",message:t})}info(t,e={}){return this.show({...e,type:"info",message:t})}}