summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/protected_branch_select.js.es6
blob: e4881eea222b094b90da405d6cb9b71f806e0217 (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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class ProtectedBranchDropdown {
  constructor(options) {
    this.onSelect = options.onSelect;
    this.$dropdown = options.$dropdown;
    this.$dropdownContainer = this.$dropdown.parent();
    this.$dropdownFooter = this.$dropdownContainer.find('.dropdown-footer');
    this.$protectedBranch = this.$dropdownContainer.find('.create-new-protected-branch');

    this.buildDropdown();
    this.bindEvents();

    // Hide footer
    this.$dropdownFooter.addClass('hidden');
  }

  buildDropdown() {
    this.$dropdown.glDropdown({
      data: this.getProtectedBranches.bind(this),
      filterable: true,
      remote: false,
      search: {
        fields: ['title']
      },
      selectable: true,
      toggleLabel(selected) {
        return (selected && 'id' in selected) ? selected.title : 'Protected Branch';
      },
      fieldName: 'protected_branch[name]',
      text(protected_branch) {
        return _.escape(protected_branch.title);
      },
      id(protected_branch) {
        return _.escape(protected_branch.id);
      },
      onFilter: this.toggleCreateNewButton.bind(this),
      clicked: (item, $el, e) => {
        e.preventDefault();
        this.onSelect();
      }
    });
  }

  bindEvents() {
    this.$protectedBranch.on('click', this.onClickCreateWildcard.bind(this));
  }

  onClickCreateWildcard() {
    this.$dropdown.data('glDropdown').remote.execute();
    this.$dropdown.data('glDropdown').selectRowAtIndex(0);
  }

  getProtectedBranches(term, callback) {
    if (this.selectedBranch) {
      callback(gon.open_branches.concat(this.selectedBranch));
    } else {
      callback(gon.open_branches);
    }
  }

  toggleCreateNewButton(branchName) {
    this.selectedBranch = {
      title: branchName,
      id: branchName,
      text: branchName
    };

    if (branchName) {
      this.$dropdownContainer
        .find('.create-new-protected-branch')
        .html(`Create wildcard <code>${branchName}</code>`);
    }

    this.$dropdownFooter.toggleClass('hidden', !branchName);
  }
}

class ProtectedBranchDropdowns {
  constructor(options) {
    const { $dropdowns, onSelect } = options;

    $dropdowns.each((i, el) => {
      new ProtectedBranchDropdown({
        $dropdown: $(el),
        onSelect: onSelect
      });
    });
  }
 }