summaryrefslogtreecommitdiff
path: root/src-migrate/utils/checkBoxState.js
blob: 0c58321fa7d2dd940c7ce513c91e12eedbdca321 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// ~/modules/cart/utils/checkboxUpdateState.js

/**
 * 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)
  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;