Commit 40a04bc7 authored by Tim Zallmann's avatar Tim Zallmann

Wraps Select 2 Import into its own webpack bundle

Wraps all imports for select 2 to deferred imports,
especially in the main.js we are actually checking if there 
is any select 2 element on the page or not.
parent 2bb0d089
...@@ -7,4 +7,3 @@ import 'vendor/jquery.caret'; ...@@ -7,4 +7,3 @@ import 'vendor/jquery.caret';
import 'vendor/jquery.atwho'; import 'vendor/jquery.atwho';
import 'vendor/jquery.scrollTo'; import 'vendor/jquery.scrollTo';
import 'jquery.waitforimages'; import 'jquery.waitforimages';
import 'select2/select2';
...@@ -4,93 +4,97 @@ import Api from './api'; ...@@ -4,93 +4,97 @@ import Api from './api';
import { normalizeHeaders } from './lib/utils/common_utils'; import { normalizeHeaders } from './lib/utils/common_utils';
export default function groupsSelect() { export default function groupsSelect() {
// Needs to be accessible in rspec import(/* webpackChunkName: 'select2' */ 'select2/select2')
window.GROUP_SELECT_PER_PAGE = 20; .then(() => {
$('.ajax-groups-select').each(function setAjaxGroupsSelect2() { // Needs to be accessible in rspec
const $select = $(this); window.GROUP_SELECT_PER_PAGE = 20;
const allAvailable = $select.data('allAvailable'); $('.ajax-groups-select').each(function setAjaxGroupsSelect2() {
const skipGroups = $select.data('skipGroups') || []; const $select = $(this);
const parentGroupID = $select.data('parentId'); const allAvailable = $select.data('allAvailable');
const groupsPath = parentGroupID const skipGroups = $select.data('skipGroups') || [];
? Api.subgroupsPath.replace(':id', parentGroupID) const parentGroupID = $select.data('parentId');
: Api.groupsPath; const groupsPath = parentGroupID
? Api.subgroupsPath.replace(':id', parentGroupID)
: Api.groupsPath;
$select.select2({ $select.select2({
placeholder: 'Search for a group', placeholder: 'Search for a group',
allowClear: $select.hasClass('allowClear'), allowClear: $select.hasClass('allowClear'),
multiple: $select.hasClass('multiselect'), multiple: $select.hasClass('multiselect'),
minimumInputLength: 0, minimumInputLength: 0,
ajax: { ajax: {
url: Api.buildUrl(groupsPath), url: Api.buildUrl(groupsPath),
dataType: 'json', dataType: 'json',
quietMillis: 250, quietMillis: 250,
transport(params) { transport(params) {
axios[params.type.toLowerCase()](params.url, { axios[params.type.toLowerCase()](params.url, {
params: params.data, params: params.data,
}) })
.then(res => { .then(res => {
const results = res.data || []; const results = res.data || [];
const headers = normalizeHeaders(res.headers); const headers = normalizeHeaders(res.headers);
const currentPage = parseInt(headers['X-PAGE'], 10) || 0; const currentPage = parseInt(headers['X-PAGE'], 10) || 0;
const totalPages = parseInt(headers['X-TOTAL-PAGES'], 10) || 0; const totalPages = parseInt(headers['X-TOTAL-PAGES'], 10) || 0;
const more = currentPage < totalPages; const more = currentPage < totalPages;
params.success({ params.success({
results, results,
pagination: { pagination: {
more, more,
}, },
}); });
}) })
.catch(params.error); .catch(params.error);
}, },
data(search, page) { data(search, page) {
return { return {
search, search,
page, page,
per_page: window.GROUP_SELECT_PER_PAGE, per_page: window.GROUP_SELECT_PER_PAGE,
all_available: allAvailable, all_available: allAvailable,
}; };
}, },
results(data, page) { results(data, page) {
if (data.length) return { results: [] }; if (data.length) return { results: [] };
const groups = data.length ? data : data.results || []; const groups = data.length ? data : data.results || [];
const more = data.pagination ? data.pagination.more : false; const more = data.pagination ? data.pagination.more : false;
const results = groups.filter(group => skipGroups.indexOf(group.id) === -1); const results = groups.filter(group => skipGroups.indexOf(group.id) === -1);
return { return {
results, results,
page, page,
more, more,
}; };
}, },
}, },
// eslint-disable-next-line consistent-return // eslint-disable-next-line consistent-return
initSelection(element, callback) { initSelection(element, callback) {
const id = $(element).val(); const id = $(element).val();
if (id !== '') { if (id !== '') {
return Api.group(id, callback); return Api.group(id, callback);
} }
}, },
formatResult(object) { formatResult(object) {
return `<div class='group-result'> <div class='group-name'>${ return `<div class='group-result'> <div class='group-name'>${
object.full_name object.full_name
}</div> <div class='group-path'>${object.full_path}</div> </div>`; }</div> <div class='group-path'>${object.full_path}</div> </div>`;
}, },
formatSelection(object) { formatSelection(object) {
return object.full_name; return object.full_name;
}, },
dropdownCssClass: 'ajax-groups-dropdown select2-infinite', dropdownCssClass: 'ajax-groups-dropdown select2-infinite',
// we do not want to escape markup since we are displaying html in results // we do not want to escape markup since we are displaying html in results
escapeMarkup(m) { escapeMarkup(m) {
return m; return m;
}, },
}); });
$select.on('select2-loaded', () => { $select.on('select2-loaded', () => {
const dropdown = document.querySelector('.select2-infinite .select2-results'); const dropdown = document.querySelector('.select2-infinite .select2-results');
dropdown.style.height = `${Math.floor(dropdown.scrollHeight)}px`; dropdown.style.height = `${Math.floor(dropdown.scrollHeight)}px`;
}); });
}); });
})
.catch(() => {});
} }
...@@ -11,10 +11,14 @@ class AutoWidthDropdownSelect { ...@@ -11,10 +11,14 @@ class AutoWidthDropdownSelect {
init() { init() {
const { dropdownClass } = this; const { dropdownClass } = this;
this.$selectElement.select2({ import(/* webpackChunkName: 'select2' */ 'select2/select2')
dropdownCssClass: dropdownClass, .then(() => {
...AutoWidthDropdownSelect.selectOptions(this.dropdownClass), this.$selectElement.select2({
}); dropdownCssClass: dropdownClass,
...AutoWidthDropdownSelect.selectOptions(this.dropdownClass),
});
})
.catch(() => {});
return this; return this;
} }
......
...@@ -7,10 +7,14 @@ export default class IssuableContext { ...@@ -7,10 +7,14 @@ export default class IssuableContext {
constructor(currentUser) { constructor(currentUser) {
this.userSelect = new UsersSelect(currentUser); this.userSelect = new UsersSelect(currentUser);
$('select.select2').select2({ import(/* webpackChunkName: 'select2' */ 'select2/select2')
width: 'resolve', .then(() => {
dropdownAutoWidth: true, $('select.select2').select2({
}); width: 'resolve',
dropdownAutoWidth: true,
});
})
.catch(() => {});
$('.issuable-sidebar .inline-update').on('change', 'select', function onClickSelect() { $('.issuable-sidebar .inline-update').on('change', 'select', function onClickSelect() {
return $(this).submit(); return $(this).submit();
......
...@@ -120,35 +120,39 @@ export default class IssuableForm { ...@@ -120,35 +120,39 @@ export default class IssuableForm {
} }
initTargetBranchDropdown() { initTargetBranchDropdown() {
this.$targetBranchSelect.select2({ import(/* webpackChunkName: 'select2' */ 'select2/select2')
...AutoWidthDropdownSelect.selectOptions('js-target-branch-select'), .then(() => {
ajax: { this.$targetBranchSelect.select2({
url: this.$targetBranchSelect.data('endpoint'), ...AutoWidthDropdownSelect.selectOptions('js-target-branch-select'),
dataType: 'JSON', ajax: {
quietMillis: 250, url: this.$targetBranchSelect.data('endpoint'),
data(search) { dataType: 'JSON',
return { quietMillis: 250,
search, data(search) {
}; return {
}, search,
results(data) { };
return { },
// `data` keys are translated so we can't just access them with a string based key results(data) {
results: data[Object.keys(data)[0]].map(name => ({ return {
id: name, // `data` keys are translated so we can't just access them with a string based key
text: name, results: data[Object.keys(data)[0]].map(name => ({
})), id: name,
}; text: name,
}, })),
}, };
initSelection(el, callback) { },
const val = el.val(); },
initSelection(el, callback) {
callback({ const val = el.val();
id: val,
text: val, callback({
id: val,
text: val,
});
},
}); });
}, })
}); .catch(() => {});
} }
} }
...@@ -100,18 +100,24 @@ function deferredInitialisation() { ...@@ -100,18 +100,24 @@ function deferredInitialisation() {
}); });
// Initialize select2 selects // Initialize select2 selects
$('select.select2').select2({ if ($('select.select2').length) {
width: 'resolve', import(/* webpackChunkName: 'select2' */ 'select2/select2')
dropdownAutoWidth: true, .then(() => {
}); $('select.select2').select2({
width: 'resolve',
// Close select2 on escape dropdownAutoWidth: true,
$('.js-select2').on('select2-close', () => { });
setTimeout(() => {
$('.select2-container-active').removeClass('select2-container-active'); // Close select2 on escape
$(':focus').blur(); $('.js-select2').on('select2-close', () => {
}, 1); setTimeout(() => {
}); $('.select2-container-active').removeClass('select2-container-active');
$(':focus').blur();
}, 1);
});
})
.catch(() => {});
}
// Initialize tooltips // Initialize tooltips
$body.tooltip({ $body.tooltip({
......
...@@ -5,97 +5,101 @@ import Api from './api'; ...@@ -5,97 +5,101 @@ import Api from './api';
import ProjectSelectComboButton from './project_select_combo_button'; import ProjectSelectComboButton from './project_select_combo_button';
export default function projectSelect() { export default function projectSelect() {
$('.ajax-project-select').each(function(i, select) { import(/* webpackChunkName: 'select2' */ 'select2/select2')
var placeholder; .then(() => {
const simpleFilter = $(select).data('simpleFilter') || false; $('.ajax-project-select').each(function(i, select) {
this.groupId = $(select).data('groupId'); var placeholder;
this.includeGroups = $(select).data('includeGroups'); const simpleFilter = $(select).data('simpleFilter') || false;
this.allProjects = $(select).data('allProjects') || false; this.groupId = $(select).data('groupId');
this.orderBy = $(select).data('orderBy') || 'id'; this.includeGroups = $(select).data('includeGroups');
this.withIssuesEnabled = $(select).data('withIssuesEnabled'); this.allProjects = $(select).data('allProjects') || false;
this.withMergeRequestsEnabled = $(select).data('withMergeRequestsEnabled'); this.orderBy = $(select).data('orderBy') || 'id';
this.withShared = this.withIssuesEnabled = $(select).data('withIssuesEnabled');
$(select).data('withShared') === undefined ? true : $(select).data('withShared'); this.withMergeRequestsEnabled = $(select).data('withMergeRequestsEnabled');
this.includeProjectsInSubgroups = $(select).data('includeProjectsInSubgroups') || false; this.withShared =
this.allowClear = $(select).data('allowClear') || false; $(select).data('withShared') === undefined ? true : $(select).data('withShared');
this.includeProjectsInSubgroups = $(select).data('includeProjectsInSubgroups') || false;
this.allowClear = $(select).data('allowClear') || false;
placeholder = 'Search for project'; placeholder = 'Search for project';
if (this.includeGroups) { if (this.includeGroups) {
placeholder += ' or group'; placeholder += ' or group';
} }
$(select).select2({ $(select).select2({
placeholder: placeholder, placeholder: placeholder,
minimumInputLength: 0, minimumInputLength: 0,
query: (function(_this) { query: (function(_this) {
return function(query) { return function(query) {
var finalCallback, projectsCallback; var finalCallback, projectsCallback;
finalCallback = function(projects) { finalCallback = function(projects) {
var data;
data = {
results: projects,
};
return query.callback(data);
};
if (_this.includeGroups) {
projectsCallback = function(projects) {
var groupsCallback;
groupsCallback = function(groups) {
var data; var data;
data = groups.concat(projects); data = {
return finalCallback(data); results: projects,
};
return query.callback(data);
}; };
return Api.groups(query.term, {}, groupsCallback); if (_this.includeGroups) {
projectsCallback = function(projects) {
var groupsCallback;
groupsCallback = function(groups) {
var data;
data = groups.concat(projects);
return finalCallback(data);
};
return Api.groups(query.term, {}, groupsCallback);
};
} else {
projectsCallback = finalCallback;
}
if (_this.groupId) {
return Api.groupProjects(
_this.groupId,
query.term,
{
with_issues_enabled: _this.withIssuesEnabled,
with_merge_requests_enabled: _this.withMergeRequestsEnabled,
with_shared: _this.withShared,
include_subgroups: _this.includeProjectsInSubgroups,
},
projectsCallback,
);
} else {
return Api.projects(
query.term,
{
order_by: _this.orderBy,
with_issues_enabled: _this.withIssuesEnabled,
with_merge_requests_enabled: _this.withMergeRequestsEnabled,
membership: !_this.allProjects,
},
projectsCallback,
);
}
}; };
} else { })(this),
projectsCallback = finalCallback; id: function(project) {
} if (simpleFilter) return project.id;
if (_this.groupId) { return JSON.stringify({
return Api.groupProjects( name: project.name,
_this.groupId, url: project.web_url,
query.term, });
{ },
with_issues_enabled: _this.withIssuesEnabled, text: function(project) {
with_merge_requests_enabled: _this.withMergeRequestsEnabled, return project.name_with_namespace || project.name;
with_shared: _this.withShared, },
include_subgroups: _this.includeProjectsInSubgroups,
},
projectsCallback,
);
} else {
return Api.projects(
query.term,
{
order_by: _this.orderBy,
with_issues_enabled: _this.withIssuesEnabled,
with_merge_requests_enabled: _this.withMergeRequestsEnabled,
membership: !_this.allProjects,
},
projectsCallback,
);
}
};
})(this),
id: function(project) {
if (simpleFilter) return project.id;
return JSON.stringify({
name: project.name,
url: project.web_url,
});
},
text: function(project) {
return project.name_with_namespace || project.name;
},
initSelection: function(el, callback) { initSelection: function(el, callback) {
return Api.project(el.val()).then(({ data }) => callback(data)); return Api.project(el.val()).then(({ data }) => callback(data));
}, },
allowClear: this.allowClear, allowClear: this.allowClear,
dropdownCssClass: 'ajax-project-dropdown', dropdownCssClass: 'ajax-project-dropdown',
}); });
if (simpleFilter) return select; if (simpleFilter) return select;
return new ProjectSelectComboButton(select); return new ProjectSelectComboButton(select);
}); });
})
.catch(() => {});
} }
...@@ -44,9 +44,13 @@ export default class ProjectSelectComboButton { ...@@ -44,9 +44,13 @@ export default class ProjectSelectComboButton {
// eslint-disable-next-line class-methods-use-this // eslint-disable-next-line class-methods-use-this
openDropdown(event) { openDropdown(event) {
$(event.currentTarget) import(/* webpackChunkName: 'select2' */ 'select2/select2')
.siblings('.project-item-select') .then(() => {
.select2('open'); $(event.currentTarget)
.siblings('.project-item-select')
.select2('open');
})
.catch(() => {});
} }
selectProject() { selectProject() {
......
...@@ -579,101 +579,109 @@ function UsersSelect(currentUser, els, options = {}) { ...@@ -579,101 +579,109 @@ function UsersSelect(currentUser, els, options = {}) {
}; };
})(this), })(this),
); );
$('.ajax-users-select').each( import(/* webpackChunkName: 'select2' */ 'select2/select2')
(function(_this) { .then(() => {
return function(i, select) { $('.ajax-users-select').each(
var firstUser, showAnyUser, showEmailUser, showNullUser; (function(_this) {
var options = {}; return function(i, select) {
options.skipLdap = $(select).hasClass('skip_ldap'); var firstUser, showAnyUser, showEmailUser, showNullUser;
options.projectId = $(select).data('projectId'); var options = {};
options.groupId = $(select).data('groupId'); options.skipLdap = $(select).hasClass('skip_ldap');
options.showCurrentUser = $(select).data('currentUser'); options.projectId = $(select).data('projectId');
options.authorId = $(select).data('authorId'); options.groupId = $(select).data('groupId');
options.skipUsers = $(select).data('skipUsers'); options.showCurrentUser = $(select).data('currentUser');
showNullUser = $(select).data('nullUser'); options.authorId = $(select).data('authorId');
showAnyUser = $(select).data('anyUser'); options.skipUsers = $(select).data('skipUsers');
showEmailUser = $(select).data('emailUser'); showNullUser = $(select).data('nullUser');
firstUser = $(select).data('firstUser'); showAnyUser = $(select).data('anyUser');
return $(select).select2({ showEmailUser = $(select).data('emailUser');
placeholder: 'Search for a user', firstUser = $(select).data('firstUser');
multiple: $(select).hasClass('multiselect'), return $(select).select2({
minimumInputLength: 0, placeholder: 'Search for a user',
query: function(query) { multiple: $(select).hasClass('multiselect'),
return _this.users(query.term, options, function(users) { minimumInputLength: 0,
var anyUser, data, emailUser, index, len, name, nullUser, obj, ref; query: function(query) {
data = { return _this.users(query.term, options, function(users) {
results: users, var anyUser, data, emailUser, index, len, name, nullUser, obj, ref;
}; data = {
if (query.term.length === 0) { results: users,
if (firstUser) { };
// Move current user to the front of the list if (query.term.length === 0) {
ref = data.results; if (firstUser) {
// Move current user to the front of the list
for (index = 0, len = ref.length; index < len; index += 1) { ref = data.results;
obj = ref[index];
if (obj.username === firstUser) { for (index = 0, len = ref.length; index < len; index += 1) {
data.results.splice(index, 1); obj = ref[index];
data.results.unshift(obj); if (obj.username === firstUser) {
break; data.results.splice(index, 1);
data.results.unshift(obj);
break;
}
}
}
if (showNullUser) {
nullUser = {
name: 'Unassigned',
id: 0,
};
data.results.unshift(nullUser);
}
if (showAnyUser) {
name = showAnyUser;
if (name === true) {
name = 'Any User';
}
anyUser = {
name: name,
id: null,
};
data.results.unshift(anyUser);
} }
} }
} if (
if (showNullUser) { showEmailUser &&
nullUser = { data.results.length === 0 &&
name: 'Unassigned', query.term.match(/^[^@]+@[^@]+$/)
id: 0, ) {
}; var trimmed = query.term.trim();
data.results.unshift(nullUser); emailUser = {
} name: 'Invite "' + trimmed + '" by email',
if (showAnyUser) { username: trimmed,
name = showAnyUser; id: trimmed,
if (name === true) { invite: true,
name = 'Any User'; };
data.results.unshift(emailUser);
} }
anyUser = { return query.callback(data);
name: name, });
id: null, },
}; initSelection: function() {
data.results.unshift(anyUser); var args;
} args = 1 <= arguments.length ? [].slice.call(arguments, 0) : [];
} return _this.initSelection.apply(_this, args);
if (showEmailUser && data.results.length === 0 && query.term.match(/^[^@]+@[^@]+$/)) { },
var trimmed = query.term.trim(); formatResult: function() {
emailUser = { var args;
name: 'Invite "' + trimmed + '" by email', args = 1 <= arguments.length ? [].slice.call(arguments, 0) : [];
username: trimmed, return _this.formatResult.apply(_this, args);
id: trimmed, },
invite: true, formatSelection: function() {
}; var args;
data.results.unshift(emailUser); args = 1 <= arguments.length ? [].slice.call(arguments, 0) : [];
} return _this.formatSelection.apply(_this, args);
return query.callback(data); },
dropdownCssClass: 'ajax-users-dropdown',
// we do not want to escape markup since we are displaying html in results
escapeMarkup: function(m) {
return m;
},
}); });
}, };
initSelection: function() { })(this),
var args; );
args = 1 <= arguments.length ? [].slice.call(arguments, 0) : []; })
return _this.initSelection.apply(_this, args); .catch(() => {});
},
formatResult: function() {
var args;
args = 1 <= arguments.length ? [].slice.call(arguments, 0) : [];
return _this.formatResult.apply(_this, args);
},
formatSelection: function() {
var args;
args = 1 <= arguments.length ? [].slice.call(arguments, 0) : [];
return _this.formatSelection.apply(_this, args);
},
dropdownCssClass: 'ajax-users-dropdown',
// we do not want to escape markup since we are displaying html in results
escapeMarkup: function(m) {
return m;
},
});
};
})(this),
);
} }
UsersSelect.prototype.initSelection = function(element, callback) { UsersSelect.prototype.initSelection = function(element, callback) {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment