// Global State Management const AppState = { currentUser: { id: 1, name: 'Admin User', email: 'admin@proflow.com', role: 'admin', avatar: 'http://static.photos/people/200x200/1' }, notifications: [ { id: 1, type: 'approval', message: 'New service order requires approval', read: false, time: '2 hours ago' }, { id: 2, type: 'user', message: 'New analyst registration pending', read: true, time: '1 day ago' }, { id: 3, type: 'project', message: 'Project deadline approaching', read: false, time: '3 days ago' } ] }; // API Service const ApiService = { baseUrl: 'https://jsonplaceholder.typicode.com', async get(endpoint) { try { const response = await fetch(`${this.baseUrl}/${endpoint}`); return await response.json(); } catch (error) { console.error('API Error:', error); throw error; } }, async post(endpoint, data) { try { const response = await fetch(`${this.baseUrl}/${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data) }); return await response.json(); } catch (error) { console.error('API Error:', error); throw error; } } }; // Modern Notification System class NotificationManager { static show(message, type = 'info', options = {}) { const notification = document.createElement('div'); notification.className = `fixed top-4 right-4 z-50 px-6 py-4 rounded-xl shadow-lg slide-in flex items-start space-x-3 ${type === 'success' ? 'bg-emerald-500' : type === 'error' ? 'bg-rose-500' : type === 'warning' ? 'bg-amber-500' : 'bg-blue-500'} text-white`; const iconMap = { success: 'check-circle', error: 'alert-circle', warning: 'alert-triangle', info: 'info' }; notification.innerHTML = `

${options.title || type.toUpperCase()}

${message}

