All files / app/assets/javascripts/analytics/shared/components projects_dropdown_filter.vue

5.17% Statements 3/58
0% Branches 0/23
5.12% Functions 2/39
5.17% Lines 3/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293                    7x   7x 7x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
<script>
import { GlButton, GlIcon, GlAvatar, GlCollapsibleListbox, GlTruncate } from '@gitlab/ui';
import { debounce, unionBy } from 'lodash';
import { filterBySearchTerm } from '~/analytics/shared/utils';
import { getIdFromGraphQLId } from '~/graphql_shared/utils';
import { AVATAR_SHAPE_OPTION_RECT } from '~/vue_shared/constants';
import { DEFAULT_DEBOUNCE_AND_THROTTLE_MS } from '~/lib/utils/constants';
import { n__, s__, __ } from '~/locale';
import getProjects from '../graphql/projects.query.graphql';
 
const MIN_SEARCH_CHARS = 3;
 
const sortByProjectName = (projects = []) => projects.sort((a, b) => a.name.localeCompare(b.name));
const mapItemToListboxFormat = (item) => ({ ...item, value: item.id, text: item.name });
 
export default {
  name: 'ProjectsDropdownFilter',
  components: {
    GlButton,
    GlIcon,
    GlAvatar,
    GlCollapsibleListbox,
    GlTruncate,
  },
  props: {
    groupNamespace: {
      type: String,
      required: true,
    },
    multiSelect: {
      type: Boolean,
      required: false,
      default: false,
    },
    label: {
      type: String,
      required: false,
      default: s__('CycleAnalytics|project dropdown filter'),
    },
    queryParams: {
      type: Object,
      required: false,
      default: () => ({}),
    },
    defaultProjects: {
      type: Array,
      required: false,
      default: () => [],
    },
    loadingDefaultProjects: {
      type: Boolean,
      required: false,
      default: false,
    },
    toggleClasses: {
      type: String,
      required: false,
      default: '',
    },
  },
  data() {
    return {
      loading: true,
      projects: [],
      selectedProjects: this.defaultProjects || [],
      searchTerm: '',
      isDirty: false,
    };
  },
  computed: {
    selectedProjectsLabel() {
      Iif (this.selectedProjects.length === 1) {
        return this.selectedProjects[0].name;
      }
      Iif (this.selectedProjects.length > 1) {
        return n__(
          'CycleAnalytics|Project selected',
          'CycleAnalytics|%d projects selected',
          this.selectedProjects.length,
        );
      }
 
      return this.selectedProjectsPlaceholder;
    },
    selectedProjectsPlaceholder() {
      return this.multiSelect ? __('Select projects') : __('Select a project');
    },
    isOnlyOneProjectSelected() {
      return this.selectedProjects.length === 1;
    },
    selectedProjectIds() {
      return this.selectedProjects.map((p) => p.id);
    },
    selectedListBoxItems() {
      return this.multiSelect ? this.selectedProjectIds : this.selectedProjectIds[0];
    },
    hasSelectedProjects() {
      return Boolean(this.selectedProjects.length);
    },
    availableProjects() {
      return filterBySearchTerm(this.projects, this.searchTerm);
    },
    selectedItems() {
      return sortByProjectName(this.selectedProjects);
    },
    unselectedItems() {
      return this.availableProjects.filter(({ id }) => !this.selectedProjectIds.includes(id));
    },
    selectedGroupOptions() {
      return this.selectedItems.map(mapItemToListboxFormat);
    },
    unSelectedGroupOptions() {
      return this.unselectedItems.map(mapItemToListboxFormat);
    },
    listBoxItems() {
      Iif (this.selectedGroupOptions.length === 0) {
        return this.unSelectedGroupOptions;
      }
 
      return [
        {
          text: __('Selected'),
          options: this.selectedGroupOptions,
        },
        {
          text: __('Unselected'),
          options: this.unSelectedGroupOptions,
        },
      ];
    },
  },
  watch: {
    searchTerm() {
      this.search();
    },
    defaultProjects(projects) {
      this.selectedProjects = [...projects];
    },
  },
  mounted() {
    this.search();
  },
  methods: {
    handleUpdatedSelectedProjects() {
      this.$emit('selected', this.selectedProjects);
    },
    search: debounce(function debouncedSearch() {
      this.fetchData();
    }, DEFAULT_DEBOUNCE_AND_THROTTLE_MS),
    singleSelectedProject(selectedObj, isMarking) {
      return isMarking ? [selectedObj] : [];
    },
    getSelectedProjects(projects, selectedProjectIds) {
      return projects.filter(({ id }) => selectedProjectIds.includes(id));
    },
    setSelectedProjects(payload) {
      this.selectedProjects = this.multiSelect
        ? payload
        : this.singleSelectedProject(payload, !this.isProjectSelected(payload));
    },
    onClick(projectId) {
      const project = this.availableProjects.find(({ id }) => id === projectId);
      this.setSelectedProjects(project);
      this.handleUpdatedSelectedProjects();
    },
    onMultiSelectClick(projectIds) {
      const newlySelectedProjects = this.getSelectedProjects(this.availableProjects, projectIds);
      const selectedProjects = this.getSelectedProjects(this.selectedProjects, projectIds);
 
      this.setSelectedProjects(unionBy(newlySelectedProjects, selectedProjects, 'id'));
      this.isDirty = true;
    },
    onSelected(payload) {
      if (this.multiSelect) {
        this.onMultiSelectClick(payload);
      } else {
        this.onClick(payload);
      }
    },
    onHide() {
      Iif (this.multiSelect && this.isDirty) {
        this.handleUpdatedSelectedProjects();
      }
      this.searchTerm = '';
      this.isDirty = false;
    },
    onClearAll() {
      Iif (this.hasSelectedProjects) {
        this.isDirty = true;
      }
      this.selectedProjects = [];
    },
    fetchData() {
      this.loading = true;
 
      return this.$apollo
        .query({
          query: getProjects,
          variables: {
            groupFullPath: this.groupNamespace,
            search: this.searchTerm,
            ...this.queryParams,
          },
        })
        .then((response) => {
          const {
            data: {
              group: {
                projects: { nodes },
              },
            },
          } = response;
 
          this.loading = false;
          this.projects = nodes;
        });
    },
    isProjectSelected(project) {
      return this.selectedProjectIds.includes(project.id);
    },
    getEntityId(project) {
      return getIdFromGraphQLId(project.id);
    },
    setSearchTerm(val) {
      Iif (val && val.length >= MIN_SEARCH_CHARS) {
        this.searchTerm = val;
        return;
      }
 
      this.searchTerm = '';
    },
  },
  AVATAR_SHAPE_OPTION_RECT,
};
</script>
<template>
  <gl-collapsible-listbox
    ref="projectsDropdown"
    :header-text="__('Projects')"
    :items="listBoxItems"
    :reset-button-label="__('Clear All')"
    :loading="loadingDefaultProjects"
    :multiple="multiSelect"
    :no-results-text="__('No matching results')"
    :selected="selectedListBoxItems"
    :searching="loading"
    searchable
    @hidden="onHide"
    @reset="onClearAll"
    @search="setSearchTerm"
    @select="onSelected"
  >
    <template #toggle>
      <gl-button
        button-text-classes="gl-w-full gl-justify-content-space-between gl-display-flex gl-shadow-none gl-mb-0"
        :class="['dropdown-projects', toggleClasses]"
      >
        <gl-avatar
          v-if="isOnlyOneProjectSelected"
          :src="selectedProjects[0].avatarUrl"
          :entity-id="getEntityId(selectedProjects[0])"
          :entity-name="selectedProjects[0].name"
          :size="16"
          :shape="$options.AVATAR_SHAPE_OPTION_RECT"
          :alt="selectedProjects[0].name"
          class="gl-display-inline-flex gl-vertical-align-middle gl-mr-2 gl-flex-shrink-0"
        />
        <gl-truncate :text="selectedProjectsLabel" class="gl-min-w-0 gl-flex-grow-1" />
        <gl-icon class="gl-ml-2 gl-flex-shrink-0" name="chevron-down" />
      </gl-button>
    </template>
    <template #list-item="{ item }">
      <div class="gl-display-flex">
        <gl-avatar
          class="gl-mr-2 gl-vertical-align-middle"
          :alt="item.name"
          :size="16"
          :entity-id="getEntityId(item)"
          :entity-name="item.name"
          :src="item.avatarUrl"
          :shape="$options.AVATAR_SHAPE_OPTION_RECT"
        />
        <div>
          <div data-testid="project-name">{{ item.name }}</div>
          <div class="gl-text-gray-500" data-testid="project-full-path">
            {{ item.fullPath }}
          </div>
        </div>
      </div>
    </template>
  </gl-collapsible-listbox>
</template>