40a04bc7e6
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.
53 lines
1.3 KiB
JavaScript
53 lines
1.3 KiB
JavaScript
import $ from 'jquery';
|
|
|
|
let instanceCount = 0;
|
|
|
|
class AutoWidthDropdownSelect {
|
|
constructor(selectElement) {
|
|
this.$selectElement = $(selectElement);
|
|
this.dropdownClass = `js-auto-width-select-dropdown-${instanceCount}`;
|
|
instanceCount += 1;
|
|
}
|
|
|
|
init() {
|
|
const { dropdownClass } = this;
|
|
import(/* webpackChunkName: 'select2' */ 'select2/select2')
|
|
.then(() => {
|
|
this.$selectElement.select2({
|
|
dropdownCssClass: dropdownClass,
|
|
...AutoWidthDropdownSelect.selectOptions(this.dropdownClass),
|
|
});
|
|
})
|
|
.catch(() => {});
|
|
|
|
return this;
|
|
}
|
|
|
|
static selectOptions(dropdownClass) {
|
|
return {
|
|
dropdownCss() {
|
|
let resultantWidth = 'auto';
|
|
const $dropdown = $(`.${dropdownClass}`);
|
|
|
|
// We have to look at the parent because
|
|
// `offsetParent` on a `display: none;` is `null`
|
|
const offsetParentWidth = $(this)
|
|
.parent()
|
|
.offsetParent()
|
|
.width();
|
|
// Reset any width to let it naturally flow
|
|
$dropdown.css('width', 'auto');
|
|
if ($dropdown.outerWidth(false) > offsetParentWidth) {
|
|
resultantWidth = offsetParentWidth;
|
|
}
|
|
|
|
return {
|
|
width: resultantWidth,
|
|
maxWidth: offsetParentWidth,
|
|
};
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
export default AutoWidthDropdownSelect;
|