All files / app/assets/javascripts/vue_shared/components/user_select user_select.vue

100% Statements 73/73
87.87% Branches 29/33
100% Functions 50/50
100% Lines 73/73

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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407                                  7x                                                                                                                                             57x                   80x     68x         40x             27x           13x         82x     50x     68x     39x                   11x 11x     50x           54x     50x         50x 48x   2x           122x       66x           66x             66x     66x     66x     64x 64x     66x     75x     60x             81x 74x     7x 7x 7x     31x     66x     74x               9x 7x         57x       3x 3x 2x 2x 2x 2x   1x 1x   3x     2x 2x     2x 2x 2x     5x     10x     97x     147x   147x 147x 19x     147x   147x 12x 12x     147x     7x     195x 191x   4x     5x 5x                                                                                                                                                                                                            
<script>
import { debounce } from 'lodash';
import {
  GlDropdown,
  GlDropdownDivider,
  GlDropdownForm,
  GlDropdownItem,
  GlLoadingIcon,
  GlSearchBoxByType,
  GlTooltipDirective,
} from '@gitlab/ui';
import { __ } from '~/locale';
import SidebarParticipant from '~/sidebar/components/assignees/sidebar_participant.vue';
import { TYPE_ISSUE, TYPE_MERGE_REQUEST } from '~/issues/constants';
import { DEFAULT_DEBOUNCE_AND_THROTTLE_MS } from '~/lib/utils/constants';
import { participantsQueries, userSearchQueries } from '~/sidebar/queries/constants';
import { TYPENAME_MERGE_REQUEST } from '~/graphql_shared/constants';
import { convertToGraphQLId } from '~/graphql_shared/utils';
 
