2018-03-17 18:26:18 +05:30
|
|
|
import $ from 'jquery';
|
2021-09-30 23:02:18 +05:30
|
|
|
import createFlash from './flash';
|
2019-02-15 15:39:39 +05:30
|
|
|
import { parseBoolean } from './lib/utils/common_utils';
|
2021-03-11 19:13:27 +05:30
|
|
|
import { __ } from './locale';
|
2018-03-17 18:26:18 +05:30
|
|
|
|
|
|
|
/*
|
|
|
|
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) {
|
2019-02-15 15:39:39 +05:30
|
|
|
const previousIsOn = parseBoolean(input.value);
|
2018-03-17 18:26:18 +05:30
|
|
|
|
|
|
|
// 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(() => {
|
2021-09-30 23:02:18 +05:30
|
|
|
createFlash({
|
|
|
|
message: __('Something went wrong when toggling the button'),
|
|
|
|
});
|
2018-03-17 18:26:18 +05:30
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function setupToggleButtons(container, clickCallback = () => {}) {
|
|
|
|
const toggles = container.querySelectorAll('.js-project-feature-toggle');
|
|
|
|
|
2021-03-08 18:12:59 +05:30
|
|
|
toggles.forEach((toggle) => {
|
2018-03-17 18:26:18 +05:30
|
|
|
const input = toggle.querySelector('.js-project-feature-toggle-input');
|
2019-02-15 15:39:39 +05:30
|
|
|
const isOn = parseBoolean(input.value);
|
2018-03-17 18:26:18 +05:30
|
|
|
|
|
|
|
// Get the visible toggle in sync with the hidden input
|
|
|
|
updateToggle(toggle, isOn);
|
|
|
|
|
|
|
|
toggle.addEventListener('click', onToggleClicked.bind(null, toggle, input, clickCallback));
|
|
|
|
});
|
|
|
|
}
|