utils.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Thanks @stimulus:
  2. // https://github.com/stimulusjs/stimulus/blob/master/packages/%40stimulus/core/src/application.ts
  3. export function domReady() {
  4. return new Promise(resolve => {
  5. if (document.readyState == "loading") {
  6. document.addEventListener("DOMContentLoaded", resolve)
  7. } else {
  8. resolve()
  9. }
  10. })
  11. }
  12. export function isTesting() {
  13. return process.env.JEST_WORKER_ID !== undefined;
  14. }
  15. export function walk(el, callback) {
  16. callback(el)
  17. let node = el.firstElementChild
  18. while (node) {
  19. walk(node, callback)
  20. node = node.nextElementSibling
  21. }
  22. }
  23. export function debounce(func, wait, immediate) {
  24. var timeout;
  25. return function () {
  26. var context = this, args = arguments;
  27. var later = function () {
  28. timeout = null;
  29. if (!immediate) func.apply(context, args);
  30. };
  31. var callNow = immediate && !timeout;
  32. clearTimeout(timeout);
  33. timeout = setTimeout(later, wait);
  34. if (callNow) func.apply(context, args);
  35. };
  36. };
  37. export function onlyUnique(value, index, self) {
  38. return self.indexOf(value) === index;
  39. }
  40. export function saferEval(expression, dataContext, additionalHelperVariables = {}) {
  41. return (new Function(['$data', ...Object.keys(additionalHelperVariables)], `var result; with($data) { result = ${expression} }; return result`))(
  42. dataContext, ...Object.values(additionalHelperVariables)
  43. )
  44. }
  45. export function saferEvalNoReturn(expression, dataContext, additionalHelperVariables = {}) {
  46. return (new Function(['$data', ...Object.keys(additionalHelperVariables)], `with($data) { ${expression} }`))(
  47. dataContext, ...Object.values(additionalHelperVariables)
  48. )
  49. }
  50. export function isXAttr(attr) {
  51. const xAttrRE = /x-(on|bind|data|text|model)/
  52. return xAttrRE.test(attr.name)
  53. }
  54. export function getXAttrs(el, type) {
  55. return Array.from(el.attributes)
  56. .filter(isXAttr)
  57. .map(attr => {
  58. const typeMatch = attr.name.match(/x-(on|bind|data|text|model)/)
  59. const valueMatch = attr.name.match(/:([a-zA-Z\-]+)/)
  60. const modifiers = attr.name.match(/\.[^.\]]+(?=[^\]]*$)/g) || []
  61. return {
  62. type: typeMatch ? typeMatch[1] : null,
  63. value: valueMatch ? valueMatch[1] : null,
  64. modifiers: modifiers.map(i => i.replace('.', '')),
  65. expression: attr.value,
  66. }
  67. })
  68. .filter(i => {
  69. // If no type is passed in for filtering, bypassfilter
  70. if (! type) return true
  71. return i.type === name
  72. })
  73. }