diff --git a/app/javascript/shared/utils.js b/app/javascript/shared/utils.js index 9339dd07f..8270f4d70 100644 --- a/app/javascript/shared/utils.js +++ b/app/javascript/shared/utils.js @@ -1,3 +1,10 @@ +import Rails from 'rails-ujs'; +import $ from 'jquery'; +import debounce from 'debounce'; + +export { debounce }; +export const { fire } = Rails; + export function show({ classList }) { classList.remove('hidden'); } @@ -9,3 +16,40 @@ export function hide({ classList }) { export function toggle({ classList }) { classList.toggle('hidden'); } + +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) { + $(container).scrollTop( + $(scrollTo).offset().top - + $(container).offset().top + + $(container).scrollTop() + ); +} + +export function scrollToBottom(container) { + $(container).scrollTop(container.scrollHeight); +} + +export function on(selector, eventName, fn) { + [...document.querySelectorAll(selector)].forEach(element => + element.addEventListener(eventName, event => fn(event, event.detail)) + ); +} diff --git a/config/webpack/environment.js b/config/webpack/environment.js index d261e8336..6016319bc 100644 --- a/config/webpack/environment.js +++ b/config/webpack/environment.js @@ -1,3 +1,4 @@ +const path = require('path'); const { environment } = require('@rails/webpacker'); // By default don't transpile JS files in ./node_modules – except for some specific modules. @@ -14,4 +15,12 @@ babelLoader.exclude = function(modulePath) { ); }; +const resolve = { + alias: { + '@utils': path.resolve(__dirname, '..', '..', 'app/javascript/shared/utils') + } +}; + +environment.config.merge({ resolve }); + module.exports = environment;