notification.js

2.27 KB
05/11/2024 06:27
JS
notification.js
const NotificationManager = {
    container: null,

    init() {
        this.container = document.getElementById('notificationContainer');
        if (!this.container) {
            this.container = document.createElement('div');
            this.container.id = 'notificationContainer';
            this.container.className = 'notification-container';
            document.body.appendChild(this.container);
        }
    },

    show(message, type = 'info', duration = CONFIG.NOTIFICATION_DURATION) {
        const notification = document.createElement('div');
        notification.className = `notification ${type} fade-in`;
        
        notification.innerHTML = `
            <div class="notification-content">
                <div class="notification-icon">
                    ${this.getIcon(type)}
                </div>
                <div class="notification-message">
                    ${Utils.sanitizeHTML(message)}
                </div>
                <button class="notification-close">&times;</button>
            </div>
        `;

        // Close button handler
        notification.querySelector('.notification-close')
            .addEventListener('click', () => this.hide(notification));

        this.container.appendChild(notification);

        // Auto-hide after duration
        if (duration > 0) {
            setTimeout(() => this.hide(notification), duration);
        }

        return notification;
    },

    hide(notification) {
        notification.classList.add('fade-out');
        setTimeout(() => notification.remove(), 300);
    },

    getIcon(type) {
        switch (type) {
            case 'success':
                return '<i class="fas fa-check-circle"></i>';
            case 'error':
                return '<i class="fas fa-exclamation-circle"></i>';
            case 'warning':
                return '<i class="fas fa-exclamation-triangle"></i>';
            default:
                return '<i class="fas fa-info-circle"></i>';
        }
    },

    showSuccess(message) {
        return this.show(message, 'success');
    },

    showError(message) {
        return this.show(message, 'error');
    },

    showWarning(message) {
        return this.show(message, 'warning');
    },

    showInfo(message) {
        return this.show(message, 'info');
    }
};