utils.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 navigator.userAgent, navigator.userAgent.includes("Node.js")
  14. || navigator.userAgent.includes("jsdom")
  15. }
  16. export function kebabCase(subject) {
  17. return subject.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/[_\s]/, '-').toLowerCase()
  18. }
  19. export function walkSkippingNestedComponents(el, callback, isRoot = true) {
  20. if (el.hasAttribute('x-data') && ! isRoot) return
  21. callback(el)
  22. let node = el.firstElementChild
  23. while (node) {
  24. walkSkippingNestedComponents(node, callback, false)
  25. node = node.nextElementSibling
  26. }
  27. }
  28. export function debounce(func, wait, immediate) {
  29. var timeout;
  30. return function () {
  31. var context = this, args = arguments;
  32. var later = function () {
  33. timeout = null;
  34. if (!immediate) func.apply(context, args);
  35. };
  36. var callNow = immediate && !timeout;
  37. clearTimeout(timeout);
  38. timeout = setTimeout(later, wait);
  39. if (callNow) func.apply(context, args);
  40. };
  41. };
  42. export function onlyUnique(value, index, self) {
  43. return self.indexOf(value) === index;
  44. }
  45. export function saferEval(expression, dataContext, additionalHelperVariables = {}) {
  46. return (new Function(['$data', ...Object.keys(additionalHelperVariables)], `var result; with($data) { result = ${expression} }; return result`))(
  47. dataContext, ...Object.values(additionalHelperVariables)
  48. )
  49. }
  50. export function saferEvalNoReturn(expression, dataContext, additionalHelperVariables = {}) {
  51. return (new Function(['$data', ...Object.keys(additionalHelperVariables)], `with($data) { ${expression} }`))(
  52. dataContext, ...Object.values(additionalHelperVariables)
  53. )
  54. }
  55. export function isXAttr(attr) {
  56. const xAttrRE = /x-(on|bind|data|text|html|model|if|show|cloak|transition|ref)/
  57. return xAttrRE.test(attr.name)
  58. }
  59. export function getXAttrs(el, type) {
  60. return Array.from(el.attributes)
  61. .filter(isXAttr)
  62. .map(attr => {
  63. const typeMatch = attr.name.match(/x-(on|bind|data|text|html|model|if|show|cloak|transition|ref)/)
  64. const valueMatch = attr.name.match(/:([a-zA-Z\-]+)/)
  65. const modifiers = attr.name.match(/\.[^.\]]+(?=[^\]]*$)/g) || []
  66. return {
  67. type: typeMatch ? typeMatch[1] : null,
  68. value: valueMatch ? valueMatch[1] : null,
  69. modifiers: modifiers.map(i => i.replace('.', '')),
  70. expression: attr.value,
  71. }
  72. })
  73. .filter(i => {
  74. // If no type is passed in for filtering, bypassfilter
  75. if (! type) return true
  76. return i.type === type
  77. })
  78. }
  79. export function transitionIn(el, callback, forceSkip = false) {
  80. if (forceSkip) callback()
  81. const attrs = getXAttrs(el, 'transition')
  82. if (attrs.length < 1) callback()
  83. const enter = (attrs.find(i => i.value === 'enter') || { expression: '' }).expression.split(' ').filter(i => i !== '')
  84. const enterStart = (attrs.find(i => i.value === 'enter-start') || { expression: '' }).expression.split(' ').filter(i => i !== '')
  85. const enterEnd = (attrs.find(i => i.value === 'enter-end') || { expression: '' }).expression.split(' ').filter(i => i !== '')
  86. transition(el, enter, enterStart, enterEnd, callback, () => {})
  87. }
  88. export function transitionOut(el, callback, forceSkip = false) {
  89. if (forceSkip) callback()
  90. const attrs = getXAttrs(el, 'transition')
  91. if (attrs.length < 1) callback()
  92. const leave = (attrs.find(i => i.value === 'leave') || { expression: '' }).expression.split(' ').filter(i => i !== '')
  93. const leaveStart = (attrs.find(i => i.value === 'leave-start') || { expression: '' }).expression.split(' ').filter(i => i !== '')
  94. const leaveEnd = (attrs.find(i => i.value === 'leave-end') || { expression: '' }).expression.split(' ').filter(i => i !== '')
  95. transition(el, leave, leaveStart, leaveEnd, () => {}, callback)
  96. }
  97. export function transition(el, classesDuring, classesStart, classesEnd, hook1, hook2) {
  98. el.classList.add(...classesStart)
  99. el.classList.add(...classesDuring)
  100. requestAnimationFrame(() => {
  101. const duration = Number(getComputedStyle(el).transitionDuration.replace('s', '')) * 1000
  102. hook1()
  103. requestAnimationFrame(() => {
  104. el.classList.remove(...classesStart)
  105. el.classList.add(...classesEnd)
  106. setTimeout(() => {
  107. hook2()
  108. // Adding an "isConnected" check, in case the callback
  109. // removed the element from the DOM.
  110. if (el.isConnected) {
  111. el.classList.remove(...classesDuring)
  112. el.classList.remove(...classesEnd)
  113. }
  114. }, duration);
  115. })
  116. });
  117. }