gitlab-org--gitlab-foss/app/assets/javascripts/protected_branches/protected_branch_dropdown.js

91 lines
2.4 KiB
JavaScript
Raw Normal View History

import _ from 'underscore';
2017-07-19 12:44:34 +00:00
export default class ProtectedBranchDropdown {
/**
* @param {Object} options containing
* `$dropdown` target element
* `onSelect` event callback
* $dropdown must be an element created using `dropdown_branch()` rails helper
*/
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('.js-create-new-protected-branch');
this.buildDropdown();
this.bindEvents();
// Hide footer
2017-07-19 12:44:34 +00:00
this.toggleFooter(true);
}
buildDropdown() {
this.$dropdown.glDropdown({
data: this.getProtectedBranches.bind(this),
filterable: true,
remote: false,
search: {
2017-07-19 12:44:34 +00:00
fields: ['title'],
},
selectable: true,
toggleLabel(selected) {
return (selected && 'id' in selected) ? selected.title : 'Protected Branch';
},
fieldName: 'protected_branch[name]',
2016-08-05 07:02:34 +00:00
text(protectedBranch) {
return _.escape(protectedBranch.title);
},
2016-08-05 07:02:34 +00:00
id(protectedBranch) {
return _.escape(protectedBranch.id);
},
onFilter: this.toggleCreateNewButton.bind(this),
clicked: (options) => {
2017-07-19 12:44:34 +00:00
options.e.preventDefault();
this.onSelect();
2017-07-19 12:44:34 +00:00
},
});
}
bindEvents() {
this.$protectedBranch.on('click', this.onClickCreateWildcard.bind(this));
}
onClickCreateWildcard(e) {
e.preventDefault();
// Refresh the dropdown's data, which ends up calling `getProtectedBranches`
this.$dropdown.data('glDropdown').remote.execute();
2016-11-21 17:45:27 +00:00
this.$dropdown.data('glDropdown').selectRowAtIndex();
}
getProtectedBranches(term, callback) {
if (this.selectedBranch) {
callback(gon.open_branches.concat(this.selectedBranch));
} else {
callback(gon.open_branches);
}
}
toggleCreateNewButton(branchName) {
if (branchName) {
2017-07-19 12:44:34 +00:00
this.selectedBranch = {
title: branchName,
id: branchName,
text: branchName,
};
this.$dropdownContainer
.find('.js-create-new-protected-branch code')
.text(branchName);
}
2017-07-19 12:44:34 +00:00
this.toggleFooter(!branchName);
}
2017-07-19 12:44:34 +00:00
toggleFooter(toggleState) {
this.$dropdownFooter.toggleClass('hidden', toggleState);
}
}