hydrate-form.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. import { materialIcon as createMaterialIcon } from '@/features/utils/material-icon'
  7. // Form helper(s) to handle:
  8. // - Attaching to the relevant form elements
  9. // - Listening for submit event
  10. // - Validating captcha
  11. // - Sending fetch request
  12. // - Redirect handling
  13. // - Showing errors
  14. // - Disabled state
  15. function formSubmitHelper(formEl) {
  16. formEl.addEventListener('submit', async e => {
  17. e.preventDefault()
  18. formEl.dispatchEvent(new Event('pending'))
  19. const messageBag = []
  20. try {
  21. let data
  22. try {
  23. const captchaResponse = await validateCaptcha(formEl)
  24. data = await sendFormRequest(formEl, captchaResponse)
  25. } catch (e) {
  26. if (
  27. e instanceof FetchError &&
  28. e.data?.errorReason === 'cannot_verify_user_not_robot'
  29. ) {
  30. // Trigger captcha unconditionally.
  31. const captchaResponse = await validateCaptchaV2()
  32. if (!captchaResponse) {
  33. throw e
  34. }
  35. data = await sendFormRequest(formEl, captchaResponse)
  36. } else {
  37. throw e
  38. }
  39. }
  40. formEl.dispatchEvent(new Event('sent'))
  41. // Handle redirects
  42. if (data.redir || data.redirect) {
  43. window.location = data.redir || data.redirect
  44. return
  45. }
  46. // Show a success message (e.g. used on 2FA page)
  47. if (data.message) {
  48. messageBag.push({
  49. type: 'message',
  50. text: data.message.text || data.message,
  51. })
  52. }
  53. // Handle reloads
  54. if (formEl.hasAttribute('data-ol-reload-on-success')) {
  55. window.setTimeout(window.location.reload.bind(window.location), 1000)
  56. return
  57. }
  58. // Let the user re-submit the form.
  59. formEl.dispatchEvent(new Event('idle'))
  60. } catch (error) {
  61. let text = error.message
  62. if (error instanceof FetchError) {
  63. text = error.getUserFacingMessage()
  64. }
  65. messageBag.push({
  66. type: 'error',
  67. key: error.data?.message?.key,
  68. text,
  69. hints: error.data?.message?.hints,
  70. })
  71. // Let the user re-submit the form.
  72. formEl.dispatchEvent(new Event('idle'))
  73. } finally {
  74. // call old and new notification builder functions
  75. // but only one will be rendered
  76. showMessages(formEl, messageBag)
  77. showMessagesNewStyle(formEl, messageBag)
  78. }
  79. })
  80. }
  81. async function validateCaptcha(formEl) {
  82. let captchaResponse
  83. if (
  84. formEl.hasAttribute('captcha') &&
  85. // Disable captcha for E2E tests in dev-env.
  86. !(process.env.NODE_ENV === 'development' && window.Cypress)
  87. ) {
  88. if (
  89. formEl.getAttribute('action') === '/login' &&
  90. (await canSkipCaptcha(new FormData(formEl).get('email')))
  91. ) {
  92. // The email is present in the deviceHistory, and we can skip the display
  93. // of a captcha challenge.
  94. // The actual login POST request will be checked against the deviceHistory
  95. // again and the server can trigger the display of a captcha if needed by
  96. // sending a 400 with errorReason set to 'cannot_verify_user_not_robot'.
  97. return ''
  98. }
  99. captchaResponse = await validateCaptchaV2()
  100. }
  101. return captchaResponse
  102. }
  103. async function sendFormRequest(formEl, captchaResponse) {
  104. const formData = new FormData(formEl)
  105. if (captchaResponse) {
  106. formData.set('g-recaptcha-response', captchaResponse)
  107. }
  108. const body = Object.fromEntries(
  109. Array.from(formData.keys(), key => {
  110. // forms may have multiple keys with the same name, eg: checkboxes
  111. const val = formData.getAll(key)
  112. return [key, val.length > 1 ? val : val.pop()]
  113. })
  114. )
  115. const url = formEl.getAttribute('action')
  116. return postJSON(url, { body })
  117. }
  118. function hideFormElements(formEl) {
  119. for (const e of formEl.elements) {
  120. e.hidden = true
  121. }
  122. }
  123. /**
  124. * Creates a notification element from a message object.
  125. *
  126. * @param {Object} message
  127. * @param {'error' | 'success' | 'warning' | 'info'} message.type
  128. * @param {string} message.key
  129. * @param {string} message.text
  130. * @param {string[]} message.hints
  131. * @returns {HTMLDivElement}
  132. */
  133. function createNotificationFromMessage(message) {
  134. const messageEl = document.createElement('div')
  135. messageEl.className = classNames('mb-3 notification', {
  136. 'notification-type-error': message.type === 'error',
  137. 'notification-type-success': message.type === 'success',
  138. 'notification-type-warning': message.type === 'warning',
  139. 'notification-type-info': message.type === 'info',
  140. })
  141. messageEl.setAttribute('aria-live', 'assertive')
  142. messageEl.setAttribute('role', message.type === 'error' ? 'alert' : 'status')
  143. const materialIcon = {
  144. info: 'info',
  145. success: 'check_circle',
  146. error: 'error',
  147. warning: 'warning',
  148. }[message.type]
  149. if (materialIcon) {
  150. const iconEl = document.createElement('div')
  151. iconEl.className = 'notification-icon'
  152. const iconSpan = createMaterialIcon(materialIcon)
  153. iconEl.append(iconSpan)
  154. messageEl.append(iconEl)
  155. }
  156. const contentAndCtaEl = document.createElement('div')
  157. contentAndCtaEl.className = 'notification-content-and-cta'
  158. const contentEl = document.createElement('div')
  159. contentEl.className = 'notification-content'
  160. contentEl.append(message.text || `Error: ${message.key}`)
  161. if (message.hints && message.hints.length) {
  162. const listEl = document.createElement('ul')
  163. message.hints.forEach(hint => {
  164. const listItemEl = document.createElement('li')
  165. listItemEl.textContent = hint
  166. listEl.append(listItemEl)
  167. })
  168. contentEl.append(listEl)
  169. }
  170. contentAndCtaEl.append(contentEl)
  171. messageEl.append(contentAndCtaEl)
  172. return messageEl
  173. }
  174. // TODO: remove the showMessages function after every form alerts are updated to use the new style
  175. // TODO: rename showMessagesNewStyle to showMessages after the above is done
  176. function showMessages(formEl, messageBag) {
  177. const messagesEl = formEl.querySelector('[data-ol-form-messages]')
  178. if (!messagesEl) return
  179. // Clear content
  180. messagesEl.textContent = ''
  181. formEl.querySelectorAll('[data-ol-custom-form-message]').forEach(el => {
  182. el.hidden = true
  183. })
  184. // Render messages
  185. messageBag.forEach(message => {
  186. const customErrorElements = message.key
  187. ? formEl.querySelectorAll(
  188. `[data-ol-custom-form-message="${message.key}"]`
  189. )
  190. : []
  191. if (message.key && customErrorElements.length > 0) {
  192. // Found at least one custom error element for key, show them
  193. customErrorElements.forEach(el => {
  194. el.hidden = false
  195. })
  196. } else {
  197. const notification = createNotificationFromMessage(message)
  198. messagesEl.append(notification)
  199. }
  200. if (message.key) {
  201. // Hide the form elements on specific message types
  202. const hideOnError = formEl.attributes['data-ol-hide-on-error']
  203. if (
  204. hideOnError &&
  205. hideOnError.value &&
  206. hideOnError.value.match(message.key)
  207. ) {
  208. hideFormElements(formEl)
  209. }
  210. // Hide any elements with specific `data-ol-hide-on-error-message` message
  211. document
  212. .querySelectorAll(`[data-ol-hide-on-error-message="${message.key}"]`)
  213. .forEach(el => {
  214. el.hidden = true
  215. })
  216. }
  217. })
  218. }
  219. function showMessagesNewStyle(formEl, messageBag) {
  220. const messagesEl = formEl.querySelector('[data-ol-form-messages-new-style]')
  221. if (!messagesEl) return
  222. // Clear content
  223. messagesEl.textContent = ''
  224. formEl.querySelectorAll('[data-ol-custom-form-message]').forEach(el => {
  225. el.hidden = true
  226. })
  227. // Render messages
  228. messageBag.forEach(message => {
  229. const customErrorElements = message.key
  230. ? formEl.querySelectorAll(
  231. `[data-ol-custom-form-message="${message.key}"]`
  232. )
  233. : []
  234. if (message.key && customErrorElements.length > 0) {
  235. // Found at least one custom error element for key, show them
  236. customErrorElements.forEach(el => {
  237. el.hidden = false
  238. })
  239. } else {
  240. // No custom error element for key on page, append a new error message
  241. const messageElContainer = document.createElement('div')
  242. messageElContainer.className = classNames('notification', {
  243. 'notification-type-error': message.type === 'error',
  244. 'notification-type-success': message.type !== 'error',
  245. })
  246. const messageEl = document.createElement('div')
  247. // create the message text
  248. messageEl.className = 'notification-content text-left'
  249. messageEl.textContent = message.text || `Error: ${message.key}`
  250. messageEl.setAttribute('aria-live', 'assertive')
  251. messageEl.setAttribute(
  252. 'role',
  253. message.type === 'error' ? 'alert' : 'status'
  254. )
  255. if (message.hints && message.hints.length) {
  256. const listEl = document.createElement('ul')
  257. message.hints.forEach(hint => {
  258. const listItemEl = document.createElement('li')
  259. listItemEl.textContent = hint
  260. listEl.append(listItemEl)
  261. })
  262. messageEl.append(listEl)
  263. }
  264. // create the left icon
  265. const icon = createMaterialIcon(
  266. message.type === 'error' ? 'error' : 'check_circle'
  267. )
  268. const messageIcon = document.createElement('div')
  269. messageIcon.className = 'notification-icon'
  270. messageIcon.appendChild(icon)
  271. // append icon first so it's on the left
  272. messageElContainer.appendChild(messageIcon)
  273. messageElContainer.appendChild(messageEl)
  274. messagesEl.append(messageElContainer)
  275. }
  276. if (message.key) {
  277. // Hide the form elements on specific message types
  278. const hideOnError = formEl.attributes['data-ol-hide-on-error']
  279. if (
  280. hideOnError &&
  281. hideOnError.value &&
  282. hideOnError.value.match(message.key)
  283. ) {
  284. hideFormElements(formEl)
  285. }
  286. // Hide any elements with specific `data-ol-hide-on-error-message` message
  287. document
  288. .querySelectorAll(`[data-ol-hide-on-error-message="${message.key}"]`)
  289. .forEach(el => {
  290. el.hidden = true
  291. })
  292. }
  293. })
  294. }
  295. export function inflightHelper(el) {
  296. const disabledInflight = el.querySelectorAll('[data-ol-disabled-inflight]')
  297. const showWhenNotInflight = el.querySelectorAll('[data-ol-inflight="idle"]')
  298. const showWhenInflight = el.querySelectorAll('[data-ol-inflight="pending"]')
  299. el.addEventListener('pending', () => {
  300. disabledInflight.forEach(disableElement)
  301. toggleDisplay(showWhenNotInflight, showWhenInflight)
  302. })
  303. el.addEventListener('idle', () => {
  304. disabledInflight.forEach(enableElement)
  305. toggleDisplay(showWhenInflight, showWhenNotInflight)
  306. })
  307. }
  308. function formSentHelper(el) {
  309. const showWhenPending = el.querySelectorAll('[data-ol-not-sent]')
  310. const showWhenDone = el.querySelectorAll('[data-ol-sent]')
  311. if (showWhenDone.length === 0) return
  312. el.addEventListener('sent', () => {
  313. toggleDisplay(showWhenPending, showWhenDone)
  314. })
  315. }
  316. function formValidationHelper(el) {
  317. el.querySelectorAll('input, textarea').forEach(inputEl => {
  318. if (
  319. inputEl.willValidate &&
  320. !inputEl.hasAttribute('data-ol-no-custom-form-validation-messages')
  321. ) {
  322. inputValidator(inputEl)
  323. }
  324. })
  325. }
  326. function formAutoSubmitHelper(el) {
  327. if (el.hasAttribute('data-ol-auto-submit')) {
  328. setTimeout(() => {
  329. el.querySelector('[type="submit"]').click()
  330. }, 0)
  331. }
  332. }
  333. export function toggleDisplay(hide, show) {
  334. hide.forEach(el => {
  335. el.hidden = true
  336. })
  337. show.forEach(el => {
  338. el.hidden = false
  339. })
  340. }
  341. function hydrateAsyncForm(el) {
  342. formSubmitHelper(el)
  343. inflightHelper(el)
  344. formSentHelper(el)
  345. formValidationHelper(el)
  346. formAutoSubmitHelper(el)
  347. }
  348. function hydrateRegularForm(el) {
  349. inflightHelper(el)
  350. formValidationHelper(el)
  351. el.addEventListener('submit', () => {
  352. el.dispatchEvent(new Event('pending'))
  353. })
  354. formAutoSubmitHelper(el)
  355. }
  356. document.querySelectorAll(`[data-ol-async-form]`).forEach(hydrateAsyncForm)
  357. document.querySelectorAll(`[data-ol-regular-form]`).forEach(hydrateRegularForm)