`; document.body.appendChild(notification); feather.replace(); // Auto-dismiss const timeout = options.timeout || 5000; let dismissTimeout = setTimeout(() => { notification.classList.add('fade-out'); setTimeout(() => notification.remove(), 200); }, timeout); // Manual dismiss const dismissBtn = notification.querySelector('button'); dismissBtn.addEventListener('click', () => { clearTimeout(dismissTimeout); notification.classList.add('fade-out'); setTimeout(() => notification.remove(), 200); }); // Hover to pause notification.addEventListener('mouseenter', () => { clearTimeout(dismissTimeout); }); notification.addEventListener('mouseleave', () => { dismissTimeout = setTimeout(() => { notification.classList.add('fade-out'); setTimeout(() => notification.remove(), 200); }, 1000); }); } static showError(message, options = {}) { this.show(message, 'error', options); } static showSuccess(message, options = {}) { this.show(message, 'success', options); } static showWarning(message, options = {}) { this.show(message, 'warning', options); } static showInfo(message, options = {}) { this.show(message, 'info', options); } } // Form Validation class FormValidator { static validateEmail(email) { const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return re.test(email); } static validatePhone(phone) { const re = /^[\+]?[1-9][\d]{0,15}$/; return re.test(phone.replace(/\D/g, '')); } static validateRequired(value) { return value && value.trim().length > 0; } static validatePassword(password) { return password && password.length >= 8; } } // Date and Time Utilities class DateTimeUtils { static formatDate(date) { return new Date(date).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }); } static formatTime(date) { return new Date(date).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }); } static calculateDuration(start, end) { const diff = new Date(end) - new Date(start); const hours = Math.floor(diff / (1000 * 60 * 60)); const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); return `${hours}h ${minutes}m`; } static getCurrentDateTime() { const now = new Date(); return now.toISOString().slice(0, 16); } } // Modern Modal Manager with Animations class ModalManager { static open(modalId) { const modal = document.getElementById(modalId); if (modal) { modal.classList.remove('hidden'); modal.classList.add('flex'); const content = modal.querySelector('.modal-content'); if (content) { content.classList.remove('closing'); content.classList.add('opening'); } document.body.style.overflow = 'hidden'; } } static close(modalId) { const modal = document.getElementById(modalId); if (modal) { const content = modal.querySelector('.modal-content'); if (content) { content.classList.add('closing'); content.classList.remove('opening'); content.addEventListener('animationend', () => { modal.classList.remove('flex'); modal.classList.add('hidden'); document.body.style.overflow = 'auto'; }, { once: true }); } else { modal.classList.remove('flex'); modal.classList.add('hidden'); document.body.style.overflow = 'auto'; } } } static closeAll() { document.querySelectorAll('.modal-overlay').forEach(modal => { const content = modal.querySelector('.modal-content'); if (content) { content.classList.add('closing'); content.classList.remove('opening'); content.addEventListener('animationend', () => { modal.classList.remove('flex'); modal.classList.add('hidden'); }, { once: true }); } else { modal.classList.remove('flex'); modal.classList.add('hidden'); } }); document.body.style.overflow = 'auto'; } } // Data Table Manager class DataTableManager { static initialize(tableId, options = {}) { const table = document.getElementById(tableId); if (!table) return; // Add search functionality if enabled if (options.searchable) { const searchInput = document.createElement('input'); searchInput.type = 'text'; searchInput.placeholder = 'Search...'; searchInput.className = 'form-input mb-4'; searchInput.addEventListener('input', (e) => { const searchTerm = e.target.value.toLowerCase(); const rows = table.querySelectorAll('tbody tr'); rows.forEach(row => { const text = row.textContent.toLowerCase(); row.style.display = text.includes(searchTerm) ? '' : 'none'; }); }); table.parentNode.insertBefore(searchInput, table); } // Add pagination if enabled if (options.paginate && options.pageSize) { this.addPagination(table, options.pageSize); } } static addPagination(table, pageSize) { const tbody = table.querySelector('tbody'); const rows = Array.from(tbody.querySelectorAll('tr')); const totalPages = Math.ceil(rows.length / pageSize); // Hide all rows initially rows.forEach(row => row.style.display = 'none'); // Show first page this.showPage(rows, 0, pageSize); // Create pagination controls const pagination = document.createElement('div'); pagination.className = 'flex justify-center items-center space-x-2 mt-4'; for (let i = 0; i < totalPages; i++) { const button = document.createElement('button'); button.textContent = i + 1; button.className = 'px-3 py-1 rounded-lg border border-gray-300 hover:bg-gray-50'; button.addEventListener('click', () => { this.showPage(rows, i, pageSize); // Update active button pagination.querySelectorAll('button').forEach(btn => { btn.classList.remove('bg-primary-600', 'text-white'); btn.classList.add('border-gray-300', 'hover:bg-gray-50'); }); button.classList.add('bg-primary-600', 'text-white'); button.classList.remove('border-gray-300', 'hover:bg-gray-50'); }); if (i === 0) { button.classList.add('bg-primary-600', 'text-white'); } pagination.appendChild(button); } table.parentNode.appendChild(pagination); } static showPage(rows, pageIndex, pageSize) { const start = pageIndex * pageSize; const end = start + pageSize; rows.forEach((row, index) => { row.style.display = (index >= start && index < end) ? '' : 'none'; }); } } // Role-based Access Control class RBAC { static hasPermission(requiredRole) { const userRole = AppState.currentUser.role; const roleHierarchy = ['analyst', 'manager', 'admin']; const userIndex = roleHierarchy.indexOf(userRole); const requiredIndex = roleHierarchy.indexOf(requiredRole); return userIndex >= requiredIndex; } static checkPermission(requiredRole) { if (!this.hasPermission(requiredRole)) { NotificationManager.showError('You do not have permission to perform this action'); return false; } return true; } } // Modern DOM Initialization document.addEventListener('DOMContentLoaded', function() { // Initialize feather icons if (typeof feather !== 'undefined') { feather.replace(); } // Initialize data tables with search document.querySelectorAll('[data-table="searchable"]').forEach(table => { DataTableManager.initialize(table.id, { searchable: true, paginate: true, pageSize: 5, sortable: true }); }); // Setup modal close handlers document.querySelectorAll('[data-modal-close]').forEach(button => { button.addEventListener('click', function() { const modalId = this.getAttribute('data-modal-close'); ModalManager.close(modalId); }); }); // Close modal when clicking outside document.querySelectorAll('.modal-overlay').forEach(modal => { modal.addEventListener('click', function(e) { if (e.target === this) { ModalManager.closeAll(); } }); }); // Format all dates with data-date attribute document.querySelectorAll('[data-date]').forEach(element => { const date = element.getAttribute('data-date'); if (date) { element.textContent = DateTimeUtils.formatDate(date); } }); // Format all times with data-time attribute document.querySelectorAll('[data-time]').forEach(element => { const time = element.getAttribute('data-time'); if (time) { element.textContent = DateTimeUtils.formatTime(time); } }); // Calculate durations document.querySelectorAll('[data-duration-start][data-duration-end]').forEach(element => { const start = element.getAttribute('data-duration-start'); const end = element.getAttribute('data-duration-end'); if (start && end) { element.textContent = DateTimeUtils.calculateDuration(start, end); } }); // Add hover effects to cards document.querySelectorAll('.card').forEach(card => { card.classList.add('hover-scale'); }); // Add ripple effect to buttons document.querySelectorAll('.btn').forEach(button => { button.addEventListener('click', function(e) { const rect = this.getBoundingClientRect(); const x = e.clientX - rect.left; const y = e.clientY - rect.top; const ripple = document.createElement('span'); ripple.className = 'ripple-effect'; ripple.style.left = `${x}px`; ripple.style.top = `${y}px`; this.appendChild(ripple); setTimeout(() => { ripple.remove(); }, 600); }); }); // Initialize tooltips document.querySelectorAll('[data-tooltip]').forEach(element => { const tooltip = document.createElement('div'); tooltip.className = 'tooltip hidden'; tooltip.textContent = element.getAttribute('data-tooltip'); document.body.appendChild(tooltip); element.addEventListener('mouseenter', (e) => { const rect = element.getBoundingClientRect(); tooltip.classList.remove('hidden'); tooltip.style.left = `${rect.left + rect.width / 2 - tooltip.offsetWidth / 2}px`; tooltip.style.top = `${rect.top - tooltip.offsetHeight - 10}px`; }); element.addEventListener('mouseleave', () => { tooltip.classList.add('hidden'); }); }); }); // Modern Utility Exports window.AppState = AppState; window.ApiService = ApiService; window.NotificationManager = NotificationManager; window.FormValidator = FormValidator; window.DateTimeUtils = DateTimeUtils; window.ModalManager = ModalManager; window.DataTableManager = DataTableManager; window.RBAC = RBAC; // Add modern utility functions window.Utils = { debounce: (func, wait) => { let timeout; return function(...args) { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), wait); }; }, throttle: (func, limit) => { let inThrottle; return function(...args) { if (!inThrottle) { func.apply(this, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; }, copyToClipboard: (text) => { navigator.clipboard.writeText(text).then(() => { NotificationManager.showSuccess('Copied to clipboard!'); }).catch(() => { NotificationManager.showError('Failed to copy text'); }); }, formatBytes: (bytes, decimals = 2) => { if (bytes === 0) return '0 Bytes'; const k = 1024; const dm = decimals < 0 ? 0 : decimals; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; } };