All files / app/assets/javascripts/ref/components ref_selector.vue

97.61% Statements 41/42
79.16% Branches 19/24
96.66% Functions 29/30
97.61% Lines 41/42

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      28x                                                                                                                                                                                         68x                         68x           151x     136x     136x     89x     78x               78x     78x     78x     170x             150x     78x 8x     70x     78x     90x                 78x 1x 77x 6x     78x                 78x 69x                     68x             68x   68x 68x   68x     69x 69x         68x                               22x 22x     10x 1x     9x 9x     91x     140x                                                                                                                            
<script>
import { GlBadge, GlIcon, GlCollapsibleListbox } from '@gitlab/ui';
import { debounce, isArray } from 'lodash';
// eslint-disable-next-line no-restricted-imports
import { mapActions, mapGetters, mapState } from 'vuex';
import { sprintf } from '~/locale';
import {
  ALL_REF_TYPES,
  SEARCH_DEBOUNCE_MS,
  DEFAULT_I18N,
  REF_TYPE_BRANCHES,
  REF_TYPE_TAGS,
  REF_TYPE_COMMITS,
  TAG_REF_TYPE,
  BRANCH_REF_TYPE,
  TAG_REF_TYPE_ICON,
  BRANCH_REF_TYPE_ICON,
} from '../constants';
import createStore from '../stores';
import { formatListBoxItems, formatErrors } from '../format_refs';
 
