import { getData, setData } from "@helpers/alpine"; export default function (Alpine) { let notificationId = 0; let queuePosition = 0; Alpine.directive("notification", (el, { expression }, { evaluate }) => { notificationId++; const data = getData(el); const type = evaluate(expression); const options = evaluate("$options"); const notification = Alpine.reactive({ id: notificationId, type, autoShow: options.show, showDelay: options.showDelay, shown: false, autoDismiss: options.dismiss, dismissDelay: options.dismissDelay, dismissed: false, dismissTimer: null, position: options.position, queuePosition: 0, init() { data.$dispatch(`${type}:init`, { id: notification.id, type: notification.type, [type]: notification, }); if (notification.autoShow) { setTimeout(() => notification.show(), notification.showDelay); } }, show() { if (!notification.shown) { notification.queuePosition = queuePosition++; notification.startAutoDismiss(); notification.shown = true; data.$dispatch(`${type}:show`, { id: notification.id, queuePosition: notification.queuePosition, type: notification.type, [type]: notification, }); } }, dismiss() { notification.dismissed = true; notification.clearAutoDismiss(); data.$dispatch(`${type}:dismiss`, { id: notification.id, [type]: notification, }); setTimeout(() => el.remove(), 500); }, startAutoDismiss() { if (notification.autoDismiss === true) { notification.dismissTimer = setTimeout( () => notification.dismiss(), notification.dismissDelay ); } }, clearAutoDismiss() { clearTimeout(notification.dismissTimer); }, clearFromQueue(event) { if ( notification.type === event.detail.type && notification.position === "fixed" && notification.id !== event.detail.id && notification.queuePosition < event.detail.queuePosition ) { notification.dismiss(); } }, }); setData(el, { notification }); evaluate("notification.init"); }).before("init"); }