2018-03-09 15:18:59 -05:00
|
|
|
import $ from 'jquery';
|
|
|
|
|
2017-04-25 05:34:46 -04:00
|
|
|
let instanceCount = 0;
|
|
|
|
|
|
|
|
class AutoWidthDropdownSelect {
|
|
|
|
constructor(selectElement) {
|
|
|
|
this.$selectElement = $(selectElement);
|
|
|
|
this.dropdownClass = `js-auto-width-select-dropdown-${instanceCount}`;
|
|
|
|
instanceCount += 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
init() {
|
2018-06-16 17:50:13 -04:00
|
|
|
const { dropdownClass } = this;
|
2019-01-29 04:35:53 -05:00
|
|
|
import(/* webpackChunkName: 'select2' */ 'select2/select2')
|
|
|
|
.then(() => {
|
|
|
|
this.$selectElement.select2({
|
|
|
|
dropdownCssClass: dropdownClass,
|
|
|
|
...AutoWidthDropdownSelect.selectOptions(this.dropdownClass),
|
|
|
|
});
|
|
|
|
})
|
|
|
|
.catch(() => {});
|
2018-01-12 07:59:08 -05:00
|
|
|
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
static selectOptions(dropdownClass) {
|
|
|
|
return {
|
2017-04-25 05:34:46 -04:00
|
|
|
dropdownCss() {
|
|
|
|
let resultantWidth = 'auto';
|
|
|
|
const $dropdown = $(`.${dropdownClass}`);
|
|
|
|
|
|
|
|
// We have to look at the parent because
|
|
|
|
// `offsetParent` on a `display: none;` is `null`
|
2018-10-24 15:17:03 -04:00
|
|
|
const offsetParentWidth = $(this)
|
|
|
|
.parent()
|
|
|
|
.offsetParent()
|
|
|
|
.width();
|
2017-04-25 05:34:46 -04:00
|
|
|
// Reset any width to let it naturally flow
|
|
|
|
$dropdown.css('width', 'auto');
|
|
|
|
if ($dropdown.outerWidth(false) > offsetParentWidth) {
|
|
|
|
resultantWidth = offsetParentWidth;
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
width: resultantWidth,
|
|
|
|
maxWidth: offsetParentWidth,
|
|
|
|
};
|
|
|
|
},
|
2018-01-12 07:59:08 -05:00
|
|
|
};
|
2017-04-25 05:34:46 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default AutoWidthDropdownSelect;
|