export default {
  i18n: {
    unassigned: __('Unassigned'),
  },
  components: {
    GlDropdownForm,
    GlDropdown,
    GlDropdownDivider,
    GlDropdownItem,
    GlSearchBoxByType,
    SidebarParticipant,
    GlLoadingIcon,
  },
  directives: {
    GlTooltip: GlTooltipDirective,
  },
  props: {
    headerText: {
      type: String,
      required: true,
    },
    text: {
      type: String,
      required: true,
    },
    fullPath: {
      type: String,
      required: true,
    },
    iid: {
      type: String,
      required: false,
      default: null,
    },
    value: {
      type: Array,
      required: true,
    },
    allowMultipleAssignees: {
      type: Boolean,
      required: false,
      default: false,
    },
    currentUser: {
      type: Object,
      required: true,
    },
    issuableType: {
      type: String,
      required: false,
      default: TYPE_ISSUE,
    },
    isEditing: {
      type: Boolean,
      required: false,
      default: true,
    },
    issuableId: {
      type: Number,
      required: false,
      default: null,
    },
    issuableAuthor: {
      type: Object,
      required: false,
      default: null,
    },
  },
  data() {
    return {
      search: '',
      participants: [],
      searchUsers: [],
      isSearching: false,
    };
  },
  apollo: {
    participants: {
      query() {
        return participantsQueries[this.issuableType].query;
      },
      skip() {
        return (
          Boolean(participantsQueries[this.issuableType].skipQuery) || !this.isEditing || !this.iid
        );
      },
      variables() {
        return {
          iid: this.iid,
          fullPath: this.fullPath,
          getStatus: true,
        };
      },
      update(data) {
        return data.workspace?.issuable?.participants.nodes.map((node) => ({
          ...node,
          canMerge: false,
        }));
      },
      error() {
        this.$emit('error');
      },
    },
    searchUsers: {
      query() {
        return userSearchQueries[this.issuableType].query;
      },
      variables() {
        return this.searchUsersVariables;
      },
      skip() {
        return !this.isEditing;
      },
      update(data) {
        return (
          data.workspace?.users
            .filter((user) => user)
            .map((user) => ({
              ...user,
              canMerge: user.mergeRequestInteraction?.canMerge || false,
            })) || []
        );
      },
      error() {
        this.$emit('error');
        this.isSearching = false;
      },
      result() {
        this.isSearching = false;
      },
    },
  },
  computed: {
    isMergeRequest() {
      return this.issuableType === TYPE_MERGE_REQUEST;
    },
    searchUsersVariables() {
      const variables = {
        fullPath: this.fullPath,
        search: this.search,
        first: 20,
      };
      if (!this.isMergeRequest) {
        return variables;
      }
      return {
        ...variables,
        mergeRequestId: convertToGraphQLId(TYPENAME_MERGE_REQUEST, this.issuableId),
      };
    },
    isLoading() {
      return this.$apollo.queries.searchUsers.loading || this.$apollo.queries.participants.loading;
    },
    users() {
      const filteredParticipants =
        this.participants?.filter(
          (user) => user.name.includes(this.search) || user.username.includes(this.search),
        ) || [];
 
      // TODO this de-duplication is temporary (BE fix required)
      // https://gitlab.com/gitlab-org/gitlab/-/issues/327822
      const mergedSearchResults = this.searchUsers
        .concat(filteredParticipants)
        .reduce(
          (acc, current) => (acc.some((user) => current.id === user.id) ? acc : [...acc, current]),
          [],
        );
 
      return this.moveCurrentUserAndAuthorToStart(mergedSearchResults);
    },
    isSearchEmpty() {
      return this.search === '';
    },
    shouldShowParticipants() {
      return this.isSearchEmpty || this.isSearching;
    },
    isCurrentUserInList() {
      const isCurrentUser = (user) => user.username === this.currentUser.username;
      return this.users.some(isCurrentUser);
    },
    noUsersFound() {
      return !this.isSearchEmpty && this.users.length === 0;
    },
    showCurrentUser() {
      return this.currentUser.username && !this.isCurrentUserInList && this.isSearchEmpty;
    },
    showAuthor() {
      return (
        this.issuableAuthor &&
        !this.users.some((user) => user.id === this.issuableAuthor.id) &&
        this.isSearchEmpty
      );
    },
    selectedFiltered() {
      if (this.shouldShowParticipants) {
        return this.moveCurrentUserAndAuthorToStart(this.value);
      }
 
      const foundUsernames = this.users.map(({ username }) => username);
      const filtered = this.value.filter(({ username }) => foundUsernames.includes(username));
      return this.moveCurrentUserAndAuthorToStart(filtered);
    },
    selectedUserNames() {
      return this.value.map(({ username }) => username);
    },
    unselectedFiltered() {
      return this.users?.filter(({ username }) => !this.selectedUserNames.includes(username)) || [];
    },
    selectedIsEmpty() {
      return this.selectedFiltered.length === 0;
    },
  },
 
  watch: {
    // We need to add this watcher to track the moment when user is alredy typing
    // but query is still not started due to debounce
    search(newVal) {
      if (newVal) {
        this.isSearching = true;
      }
    },
  },
  created() {
    this.debouncedSearchKeyUpdate = debounce(this.setSearchKey, DEFAULT_DEBOUNCE_AND_THROTTLE_MS);
  },
  methods: {
    selectAssignee(user) {
      let selected = [...this.value];
      if (!this.allowMultipleAssignees) {
        selected = [user];
        this.$emit('input', selected);
        this.$refs.dropdown.hide();
        this.$emit('toggle');
      } else {
        selected.push(user);
        this.$emit('input', selected);
      }
      this.clearAndFocusSearch();
    },
    unassign() {
      this.$emit('input', []);
      this.$refs.dropdown.hide();
    },
    unselect(name) {
      const selected = this.value.filter((user) => user.username !== name);
      this.$emit('input', selected);
      this.clearAndFocusSearch();
    },
    focusSearch() {
      this.$refs.search.focusInput();
    },
    showDropdown() {
      this.$refs.dropdown.show();
    },
    showDivider(list) {
      return list.length > 0 && this.isSearchEmpty;
    },
    moveCurrentUserAndAuthorToStart(users = []) {
      let sortedUsers = [...users];
 
      const author = sortedUsers.find((user) => user.id === this.issuableAuthor?.id);
      if (author) {
        sortedUsers = [author, ...sortedUsers.filter((user) => user.id !== author.id)];
      }
 
      const currentUser = sortedUsers.find((user) => user.username === this.currentUser.username);
 
      if (currentUser) {
        currentUser.canMerge = this.currentUser.canMerge;
        sortedUsers = [currentUser, ...sortedUsers.filter((user) => user.id !== currentUser.id)];
      }
 
      return sortedUsers;
    },
    setSearchKey(value) {
      this.search = value.trim();
    },
    tooltipText(user) {
      if (!this.isMergeRequest) {
        return '';
      }
      return user.canMerge ? '' : __('Cannot merge');
    },
    clearAndFocusSearch() {
      this.search = '';
      this.focusSearch();
    },
  },
};
</script>
 
