/** * Enhanced state manager for checkbox updates * Tracks both global update state and individual checkbox update states */ // Track the number of ongoing updates let updateCount = 0; let listeners = []; // Track which checkboxes are currently updating by ID let updatingCheckboxIds = new Set(); const checkboxUpdateState = { // Check if any checkboxes are currently updating (for buttons quotation and checkout) isUpdating: () => updateCount > 0, // Check if a specific checkbox is updating (for disabling just that checkbox) isCheckboxUpdating: (itemId) => updatingCheckboxIds.has(itemId.toString()), // Start an update for a specific checkbox startUpdate: (itemId = null) => { updateCount++; // If an item ID is provided, mark it as updating if (itemId !== null) { updatingCheckboxIds.add(itemId.toString()); } notifyListeners(); return updateCount; }, // End an update for a specific checkbox endUpdate: (itemId = null) => { updateCount = Math.max(0, updateCount - 1); // If an item ID is provided, remove it from updating set if (itemId !== null) { updatingCheckboxIds.delete(itemId.toString()); } notifyListeners(); return updateCount; }, // Reset the update counter and clear all updating checkboxes reset: () => { updateCount = 0; updatingCheckboxIds.clear(); notifyListeners(); }, // Get IDs of all checkboxes currently updating (for debugging) // getUpdatingCheckboxIds: () => [...updatingCheckboxIds], // // Add a listener function to be called when update state changes // addListener: (callback) => { // if (typeof callback === 'function') { // listeners.push(callback); // // Immediately call with current state // callback(updateCount > 0); // } // }, // Remove a listener removeListener: (callback) => { listeners = listeners.filter((listener) => listener !== callback); }, // Get current counter (for debugging) getUpdateCount: () => updateCount, }; // Private function to notify all listeners of state changes function notifyListeners() { const isUpdating = updateCount > 0; listeners.forEach((listener) => { try { listener(isUpdating); } catch (error) { console.error('Error in checkbox update state listener:', error); } }); } export default checkboxUpdateState;