summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/issuable/auto_width_dropdown_select.js
blob: 12f038739582e9849c4029f5cf0b672c3525c2e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import $ from 'jquery';
import { loadCSSFile } from '../lib/utils/css_utils';

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(() => {
        // eslint-disable-next-line promise/no-nesting
        loadCSSFile(gon.select2_css_path)
          .then(() => {
            this.$selectElement.select2({
              dropdownCssClass: dropdownClass,
              ...AutoWidthDropdownSelect.selectOptions(this.dropdownClass),
            });
          })
          .catch(() => {});
      })
      .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;