<template>
  <gl-dropdown ref="dropdown" :text="text" @toggle="$emit('toggle')" @shown="focusSearch">
    <template #header>
      <p class="gl-font-weight-bold gl-text-center gl-mt-2 gl-mb-4">{{ headerText }}</p>
      <gl-dropdown-divider />
      <gl-search-box-by-type
        ref="search"
        :value="search"
        data-testid="user-search-input"
        @input="debouncedSearchKeyUpdate"
      />
    </template>
    <gl-dropdown-form class="gl-relative gl-min-h-7">
      <gl-loading-icon
        v-if="isLoading"
        data-testid="loading-participants"
        size="md"
        class="gl-absolute gl-left-0 gl-top-0 gl-right-0"
      />
      <template v-else>
        <template v-if="shouldShowParticipants">
          <gl-dropdown-item
            v-if="isSearchEmpty"
            :is-checked="selectedIsEmpty"
            is-check-centered
            data-testid="unassign"
            @click.native.capture.stop="unassign"
          >
            <span :class="selectedIsEmpty ? 'gl-pl-0' : 'gl-pl-6'" class="gl-font-weight-bold">{{
              $options.i18n.unassigned
            }}</span>
          </gl-dropdown-item>
        </template>
        <gl-dropdown-divider v-if="showDivider(selectedFiltered)" />
        <gl-dropdown-item
          v-for="item in selectedFiltered"
          :key="item.id"
          v-gl-tooltip.left.viewport
          :title="tooltipText(item)"
          boundary="viewport"
          is-checked
          is-check-centered
          data-testid="selected-participant"
          @click.native.capture.stop="unselect(item.username)"
        >
          <sidebar-participant :user="item" :issuable-type="issuableType" selected />
        </gl-dropdown-item>
        <template v-if="showCurrentUser">
          <gl-dropdown-divider />
          <gl-dropdown-item
            data-testid="current-user"
            @click.native.capture.stop="selectAssignee(currentUser)"
          >
            <sidebar-participant
              :user="currentUser"
              :issuable-type="issuableType"
              class="gl-pl-6!"
            />
          </gl-dropdown-item>
        </template>
        <gl-dropdown-item
          v-if="showAuthor"
          data-testid="issuable-author"
          @click.native.capture.stop="selectAssignee(issuableAuthor)"
        >
          <sidebar-participant
            :user="issuableAuthor"
            :issuable-type="issuableType"
            class="gl-pl-6!"
          />
        </gl-dropdown-item>
        <gl-dropdown-item
          v-for="unselectedUser in unselectedFiltered"
          :key="unselectedUser.id"
          v-gl-tooltip.left.viewport
          :title="tooltipText(unselectedUser)"
          boundary="viewport"
          data-testid="unselected-participant"
          @click.native.capture.stop="selectAssignee(unselectedUser)"
        >
          <sidebar-participant
            :user="unselectedUser"
            :issuable-type="issuableType"
            class="gl-pl-6!"
          />
        </gl-dropdown-item>
        <gl-dropdown-item v-if="noUsersFound" data-testid="empty-results" class="gl-pl-6!">
          {{ __('No matching results') }}
        </gl-dropdown-item>
      </template>
    </gl-dropdown-form>
    <template #footer>
      <slot name="footer"></slot>
    </template>
  </gl-dropdown>
</template>