2019-07-02 14:38:42 +02:00
|
|
|
import Rails from '@rails/ujs';
|
2018-07-12 11:50:47 +02:00
|
|
|
import jQuery from 'jquery';
|
2018-10-09 11:35:22 +02:00
|
|
|
import { delegate } from '@utils';
|
2018-07-12 11:50:47 +02:00
|
|
|
|
|
|
|
// We use `jQuery.active` in our capybara suit to wait for ajax requests.
|
|
|
|
// Newer jQuery-less version of rails-ujs is breaking it.
|
|
|
|
// We have to set `ajax:complete` listener on the same element as the one
|
|
|
|
// we catch ajax:send on as by the end of the request
|
|
|
|
// the old element may be removed from DOM.
|
2018-10-09 11:35:22 +02:00
|
|
|
delegate('ajax:send', '[data-remote]', ({ target }) => {
|
2018-07-12 11:50:47 +02:00
|
|
|
let callback = () => {
|
|
|
|
jQuery.active--;
|
|
|
|
target.removeEventListener('ajax:complete', callback);
|
|
|
|
};
|
|
|
|
target.addEventListener('ajax:complete', callback);
|
|
|
|
jQuery.active++;
|
|
|
|
});
|
|
|
|
|
|
|
|
// `smart_listing` gem is overriding `$.rails.href` method. When using newer
|
|
|
|
// jQuery-less version of rails-ujs it breaks.
|
|
|
|
// https://github.com/Sology/smart_listing/blob/master/app/assets/javascripts/smart_listing.coffee.erb#L9
|
|
|
|
addEventListener('load', () => {
|
2018-11-20 11:57:03 +01:00
|
|
|
const { href, handleRemote } = Rails;
|
2018-08-09 11:53:59 +02:00
|
|
|
Rails.href = function(element) {
|
2018-07-12 11:50:47 +02:00
|
|
|
return element.href || href(element);
|
|
|
|
};
|
2018-11-20 11:57:03 +01:00
|
|
|
Rails.handleRemote = function(e) {
|
|
|
|
if (this instanceof HTMLElement) {
|
|
|
|
handleRemote.call(this, e);
|
|
|
|
} else {
|
|
|
|
let element = e.find('[data-remote]')[0];
|
|
|
|
let event = new CustomEvent('click');
|
|
|
|
Object.defineProperty(event, 'target', { value: element });
|
|
|
|
return handleRemote.call(element, event);
|
|
|
|
}
|
|
|
|
};
|
2018-07-12 11:50:47 +02:00
|
|
|
});
|
2018-08-21 11:31:42 +02:00
|
|
|
|
|
|
|
// rails-ujs installs CSRFProtection for its own ajax implementation. We might need
|
|
|
|
// CSRFProtection for jQuery initiated requests. This code is from jquery-ujs.
|
|
|
|
jQuery.ajaxPrefilter((options, originalOptions, xhr) => {
|
|
|
|
if (!options.crossDomain) {
|
|
|
|
CSRFProtection(xhr);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
function csrfToken() {
|
|
|
|
return jQuery('meta[name=csrf-token]').attr('content');
|
|
|
|
}
|
|
|
|
|
|
|
|
function CSRFProtection(xhr) {
|
|
|
|
let token = csrfToken();
|
|
|
|
if (token) {
|
|
|
|
xhr.setRequestHeader('X-CSRF-Token', token);
|
|
|
|
}
|
|
|
|
}
|