export default {
  name: 'RefSelector',
  components: {
    GlBadge,
    GlIcon,
    GlCollapsibleListbox,
  },
  inheritAttrs: false,
  props: {
    disabled: {
      type: Boolean,
      required: false,
      default: false,
    },
    enabledRefTypes: {
      type: Array,
      required: false,
      default: () => ALL_REF_TYPES,
      validator: (val) =>
        // It has to be an array
        isArray(val) &&
        // with at least one item
        val.length > 0 &&
        // and only "REF_TYPE_BRANCHES", "REF_TYPE_TAGS", and "REF_TYPE_COMMITS" are allowed
        val.every((item) => ALL_REF_TYPES.includes(item)) &&
        // and no duplicates are allowed
        val.length === new Set(val).size,
    },
    value: {
      type: String,
      required: false,
      default: '',
    },
    queryParams: {
      type: Object,
      required: false,
      default: () => {},
    },
    projectId: {
      type: String,
      required: true,
    },
    translations: {
      type: Object,
      required: false,
      default: () => ({}),
    },
    useSymbolicRefNames: {
      type: Boolean,
      required: false,
      default: false,
    },
 
    /** The validation state of this component. */
    state: {
      type: Boolean,
      required: false,
      default: true,
    },
 
    /* Underlying form field name for scenarios where ref_selector
     * is used as part of submitting an HTML form
     */
    name: {
      type: String,
      required: false,
      default: '',
    },
    toggleButtonClass: {
      type: [String, Object, Array],
      required: false,
      default: null,
    },
  },
  data() {
    return {
      query: '',
    };
  },
  computed: {
    ...mapState({
      matches: (state) => state.matches,
      lastQuery: (state) => state.query,
      selectedRef: (state) => state.selectedRef,
      params: (state) => state.params,
    }),
    ...mapGetters(['isLoading', 'isQueryPossiblyASha']),
    i18n() {
      return {
        ...DEFAULT_I18N,
        ...this.translations,
      };
    },
    listBoxItems() {
      return formatListBoxItems(this.branches, this.tags, this.commits);
    },
    branches() {
      return this.enabledRefTypes.includes(REF_TYPE_BRANCHES) ? this.matches.branches.list : [];
    },
    tags() {
      return this.enabledRefTypes.includes(REF_TYPE_TAGS) ? this.matches.tags.list : [];
    },
    commits() {
      return this.enabledRefTypes.includes(REF_TYPE_COMMITS) ? this.matches.commits.list : [];
    },
    extendedToggleButtonClass() {
      const classes = [
        {
          'gl-inset-border-1-red-500!': !this.state,
          'gl-font-monospace': Boolean(this.selectedRef),
        },
        'gl-mb-0',
      ];
 
      Iif (Array.isArray(this.toggleButtonClass)) {
        classes.push(...this.toggleButtonClass);
      } else {
        classes.push(this.toggleButtonClass);
      }
 
      return classes;
    },
    footerSlotProps() {
      return {
        isLoading: this.isLoading,
        matches: this.matches,
        query: this.lastQuery,
      };
    },
    errors() {
      return formatErrors(this.matches.branches, this.matches.tags, this.matches.commits);
    },
    selectedRefForDisplay() {
      if (this.useSymbolicRefNames && this.selectedRef) {
        return this.selectedRef.replace(/^refs\/(tags|heads)\//, '');
      }
 
      return this.selectedRef;
    },
    buttonText() {
      return this.selectedRefForDisplay || this.i18n.noRefSelected;
    },
    noResultsMessage() {
      return this.lastQuery
        ? sprintf(this.i18n.noResultsWithQuery, {
            query: this.lastQuery,
          })
        : this.i18n.noResults;
    },
    dropdownIcon() {
      let icon;
 
      if (this.selectedRef.includes(`refs/${TAG_REF_TYPE}`)) {
        icon = TAG_REF_TYPE_ICON;
      } else if (this.selectedRef.includes(`refs/${BRANCH_REF_TYPE}`)) {
        icon = BRANCH_REF_TYPE_ICON;
      }
 
      return icon;
    },
  },
  watch: {
    // Keep the Vuex store synchronized if the parent
    // component updates the selected ref through v-model
    value: {
      immediate: true,
      handler() {
        if (this.value !== this.selectedRef) {
          this.setSelectedRef(this.value);
        }
      },
    },
  },
  beforeCreate() {
    // Setting the store here instead of using
    // the built in `store` component option because
    // we need each new `RefSelector` instance to
    // create a new Vuex store instance.
    // See https://github.com/vuejs/vuex/issues/414#issue-184491718.
    this.$store = createStore();
  },
  created() {
    // This method is defined here instead of in `methods`
    // because we need to access the .cancel() method
    // lodash attaches to the function, which is
    // made inaccessible by Vue.
    this.debouncedSearch = debounce(this.search, SEARCH_DEBOUNCE_MS);
 
    this.setProjectId(this.projectId);
    this.setParams(this.queryParams);
 
    this.$watch(
      'enabledRefTypes',
      () => {
        this.setEnabledRefTypes(this.enabledRefTypes);
        this.search();
      },
      { immediate: true },
    );
 
    this.$watch(
      'useSymbolicRefNames',
      () => this.setUseSymbolicRefNames(this.useSymbolicRefNames),
      { immediate: true },
    );
  },
  methods: {
    ...mapActions([
      'setEnabledRefTypes',
      'setUseSymbolicRefNames',
      'setParams',
      'setProjectId',
      'setSelectedRef',
    ]),
    ...mapActions({ storeSearch: 'search' }),
    onSearchBoxInput(searchQuery = '') {
      this.query = searchQuery?.trim();
      this.debouncedSearch();
    },
    selectRef(ref) {
      if (this.disabled) {
        return;
      }
 
      this.setSelectedRef(ref);
      this.$emit('input', this.selectedRef);
    },
    search() {
      this.storeSearch(this.query);
    },
    totalCountText(count) {
      return count > 999 ? this.i18n.totalCountLabel : `${count}`;
    },
  },
};
</script>
 
<template>
  <div>
    <gl-collapsible-listbox
      class="ref-selector gl-w-full"
      block
      searchable
      :selected="selectedRef"
      :header-text="i18n.dropdownHeader"
      :items="listBoxItems"
      :no-results-text="noResultsMessage"
      :searching="isLoading"
      :search-placeholder="i18n.searchPlaceholder"
      :toggle-class="extendedToggleButtonClass"
      :toggle-text="buttonText"
      :icon="dropdownIcon"
      :disabled="disabled"
      v-bind="$attrs"
      v-on="$listeners"
      @hidden="$emit('hide')"
      @search="onSearchBoxInput"
      @select="selectRef"
    >
      <template #group-label="{ group }">
        {{ group.text }} <gl-badge size="sm">{{ totalCountText(group.options.length) }}</gl-badge>
      </template>
      <template #list-item="{ item }">
        {{ item.text }}
        <gl-badge v-if="item.default" size="sm" variant="info">{{
          i18n.defaultLabelText
        }}</gl-badge>
        <gl-badge v-if="item.protected" size="sm" variant="neutral">{{
          i18n.protectedLabelText
        }}</gl-badge>
      </template>
      <template #footer>
        <slot name="footer" v-bind="footerSlotProps"></slot>
        <div
          v-for="errorMessage in errors"
          :key="errorMessage"
          data-testid="red-selector-error-list"
          class="gl-display-flex gl-align-items-flex-start gl-text-red-500 gl-mx-4 gl-my-3"
        >
          <gl-icon name="error" class="gl-mr-2 gl-mt-2 gl-flex-shrink-0" />
          <span>{{ errorMessage }}</span>
        </div>
      </template>
    </gl-collapsible-listbox>
    <input
      v-if="name"
      data-testid="selected-ref-form-field"
      type="hidden"
      :value="selectedRef"
      :name="name"
    />
  </div>
</template>