Welcome to mirror list, hosted at ThFree Co, Russian Federation.

rails_ujs.js « utils « lib « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6b1985a23baa4ac6ffb52208fdd1ffffd7fe8e3b (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
import Rails from '@rails/ujs';
import { confirmViaGlModal } from './confirm_via_gl_modal/confirm_via_gl_modal';

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}
   */
  function confirmViaModal(message, element) {
    confirmViaGlModal(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 };