summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/projects/commit/components/projects_dropdown.vue
blob: fe54b62e2c815c46130d465d4a5838ed4f9e3902 (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<script>
import { GlCollapsibleListbox } from '@gitlab/ui';
import { mapGetters, mapState } from 'vuex';
import { debounce, uniqBy } from 'lodash';
import {
  I18N_NO_RESULTS_MESSAGE,
  I18N_PROJECT_HEADER,
  I18N_PROJECT_SEARCH_PLACEHOLDER,
} from '../constants';

export default {
  name: 'ProjectsDropdown',
  components: {
    GlCollapsibleListbox,
  },
  props: {
    value: {
      type: String,
      required: false,
      default: '',
    },
  },
  i18n: {
    noResultsMessage: I18N_NO_RESULTS_MESSAGE,
    projectHeaderTitle: I18N_PROJECT_HEADER,
    projectSearchPlaceholder: I18N_PROJECT_SEARCH_PLACEHOLDER,
  },
  data() {
    return {
      filterTerm: '',
    };
  },
  computed: {
    ...mapGetters(['sortedProjects']),
    ...mapState(['targetProjectId']),
    filteredResults() {
      const lowerCasedFilterTerm = this.filterTerm.toLowerCase();
      return this.sortedProjects.filter((project) =>
        project.name.toLowerCase().includes(lowerCasedFilterTerm),
      );
    },
    listboxItems() {
      const selectedItem = { value: this.selectedProject.id, text: this.selectedProject.name };
      const transformedList = this.filteredResults.map(({ id, name }) => ({
        value: id,
        text: name,
      }));

      if (this.filterTerm) {
        return transformedList;
      }

      // Add selected item to top of list if not searching
      return uniqBy([selectedItem].concat(transformedList), 'value');
    },
    selectedProject() {
      return this.sortedProjects.find((project) => project.id === this.targetProjectId) || {};
    },
  },
  methods: {
    selectProject(value) {
      this.$emit('input', value);
    },
    debouncedSearch: debounce(function debouncedSearch(value) {
      this.filterTerm = value.trim();
    }, 250),
  },
};
</script>
<template>
  <gl-collapsible-listbox
    class="gl-max-w-full"
    :header-text="$options.i18n.projectHeaderTitle"
    :items="listboxItems"
    searchable
    :search-placeholder="$options.i18n.projectSearchPlaceholder"
    :selected="selectedProject.id"
    :toggle-text="selectedProject.name"
    toggle-class="gl-w-full"
    :no-results-text="$options.i18n.noResultsMessage"
    @search="debouncedSearch"
    @select="selectProject"
  />
</template>