1<script>
2import { mapState, mapActions, mapGetters } from 'vuex';
3import { visitUrl, setUrlParams } from '~/lib/utils/url_utility';
4import { ANY_OPTION, GROUP_DATA, PROJECT_DATA } from '../constants';
5import SearchableDropdown from './searchable_dropdown.vue';
6
7export default {
8  name: 'ProjectFilter',
9  components: {
10    SearchableDropdown,
11  },
12  props: {
13    initialData: {
14      type: Object,
15      required: false,
16      default: () => null,
17    },
18  },
19  computed: {
20    ...mapState(['query', 'projects', 'fetchingProjects']),
21    ...mapGetters(['frequentProjects']),
22    selectedProject() {
23      return this.initialData ? this.initialData : ANY_OPTION;
24    },
25  },
26  created() {
27    // This tracks projects searched via the top nav search bar
28    if (this.query.nav_source === 'navbar' && this.initialData?.id) {
29      this.setFrequentProject(this.initialData);
30    }
31  },
32  methods: {
33    ...mapActions(['fetchProjects', 'setFrequentProject', 'loadFrequentProjects']),
34    handleProjectChange(project) {
35      // If project.id is null we are clearing the filter and don't need to store that in LS.
36      if (project.id) {
37        this.setFrequentProject(project);
38      }
39
40      // This determines if we need to update the group filter or not
41      const queryParams = {
42        ...(project.namespace?.id && { [GROUP_DATA.queryParam]: project.namespace.id }),
43        [PROJECT_DATA.queryParam]: project.id,
44        nav_source: null,
45      };
46
47      visitUrl(setUrlParams(queryParams));
48    },
49  },
50  PROJECT_DATA,
51};
52</script>
53
54<template>
55  <searchable-dropdown
56    data-testid="project-filter"
57    :header-text="$options.PROJECT_DATA.headerText"
58    :name="$options.PROJECT_DATA.name"
59    :full-name="$options.PROJECT_DATA.fullName"
60    :loading="fetchingProjects"
61    :selected-item="selectedProject"
62    :items="projects"
63    :frequent-items="frequentProjects"
64    @first-open="loadFrequentProjects"
65    @search="fetchProjects"
66    @change="handleProjectChange"
67  />
68</template>
69