gitlab-org--gitlab-foss/app/assets/javascripts/pages/search/show/search.js

114 lines
2.7 KiB
JavaScript
Raw Normal View History

2018-01-10 13:32:29 -05:00
import Flash from '~/flash';
import Api from '~/api';
2017-12-13 04:26:44 -05:00
export default class Search {
constructor() {
const $groupDropdown = $('.js-search-group-dropdown');
const $projectDropdown = $('.js-search-project-dropdown');
this.searchInput = '.js-search-input';
this.searchClear = '.js-search-clear';
this.groupId = $groupDropdown.data('group-id');
this.eventListeners();
$groupDropdown.glDropdown({
selectable: true,
filterable: true,
fieldName: 'group_id',
search: {
fields: ['full_name'],
},
data(term, callback) {
return Api.groups(term, {}, (data) => {
data.unshift({
full_name: 'Any',
});
data.splice(1, 0, 'divider');
return callback(data);
});
},
id(obj) {
return obj.id;
},
text(obj) {
return obj.full_name;
},
toggleLabel(obj) {
return `${($groupDropdown.data('default-label'))} ${obj.full_name}`;
},
clicked: () => Search.submitSearch(),
});
$projectDropdown.glDropdown({
selectable: true,
filterable: true,
fieldName: 'project_id',
search: {
fields: ['name'],
},
data: (term, callback) => {
this.getProjectsData(term)
.then((data) => {
2016-07-24 16:45:11 -04:00
data.unshift({
2017-12-13 04:26:44 -05:00
name_with_namespace: 'Any',
2016-07-24 16:45:11 -04:00
});
data.splice(1, 0, 'divider');
2017-12-13 04:26:44 -05:00
return data;
})
.then(data => callback(data))
.catch(() => new Flash('Error fetching projects'));
},
id(obj) {
return obj.id;
},
text(obj) {
return obj.name_with_namespace;
},
toggleLabel(obj) {
return `${($projectDropdown.data('default-label'))} ${obj.name_with_namespace}`;
},
clicked: () => Search.submitSearch(),
});
}
2016-07-24 16:45:11 -04:00
2017-12-13 04:26:44 -05:00
eventListeners() {
$(document)
.off('keyup', this.searchInput)
.on('keyup', this.searchInput, this.searchKeyUp);
$(document)
.off('click', this.searchClear)
.on('click', this.searchClear, this.clearSearchField.bind(this));
}
2016-07-24 16:45:11 -04:00
2017-12-13 04:26:44 -05:00
static submitSearch() {
return $('.js-search-form').submit();
}
2016-07-24 16:45:11 -04:00
2017-12-13 04:26:44 -05:00
searchKeyUp() {
const $input = $(this);
if ($input.val() === '') {
$('.js-search-clear').addClass('hidden');
} else {
$('.js-search-clear').removeClass('hidden');
}
}
2016-07-24 16:45:11 -04:00
2017-12-13 04:26:44 -05:00
clearSearchField() {
return $(this.searchInput).val('').trigger('keyup').focus();
}
2017-12-13 04:26:44 -05:00
getProjectsData(term) {
return new Promise((resolve) => {
if (this.groupId) {
Api.groupProjects(this.groupId, term, resolve);
} else {
Api.projects(term, {
order_by: 'id',
}, resolve);
}
});
}
}