summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/confirm_danger_modal.js
blob: ad70d9be16fad2968fbb886d953e11fab0c80682 (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
62
63
64
import $ from 'jquery';
import { Rails } from '~/lib/utils/rails_ujs';
import { rstrip } from './lib/utils/common_utils';

function openConfirmDangerModal($form, $modal, text) {
  const $input = $('.js-legacy-confirm-danger-input', $modal);
  $input.val('');

  $('.js-confirm-text', $modal).text(text || '');
  $modal.modal('show');

  const confirmTextMatch = $('.js-legacy-confirm-danger-match', $modal).text();
  const $submit = $('.js-legacy-confirm-danger-submit', $modal);
  $submit.disable();
  $input.focus();

  // eslint-disable-next-line @gitlab/no-global-event-off
  $input.off('input').on('input', function handleInput() {
    const confirmText = rstrip($(this).val());
    if (confirmText === confirmTextMatch) {
      $submit.enable();
    } else {
      $submit.disable();
    }
  });

  // eslint-disable-next-line @gitlab/no-global-event-off
  $('.js-legacy-confirm-danger-submit', $modal)
    .off('click')
    .on('click', () => {
      if ($form.data('remote')) {
        Rails.fire($form[0], 'submit');
      } else {
        $form.submit();
      }
    });
}

function getModal($btn) {
  const $modal = $btn.prev('.modal');

  if ($modal.length) {
    return $modal;
  }

  return $('#modal-confirm-danger');
}

export default function initConfirmDangerModal() {
  $(document).on('click', '.js-legacy-confirm-danger', (e) => {
    const $btn = $(e.target);
    const checkFieldName = $btn.data('checkFieldName');
    const checkFieldCompareValue = $btn.data('checkCompareValue');
    const checkFieldVal = parseInt($(`[name="${checkFieldName}"]`).val(), 10);

    if (!checkFieldName || checkFieldVal < checkFieldCompareValue) {
      e.preventDefault();
      const $form = $btn.closest('form');
      const $modal = getModal($btn);
      const text = $btn.data('confirmDangerMessage');
      openConfirmDangerModal($form, $modal, text);
    }
  });
}