summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/pipeline_schedules/setup_pipeline_variable_list.js
blob: 644efd10509b081e21a8d6451f54d2c0e44fb8f4 (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
65
66
67
68
69
70
71
function insertRow($row) {
  const $rowClone = $row.clone();
  $rowClone.removeAttr('data-is-persisted');
  $rowClone.find('input, textarea').val('');
  $row.after($rowClone);
}

function removeRow($row) {
  const isPersisted = gl.utils.convertPermissionToBoolean($row.attr('data-is-persisted'));

  if (isPersisted) {
    $row.hide();
    $row
      .find('.js-destroy-input')
      .val(1);
  } else {
    $row.remove();
  }
}

function checkIfRowTouched($row) {
  return $row.find('.js-user-input').toArray().some(el => $(el).val().length > 0);
}

function setupPipelineVariableList(parent = document) {
  const $parent = $(parent);

  $parent.on('click', '.js-row-remove-button', (e) => {
    const $row = $(e.currentTarget).closest('.js-row');
    removeRow($row);

    e.preventDefault();
  });

  // Remove any empty rows except the last r
  $parent.on('blur', '.js-user-input', (e) => {
    const $row = $(e.currentTarget).closest('.js-row');

    const isTouched = checkIfRowTouched($row);
    if ($row.is(':not(:last-child)') && !isTouched) {
      removeRow($row);
    }
  });

  // Always make sure there is an empty last row
  $parent.on('input', '.js-user-input', () => {
    const $lastRow = $parent.find('.js-row').last();

    const isTouched = checkIfRowTouched($lastRow);
    if (isTouched) {
      insertRow($lastRow);
    }
  });

  // Clear out the empty last row so it
  // doesn't get submitted and throw validation errors
  $parent.closest('form').on('submit', () => {
    const $lastRow = $parent.find('.js-row').last();

    const isTouched = checkIfRowTouched($lastRow);
    if (!isTouched) {
      $lastRow.find('input, textarea').attr('name', '');
    }
  });
}

export {
  setupPipelineVariableList,
  insertRow,
  removeRow,
};