summaryrefslogtreecommitdiff
path: root/src-migrate/utils/checkBoxState.js
blob: 9568c3216e210ff6d9cd3c0a5c6177eb96606f19 (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
90
/**
 * State manager for checkbox updates
 * Tracks global and individual checkbox update states
 */
class CheckboxUpdateState {
  constructor() {
    this.updateCount = 0;
    this.listeners = new Set();
    this.updatingCheckboxIds = new Set();
  }

  // Global update state (for buttons quotation and checkout)
  isUpdating() {
    return this.updateCount > 0;
  }

  // Individual checkbox state
  isCheckboxUpdating(itemId) {
    return this.updatingCheckboxIds.has(String(itemId));
  }

  // Start update
  startUpdate(itemId = null) {
    this.updateCount++;

    if (itemId !== null) {
      this.updatingCheckboxIds.add(String(itemId));
    }

    this.notifyListeners();
    return this.updateCount;
  }

  // End update
  endUpdate(itemId = null) {
    this.updateCount = Math.max(0, this.updateCount - 1);

    if (itemId !== null) {
      this.updatingCheckboxIds.delete(String(itemId));
    }

    this.notifyListeners();
    return this.updateCount;
  }

  // Reset all states
  reset() {
    this.updateCount = 0;
    this.updatingCheckboxIds.clear();
    this.notifyListeners();
  }

  // Listener management
  addListener(callback) {
    if (typeof callback === 'function') {
      this.listeners.add(callback);
      // Immediate callback with current state
      callback(this.isUpdating());
    }
  }

  removeListener(callback) {
    this.listeners.delete(callback);
  }

  // Debug helpers
  getUpdateCount() {
    return this.updateCount;
  }

  getUpdatingCheckboxIds() {
    return [...this.updatingCheckboxIds];
  }

  // Private method to notify listeners
  notifyListeners() {
    const isUpdating = this.isUpdating();

    this.listeners.forEach((listener) => {
      try {
        listener(isUpdating);
      } catch (error) {
        console.error('Checkbox update state listener error:', error);
      }
    });
  }
}

const checkboxUpdateState = new CheckboxUpdateState();
export default checkboxUpdateState;