Utils.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * A collection of small utility functions that help with dom manipulation, adding listeners,
  3. * promises and other good things.
  4. *
  5. * @module Utils
  6. */
  7. /**
  8. * Runs a waterfall of promises: calls each task, passing the result
  9. * from the previous one as an argument. The first task is run with an empty array.
  10. *
  11. * @memberof Utils
  12. * @param {array} methods of Promises to run waterfall on
  13. * @return {Promise} of the final task
  14. */
  15. function promiseWaterfall (methods) {
  16. const [resolvedPromise, ...tasks] = methods
  17. const finalTaskPromise = tasks.reduce((prevTaskPromise, task) => {
  18. return prevTaskPromise.then(task)
  19. }, resolvedPromise([])) // initial value
  20. return finalTaskPromise
  21. }
  22. /**
  23. * Adds multiple listeners to to a DOM element
  24. * Equvalent to jQuery’s `$form.on('drag dragstart dragend dragover dragenter dragleave drop')`.
  25. *
  26. * @memberof Utils
  27. * @param {String} el selector
  28. * @param {String} events to add, like `drag dragstart dragend dragover dragenter dragleave drop`
  29. * @param {requestCallback} cb
  30. * @return {String}
  31. */
  32. function addListenerMulti (el, events, cb) {
  33. const eventsArray = events.split(' ')
  34. for (let event in eventsArray) {
  35. el.addEventListener(eventsArray[event], cb, false)
  36. }
  37. }
  38. /**
  39. * Shallow flatten nested arrays.
  40. */
  41. function flatten (arr) {
  42. return [].concat.apply([], arr)
  43. }
  44. function qsa (selector, context) {
  45. return Array.prototype.slice.call((context || document).querySelectorAll(selector) || [])
  46. }
  47. export default {
  48. promiseWaterfall,
  49. // toggleClass,
  50. // addClass,
  51. // removeClass,
  52. addListenerMulti,
  53. flatten,
  54. qsa
  55. }