summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/namespace_select.js
blob: 4660e4397a22127cfaad7ea93434d86aa9ad6178 (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
60
61
62
/* eslint-disable func-names, no-else-return, prefer-template, prefer-arrow-callback */

import $ from 'jquery';
import '~/gl_dropdown';
import Api from './api';
import { mergeUrlParams } from './lib/utils/url_utility';
import { parseBoolean } from '~/lib/utils/common_utils';
import { __ } from './locale';

export default class NamespaceSelect {
  constructor(opts) {
    const isFilter = parseBoolean(opts.dropdown.dataset.isFilter);
    const fieldName = opts.dropdown.dataset.fieldName || 'namespace_id';

    $(opts.dropdown).glDropdown({
      filterable: true,
      selectable: true,
      filterRemote: true,
      search: {
        fields: ['path'],
      },
      fieldName,
      toggleLabel(selected) {
        if (selected.id == null) {
          return selected.text;
        } else {
          return selected.kind + ': ' + selected.full_path;
        }
      },
      data(term, dataCallback) {
        return Api.namespaces(term, function(namespaces) {
          if (isFilter) {
            const anyNamespace = {
              text: __('Any namespace'),
              id: null,
            };
            namespaces.unshift(anyNamespace);
            namespaces.splice(1, 0, { type: 'divider' });
          }
          return dataCallback(namespaces);
        });
      },
      text(namespace) {
        if (namespace.id == null) {
          return namespace.text;
        } else {
          return namespace.kind + ': ' + namespace.full_path;
        }
      },
      renderRow: this.renderRow,
      clicked(options) {
        if (!isFilter) {
          const { e } = options;
          e.preventDefault();
        }
      },
      url(namespace) {
        return mergeUrlParams({ [fieldName]: namespace.id }, window.location.href);
      },
    });
  }
}