UNPKG

expo-toastee

Version:

A simple and elegant toast notification library for React Native Expo with Material You and Neobrutalist themes

81 lines (80 loc) 3.3 kB
import { toastConfig } from './ToastConfig'; class ToastManager { constructor() { this.toasts = []; this.listeners = []; this.idCounter = 0; } // Subscribe to toast updates subscribe(listener) { this.listeners.push(listener); // Return unsubscribe function return () => { const index = this.listeners.indexOf(listener); if (index > -1) { this.listeners.splice(index, 1); } }; } // Notify all listeners notify() { console.log('ToastManager: Notifying listeners with toasts:', this.toasts.length); // Create a new array reference to ensure React detects the change this.listeners.forEach(listener => listener([...this.toasts])); } // Add a new toast addToast(type, message, options = {}) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; const globalConfig = toastConfig.getConfig(); const toast = { id: `toast-${++this.idCounter}`, type, message, timestamp: Date.now(), duration: (_b = (_a = options.duration) !== null && _a !== void 0 ? _a : globalConfig.defaultDuration) !== null && _b !== void 0 ? _b : 3000, position: (_d = (_c = options.position) !== null && _c !== void 0 ? _c : globalConfig.defaultPosition) !== null && _d !== void 0 ? _d : 'top', animationType: (_f = (_e = options.animationType) !== null && _e !== void 0 ? _e : globalConfig.defaultAnimationType) !== null && _f !== void 0 ? _f : 'slide', theme: (_h = (_g = options.theme) !== null && _g !== void 0 ? _g : globalConfig.theme) !== null && _h !== void 0 ? _h : 'material', size: (_k = (_j = options.size) !== null && _j !== void 0 ? _j : globalConfig.size) !== null && _k !== void 0 ? _k : 'md', customStyles: (_l = options.customStyles) !== null && _l !== void 0 ? _l : globalConfig.customStyles, }; console.log('ToastManager: Adding toast', toast.id, toast.message); this.toasts.push(toast); this.notify(); // Note: Auto-removal is now handled by the ToastItem component // to ensure proper exit animations } // Remove a toast by ID removeToast(id) { console.log('ToastManager: Removing toast', id); const index = this.toasts.findIndex(toast => toast.id === id); if (index > -1) { this.toasts.splice(index, 1); console.log('ToastManager: Toast removed, remaining:', this.toasts.length); this.notify(); } else { console.log('ToastManager: Toast not found for removal:', id); } } // Clear all toasts clearAll() { this.toasts = []; this.notify(); } // Public methods for different toast types success(message, options) { this.addToast('success', message, options); } error(message, options) { this.addToast('error', message, options); } info(message, options) { this.addToast('info', message, options); } warning(message, options) { this.addToast('warning', message, options); } } // Create singleton instance export const toastManager = new ToastManager();