summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/toggle_buttons.js
blob: bcb44bf7acfcc601a6bcc3d2d7ae1e0872ae68d0 (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
import $ from 'jquery';
import Flash from './flash';
import { __ } from './locale';
import { parseBoolean } from './lib/utils/common_utils';

/*
 example HAML:
 ```
  %button.js-project-feature-toggle.project-feature-toggle{ type: "button",
    class: "#{'is-checked' if enabled?}",
    'aria-label': _('Toggle Kubernetes Cluster') }
    %input{ type: "hidden", class: 'js-project-feature-toggle-input', value: enabled? }
  ```
*/

function updateToggle(toggle, isOn) {
  toggle.classList.toggle('is-checked', isOn);
}

function onToggleClicked(toggle, input, clickCallback) {
  const previousIsOn = parseBoolean(input.value);

  // Visually change the toggle and start loading
  updateToggle(toggle, !previousIsOn);
  toggle.setAttribute('disabled', true);
  toggle.classList.toggle('is-loading', true);

  Promise.resolve(clickCallback(!previousIsOn, toggle))
    .then(() => {
      // Actually change the input value
      input.setAttribute('value', !previousIsOn);
    })
    .catch(() => {
      // Revert the visuals if something goes wrong
      updateToggle(toggle, previousIsOn);
    })
    .then(() => {
      // Remove the loading indicator in any case
      toggle.removeAttribute('disabled');
      toggle.classList.toggle('is-loading', false);

      $(input).trigger('trigger-change');
    })
    .catch(() => {
      Flash(__('Something went wrong when toggling the button'));
    });
}

export default function setupToggleButtons(container, clickCallback = () => {}) {
  const toggles = container.querySelectorAll('.js-project-feature-toggle');

  toggles.forEach(toggle => {
    const input = toggle.querySelector('.js-project-feature-toggle-input');
    const isOn = parseBoolean(input.value);

    // Get the visible toggle in sync with the hidden input
    updateToggle(toggle, isOn);

    toggle.addEventListener('click', onToggleClicked.bind(null, toggle, input, clickCallback));
  });
}