utils.js 5.4 KB

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