demarches-normaliennes/app/javascript/shared/utils.js

65 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-10-09 11:32:27 +02:00
import Rails from 'rails-ujs';
import $ from 'jquery';
import debounce from 'debounce';
export { debounce };
export const { fire, ajax } = Rails;
2018-10-09 11:32:27 +02:00
2018-09-06 19:23:27 +02:00
export function show({ classList }) {
classList.remove('hidden');
}
export function hide({ classList }) {
classList.add('hidden');
}
export function toggle({ classList }) {
classList.toggle('hidden');
}
2018-10-09 11:32:27 +02:00
export function delegate(eventNames, selector, callback) {
eventNames
.split(' ')
.forEach(eventName =>
Rails.delegate(document, selector, eventName, callback)
);
}
export function getJSON(url, data, method = 'get') {
data = method !== 'get' ? JSON.stringify(data) : data;
return $.ajax({
method,
url,
data,
contentType: 'application/json',
dataType: 'json'
});
}
export function scrollTo(container, scrollTo) {
2018-10-09 11:43:38 +02:00
container.scrollTop =
offset(scrollTo).top - offset(container).top + container.scrollTop;
2018-10-09 11:32:27 +02:00
}
export function scrollToBottom(container) {
2018-10-09 11:43:38 +02:00
container.scrollTop = container.scrollHeight;
2018-10-09 11:32:27 +02:00
}
export function on(selector, eventName, fn) {
[...document.querySelectorAll(selector)].forEach(element =>
element.addEventListener(eventName, event => fn(event, event.detail))
);
}
2018-10-09 11:43:38 +02:00
export function to(promise) {
return promise.then(result => [result]).catch(error => [null, error]);
}
2018-10-09 11:43:38 +02:00
function offset(element) {
const rect = element.getBoundingClientRect();
return {
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
};
}