import Api from './api'; import { normalizeCRLFHeaders } from './lib/utils/common_utils'; export default function groupsSelect() { // Needs to be accessible in rspec window.GROUP_SELECT_PER_PAGE = 20; $('.ajax-groups-select').each(function setAjaxGroupsSelect2() { const $select = $(this); const allAvailable = $select.data('all-available'); const skipGroups = $select.data('skip-groups') || []; $select.select2({ placeholder: 'Search for a group', multiple: $select.hasClass('multiselect'), minimumInputLength: 0, ajax: { url: Api.buildUrl(Api.groupsPath), dataType: 'json', quietMillis: 250, transport(params) { return $.ajax(params) .then((data, status, xhr) => { const results = data || []; const headers = normalizeCRLFHeaders(xhr.getAllResponseHeaders()); const currentPage = parseInt(headers['X-PAGE'], 10) || 0; const totalPages = parseInt(headers['X-TOTAL-PAGES'], 10) || 0; const more = currentPage < totalPages; return { results, pagination: { more, }, }; }) .then(params.success) .fail(params.error); }, data(search, page) { return { search, page, per_page: window.GROUP_SELECT_PER_PAGE, all_available: allAvailable, }; }, results(data, page) { if (data.length) return { results: [] }; const groups = data.length ? data : data.results || []; const more = data.pagination ? data.pagination.more : false; const results = groups.filter(group => skipGroups.indexOf(group.id) === -1); return { results, page, more, }; }, }, // eslint-disable-next-line consistent-return initSelection(element, callback) { const id = $(element).val(); if (id !== '') { return Api.group(id, callback); } }, formatResult(object) { return `