summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/utils/rails_ujs.js
blob: b4f425da871d8cc381718b1e562dd2763a35d510 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import Rails from '@rails/ujs';
import { confirmViaGlModal } from './confirm_via_gl_modal/confirm_via_gl_modal';
import { ignoreWhilePending } from './ignore_while_pending';

function monkeyPatchConfirmModal() {
  /**
   * This function is used to replace the `Rails.confirm` which uses `window.confirm`
   *
   * This function opens a confirmation modal which will resolve in a promise.
   * Because the `Rails.confirm` API is synchronous, we go with a little hack here:
   *
   * 1. User clicks on something with `data-confirm`
   * 2. We open the modal and return `false`, ending the "Rails" event chain
   * 3. If the modal is closed and the user "confirmed" the action
   *     1. replace the `Rails.confirm` with a function that always returns `true`
   *     2. click the same element programmatically
   *
   * @param message {String} Message to be shown in the modal
   * @param element {HTMLElement} Element that was clicked on
   * @returns {boolean}
   */
  const safeConfirm = ignoreWhilePending(confirmViaGlModal);

  function confirmViaModal(message, element) {
    safeConfirm(message, element)
      .then((confirmed) => {
        if (confirmed) {
          Rails.confirm = () => true;
          element.click();
          Rails.confirm = confirmViaModal;
        }
      })
      .catch(() => {});
    return false;
  }

  Rails.confirm = confirmViaModal;
}

if (gon?.features?.bootstrapConfirmationModals) {
  monkeyPatchConfirmModal();
}

export const initRails = () => {
  // eslint-disable-next-line no-underscore-dangle
  if (!window._rails_loaded) {
    Rails.start();

    // Count XHR requests for tests. See spec/support/helpers/wait_for_requests.rb
    window.pendingRailsUJSRequests = 0;
    document.body.addEventListener('ajax:complete', () => {
      window.pendingRailsUJSRequests -= 1;
    });

    document.body.addEventListener('ajax:beforeSend', () => {
      window.pendingRailsUJSRequests += 1;
    });
  }
};

export { Rails };