namespace_select.js 1.73 KB
Newer Older
1
/* eslint-disable func-names, object-shorthand, no-else-return, prefer-template, prefer-arrow-callback */
2 3

import $ from 'jquery';
4
import Api from './api';
5
import { mergeUrlParams } from './lib/utils/url_utility';
6
import { parseBoolean } from '~/lib/utils/common_utils';
7

8 9
export default class NamespaceSelect {
  constructor(opts) {
10
    const isFilter = parseBoolean(opts.dropdown.dataset.isFilter);
11 12 13
    const fieldName = opts.dropdown.dataset.fieldName || 'namespace_id';

    $(opts.dropdown).glDropdown({
14 15 16 17
      filterable: true,
      selectable: true,
      filterRemote: true,
      search: {
18
        fields: ['path'],
19 20 21 22 23 24
      },
      fieldName: fieldName,
      toggleLabel: function(selected) {
        if (selected.id == null) {
          return selected.text;
        } else {
25
          return selected.kind + ': ' + selected.full_path;
26 27 28 29
        }
      },
      data: function(term, dataCallback) {
        return Api.namespaces(term, function(namespaces) {
30
          if (isFilter) {
31
            const anyNamespace = {
32
              text: 'Any namespace',
33
              id: null,
34 35 36 37 38 39 40 41 42 43 44
            };
            namespaces.unshift(anyNamespace);
            namespaces.splice(1, 0, 'divider');
          }
          return dataCallback(namespaces);
        });
      },
      text: function(namespace) {
        if (namespace.id == null) {
          return namespace.text;
        } else {
45
          return namespace.kind + ': ' + namespace.full_path;
46 47 48
        }
      },
      renderRow: this.renderRow,
49
      clicked(options) {
50 51 52 53 54 55
        if (!isFilter) {
          const { e } = options;
          e.preventDefault();
        }
      },
      url(namespace) {
56
        return mergeUrlParams({ [fieldName]: namespace.id }, window.location.href);
57
      },
58 59 60
    });
  }
}