summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/clusters/clusters_index.js
blob: efdf2de55835df18e712c01ab542849f8c599580 (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
import Flash from '../flash';
import { s__ } from '../locale';
import ClustersService from './services/clusters_service';

/**
 * Handles toggle buttons in the cluster's table.
 *
 * When the user clicks the toggle button for each cluster, it:
 * - toggles the button
 * - shows a loding and disabled state
 * - Makes a put request to the given endpoint
 * Once we receive the response, either:
 * 1) Show updated status in case of successfull response
 * 2) Show initial status in case of failed response
 */
export default class ClusterTable {
  constructor() {
    this.container = '.js-clusters-list';
    document.querySelectorAll(`${this.container} .js-toggle-cluster-list`).forEach(button => button.addEventListener('click', e => ClusterTable.updateCluster(e)));
  }

  removeListeners() {
    document.querySelectorAll(`${this.container} .js-toggle-cluster-list`).forEach(button => button.removeEventListener('click'));
  }

  static updateCluster(e) {
    const toggleButton = e.currentTarget;
    const value = toggleButton.classList.contains('checked').toString();
    const endpoint = toggleButton.getAttribute('data-endpoint');

    ClusterTable.toggleValue(toggleButton);
    ClusterTable.toggleLoadingButton(toggleButton);

    ClustersService.updateCluster(endpoint, { cluster: { enabled: value } })
      .then(() => {
        ClusterTable.toggleLoadingButton(toggleButton);
      })
      .catch(() => {
        ClusterTable.toggleLoadingButton(toggleButton);
        ClusterTable.toggleValue(toggleButton);
        Flash(s__('ClusterIntegration|Something went wrong on our end.'));
      });
  }

  /**
   * Toggles loading and disabled classes.
   * @param {HTMLElement} button
   */
  static toggleLoadingButton(button) {
    if (button.getAttribute('disabled')) {
      button.removeAttribute('disabled');
    } else {
      button.setAttribute('disabled', true);
    }

    button.classList.toggle('disabled');
    button.classList.toggle('is-loading');
    button.querySelector('.loading-icon').classList.toggle('hidden');
  }

  /**
   * Toggles checked class for the given button
   * @param {HTMLElement} button
   */
  static toggleValue(button) {
    button.classList.toggle('checked');
  }
}