hydrate-form.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import classNames from 'classnames'
  2. import { FetchError, postJSON } from '../../infrastructure/fetch-json'
  3. import { canSkipCaptcha, validateCaptchaV2 } from './captcha'
  4. import inputValidator from './input-validator'
  5. import { disableElement, enableElement } from '../utils/disableElement'
  6. // Form helper(s) to handle:
  7. // - Attaching to the relevant form elements
  8. // - Listening for submit event
  9. // - Validating captcha
  10. // - Sending fetch request
  11. // - Redirect handling
  12. // - Showing errors
  13. // - Disabled state
  14. function formSubmitHelper(formEl) {
  15. formEl.addEventListener('submit', async e => {
  16. e.preventDefault()
  17. formEl.dispatchEvent(new Event('pending'))
  18. const messageBag = []
  19. try {
  20. let data
  21. try {
  22. const captchaResponse = await validateCaptcha(formEl)
  23. data = await sendFormRequest(formEl, captchaResponse)
  24. } catch (e) {
  25. if (
  26. e instanceof FetchError &&
  27. e.data?.errorReason === 'cannot_verify_user_not_robot'
  28. ) {
  29. // Trigger captcha unconditionally.
  30. const captchaResponse = await validateCaptchaV2()
  31. if (!captchaResponse) {
  32. throw e
  33. }
  34. data = await sendFormRequest(formEl, captchaResponse)
  35. } else {
  36. throw e
  37. }
  38. }
  39. formEl.dispatchEvent(new Event('sent'))
  40. // Handle redirects
  41. if (data.redir) {
  42. window.location = data.redir
  43. return
  44. }
  45. // Show a success message (e.g. used on 2FA page)
  46. if (data.message) {
  47. messageBag.push({
  48. type: 'message',
  49. text: data.message.text || data.message,
  50. })
  51. }
  52. // Handle reloads
  53. if (formEl.hasAttribute('data-ol-reload-on-success')) {
  54. window.setTimeout(window.location.reload.bind(window.location), 1000)
  55. return
  56. }
  57. // Let the user re-submit the form.
  58. formEl.dispatchEvent(new Event('idle'))
  59. } catch (error) {
  60. let text = error.message
  61. if (error instanceof FetchError) {
  62. text = error.getUserFacingMessage()
  63. }
  64. messageBag.push({
  65. type: 'error',
  66. key: error.data?.message?.key,
  67. text,
  68. })
  69. // Let the user re-submit the form.
  70. formEl.dispatchEvent(new Event('idle'))
  71. } finally {
  72. showMessages(formEl, messageBag)
  73. }
  74. })
  75. }
  76. async function validateCaptcha(formEl) {
  77. let captchaResponse
  78. if (formEl.hasAttribute('captcha')) {
  79. if (
  80. formEl.getAttribute('action') === '/login' &&
  81. (await canSkipCaptcha(new FormData(formEl).get('email')))
  82. ) {
  83. // The email is present in the deviceHistory, and we can skip the display
  84. // of a captcha challenge.
  85. // The actual login POST request will be checked against the deviceHistory
  86. // again and the server can trigger the display of a captcha if needed by
  87. // sending a 400 with errorReason set to 'cannot_verify_user_not_robot'.
  88. return ''
  89. }
  90. captchaResponse = await validateCaptchaV2()
  91. }
  92. return captchaResponse
  93. }
  94. async function sendFormRequest(formEl, captchaResponse) {
  95. const formData = new FormData(formEl)
  96. if (captchaResponse) {
  97. formData.set('g-recaptcha-response', captchaResponse)
  98. }
  99. const body = Object.fromEntries(formData.entries())
  100. const url = formEl.getAttribute('action')
  101. return postJSON(url, { body })
  102. }
  103. function showMessages(formEl, messageBag) {
  104. const messagesEl = formEl.querySelector('[data-ol-form-messages]')
  105. if (!messagesEl) return
  106. // Clear content
  107. messagesEl.textContent = ''
  108. formEl.querySelectorAll('[data-ol-custom-form-message]').forEach(el => {
  109. el.hidden = true
  110. })
  111. // Render messages
  112. messageBag.forEach(message => {
  113. if (message.key) {
  114. formEl
  115. .querySelectorAll(`[data-ol-custom-form-message="${message.key}"]`)
  116. .forEach(el => {
  117. el.hidden = false
  118. })
  119. return
  120. }
  121. const messageEl = document.createElement('div')
  122. messageEl.className = classNames('alert', {
  123. 'alert-danger': message.type === 'error',
  124. 'alert-success': message.type !== 'error',
  125. })
  126. messageEl.textContent = message.text
  127. messageEl.setAttribute('aria-live', 'assertive')
  128. messageEl.setAttribute(
  129. 'role',
  130. message.type === 'error' ? 'alert' : 'status'
  131. )
  132. messagesEl.append(messageEl)
  133. })
  134. }
  135. export function inflightHelper(el) {
  136. const disabledInflight = el.querySelectorAll('[data-ol-disabled-inflight]')
  137. const showWhenNotInflight = el.querySelectorAll('[data-ol-inflight="idle"]')
  138. const showWhenInflight = el.querySelectorAll('[data-ol-inflight="pending"]')
  139. el.addEventListener('pending', () => {
  140. disabledInflight.forEach(disableElement)
  141. toggleDisplay(showWhenNotInflight, showWhenInflight)
  142. })
  143. el.addEventListener('idle', () => {
  144. disabledInflight.forEach(enableElement)
  145. toggleDisplay(showWhenInflight, showWhenNotInflight)
  146. })
  147. }
  148. function formSentHelper(el) {
  149. const showWhenPending = el.querySelectorAll('[data-ol-not-sent]')
  150. const showWhenDone = el.querySelectorAll('[data-ol-sent]')
  151. if (showWhenDone.length === 0) return
  152. el.addEventListener('sent', () => {
  153. toggleDisplay(showWhenPending, showWhenDone)
  154. })
  155. }
  156. function formValidationHelper(el) {
  157. el.querySelectorAll('input').forEach(inputEl => {
  158. if (
  159. inputEl.willValidate &&
  160. !inputEl.hasAttribute('data-ol-no-custom-form-validation-messages')
  161. ) {
  162. inputValidator(inputEl)
  163. }
  164. })
  165. }
  166. function formAutoSubmitHelper(el) {
  167. if (el.hasAttribute('data-ol-auto-submit')) {
  168. setTimeout(() => {
  169. el.querySelector('[type="submit"]').click()
  170. }, 0)
  171. }
  172. }
  173. export function toggleDisplay(hide, show) {
  174. hide.forEach(el => {
  175. el.hidden = true
  176. })
  177. show.forEach(el => {
  178. el.hidden = false
  179. })
  180. }
  181. function hydrateAsyncForm(el) {
  182. formSubmitHelper(el)
  183. inflightHelper(el)
  184. formSentHelper(el)
  185. formValidationHelper(el)
  186. formAutoSubmitHelper(el)
  187. }
  188. function hydrateRegularForm(el) {
  189. inflightHelper(el)
  190. formValidationHelper(el)
  191. el.addEventListener('submit', () => {
  192. el.dispatchEvent(new Event('pending'))
  193. })
  194. formAutoSubmitHelper(el)
  195. }
  196. document.querySelectorAll(`[data-ol-async-form]`).forEach(hydrateAsyncForm)
  197. document.querySelectorAll(`[data-ol-regular-form]`).forEach(hydrateRegularForm)