All files / app/assets/javascripts/packages_and_registries/package_registry/components/details package_files.vue

91.52% Statements 54/59
78.57% Branches 33/42
97.29% Functions 36/37
91.37% Lines 53/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 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 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526                                                                                          6x                                                                                                   80x     48x     80x 80x 48x       32x 32x         80x                     97x     142x     128x           97x     156x     80x                                                       80x           22x         8x               99x                   99x             65x     168x     6x 5x       18x 18x     77x     12x 12x     8x 8x 8x                 4x                                     8x 8x 8x       13x 13x 2x             11x 11x       216x     8x 5x   3x   8x     3x                 3x       3x                 3x             6x 6x 6x                                                                                                                                                                                                                                                                                                                                                                                                                          
<script>
import {
  GlAlert,
  GlLink,
  GlTable,
  GlDisclosureDropdown,
  GlDisclosureDropdownItem,
  GlButton,
  GlFormCheckbox,
  GlLoadingIcon,
  GlModal,
  GlSprintf,
  GlKeysetPagination,
} from '@gitlab/ui';
import * as Sentry from '~/sentry/sentry_browser_wrapper';
import { createAlert, VARIANT_SUCCESS, VARIANT_WARNING } from '~/alert';
import { NEXT, PREV } from '~/vue_shared/components/pagination/constants';
import { numberToHumanSize } from '~/lib/utils/number_utils';
import { scrollToElement } from '~/lib/utils/common_utils';
import { __, s__ } from '~/locale';
import FileSha from '~/packages_and_registries/package_registry/components/details/file_sha.vue';
import Tracking from '~/tracking';
import { packageTypeToTrackCategory } from '~/packages_and_registries/package_registry/utils';
import FileIcon from '~/vue_shared/components/file_icon.vue';
import TimeAgoTooltip from '~/vue_shared/components/time_ago_tooltip.vue';
import {
  FETCH_PACKAGE_FILES_ERROR_MESSAGE,
  GRAPHQL_PACKAGE_FILES_PAGE_SIZE,
  REQUEST_DELETE_SELECTED_PACKAGE_FILE_TRACKING_ACTION,
  SELECT_PACKAGE_FILE_TRACKING_ACTION,
  DOWNLOAD_PACKAGE_ASSET_TRACKING_ACTION,
  CANCEL_DELETE_PACKAGE_FILE_TRACKING_ACTION,
  DELETE_PACKAGE_FILE_TRACKING_ACTION,
  REQUEST_DELETE_PACKAGE_FILE_TRACKING_ACTION,
  TRACKING_LABEL_PACKAGE_ASSET,
  TRACKING_ACTION_EXPAND_PACKAGE_ASSET,
  DELETE_PACKAGE_FILE_ERROR_MESSAGE,
  DELETE_PACKAGE_FILE_SUCCESS_MESSAGE,
  DELETE_PACKAGE_FILES_ERROR_MESSAGE,
  DELETE_PACKAGE_FILES_SUCCESS_MESSAGE,
  DELETE_PACKAGE_FILES_TRACKING_ACTION,
  DELETE_ALL_PACKAGE_FILES_MODAL_CONTENT,
  DELETE_LAST_PACKAGE_FILE_MODAL_CONTENT,
} from '~/packages_and_registries/package_registry/constants';
import getPackageFilesQuery from '~/packages_and_registries/package_registry/graphql/queries/get_package_files.query.graphql';
import destroyPackageFilesMutation from '~/packages_and_registries/package_registry/graphql/mutations/destroy_package_files.mutation.graphql';
 
export default {
  name: 'PackageFiles',
  components: {
    GlAlert,
    GlLink,
    GlTable,
    GlDisclosureDropdown,
    GlDisclosureDropdownItem,
    GlFormCheckbox,
    GlButton,
    GlLoadingIcon,
    GlModal,
    GlKeysetPagination,
    GlSprintf,
    FileIcon,
    TimeAgoTooltip,
    FileSha,
  },
  mixins: [Tracking.mixin()],
  trackingActions: {
    DELETE_PACKAGE_FILE_TRACKING_ACTION,
    REQUEST_DELETE_PACKAGE_FILE_TRACKING_ACTION,
    CANCEL_DELETE_PACKAGE_FILE_TRACKING_ACTION,
    DOWNLOAD_PACKAGE_ASSET_TRACKING_ACTION,
  },
  props: {
    canDelete: {
      type: Boolean,
      required: false,
      default: false,
    },
    packageId: {
      type: String,
      required: true,
    },
    packageType: {
      type: String,
      required: true,
    },
    projectPath: {
      type: String,
      required: true,
    },
  },
  apollo: {
    packageFiles: {
      query: getPackageFilesQuery,
      variables() {
        return this.queryVariables;
      },
      update(data) {
        return data.package?.packageFiles?.nodes ?? [];
      },
      result({ data }) {
        const { packageFiles } = data?.package ?? {};
        if (packageFiles?.pageInfo) {
          this.pageInfo = packageFiles.pageInfo;
        }
      },
      error(error) {
        this.fetchPackageFilesError = true;
        Sentry.captureException(error);
      },
    },
  },
  data() {
    return {
      fetchPackageFilesError: false,
      filesToDelete: [],
      packageFiles: [],
      mutationLoading: false,
      selectedReferences: [],
      pageInfo: {},
    };
  },
  computed: {
    areFilesSelected() {
      return this.selectedReferences.length > 0;
    },
    areAllFilesSelected() {
      return this.packageFiles.length > 0 && this.packageFiles.every(this.isSelected);
    },
    filesTableRows() {
      return this.packageFiles.map((pf) => ({
        ...pf,
        size: this.formatSize(pf.size),
      }));
    },
    hasSelectedSomeFiles() {
      return this.areFilesSelected && !this.areAllFilesSelected;
    },
    isLoading() {
      return this.$apollo.queries.packageFiles.loading || this.mutationLoading;
    },
    filesTableHeaderFields() {
      return [
        {
          key: 'checkbox',
          label: __('Select all'),
          thClass: 'gl-w-4',
          hide: !this.canDelete,
        },
        {
          key: 'name',
          label: __('Name'),
        },
        {
          key: 'size',
          label: __('Size'),
        },
        {
          key: 'created',
          label: __('Created'),
        },
        {
          key: 'actions',
          label: '',
          hide: !this.canDelete,
          thClass: 'gl-w-4',
        },
      ].filter((c) => !c.hide);
    },
    queryVariables() {
      return {
        id: this.packageId,
        first: GRAPHQL_PACKAGE_FILES_PAGE_SIZE,
      };
    },
    tracking() {
      return {
        category: packageTypeToTrackCategory(this.packageType),
      };
    },
    refetchQueriesData() {
      return [
        {
          query: getPackageFilesQuery,
          variables: this.queryVariables,
        },
      ];
    },
    modalAction() {
      return this.hasOneItem(this.filesToDelete)
        ? this.$options.modal.fileDeletePrimaryAction
        : this.$options.modal.filesDeletePrimaryAction;
    },
    modalTitle() {
      return this.hasOneItem(this.filesToDelete)
        ? this.$options.i18n.deleteFileModalTitle
        : this.$options.i18n.deleteFilesModalTitle;
    },
    modalDescription() {
      return this.hasOneItem(this.filesToDelete)
        ? this.$options.i18n.deleteFileModalContent
        : this.$options.i18n.deleteFilesModalContent;
    },
  },
  methods: {
    formatSize(size) {
      return numberToHumanSize(size);
    },
    hasDetails(item) {
      return item.fileSha256 || item.fileMd5 || item.fileSha1;
    },
    trackToggleDetails(detailsShowing) {
      if (!detailsShowing) {
        this.track(TRACKING_ACTION_EXPAND_PACKAGE_ASSET, { label: TRACKING_LABEL_PACKAGE_ASSET });
      }
    },
    updateSelectedReferences(selection) {
      this.track(SELECT_PACKAGE_FILE_TRACKING_ACTION);
      this.selectedReferences = selection;
    },
    isSelected(packageFile) {
      return this.selectedReferences.find((reference) => reference.id === packageFile.id);
    },
    handleFileDeleteSelected() {
      this.track(REQUEST_DELETE_SELECTED_PACKAGE_FILE_TRACKING_ACTION);
      this.handleFileDelete(this.selectedReferences);
    },
    async deletePackageFiles(ids) {
      this.mutationLoading = true;
      try {
        const { data } = await this.$apollo.mutate({
          mutation: destroyPackageFilesMutation,
          variables: {
            projectPath: this.projectPath,
            ids,
          },
          awaitRefetchQueries: true,
          refetchQueries: this.refetchQueriesData,
        });
        Iif (data?.destroyPackageFiles?.errors[0]) {
          throw data.destroyPackageFiles.errors[0];
        }
        createAlert({
          message: this.hasOneItem(ids)
            ? DELETE_PACKAGE_FILE_SUCCESS_MESSAGE
            : DELETE_PACKAGE_FILES_SUCCESS_MESSAGE,
          variant: VARIANT_SUCCESS,
        });
      } catch (error) {
        createAlert({
          message: this.hasOneItem(ids)
            ? DELETE_PACKAGE_FILE_ERROR_MESSAGE
            : DELETE_PACKAGE_FILES_ERROR_MESSAGE,
          variant: VARIANT_WARNING,
          captureError: true,
          error,
        });
      } finally {
        this.mutationLoading = false;
        this.filesToDelete = [];
        this.selectedReferences = [];
      }
    },
    handleFileDelete(files) {
      this.track(REQUEST_DELETE_PACKAGE_FILE_TRACKING_ACTION);
      if (files.length === this.packageFiles.length && !this.pageInfo.hasNextPage) {
        this.$emit(
          'delete-all-files',
          this.hasOneItem(files)
            ? DELETE_LAST_PACKAGE_FILE_MODAL_CONTENT
            : DELETE_ALL_PACKAGE_FILES_MODAL_CONTENT,
        );
      } else {
        this.filesToDelete = files;
        this.$refs.deleteFilesModal.show();
      }
    },
    hasOneItem(items) {
      return items.length === 1;
    },
    confirmFilesDelete() {
      if (this.hasOneItem(this.filesToDelete)) {
        this.track(DELETE_PACKAGE_FILE_TRACKING_ACTION);
      } else {
        this.track(DELETE_PACKAGE_FILES_TRACKING_ACTION);
      }
      this.deletePackageFiles(this.filesToDelete.map((file) => file.id));
    },
    fetchPreviousFilesPage() {
      return this.$apollo.queries.packageFiles
        .fetchMore({
          variables: {
            first: null,
            last: GRAPHQL_PACKAGE_FILES_PAGE_SIZE,
            before: this.pageInfo.startCursor,
          },
        })
        .then(() => {
          this.scrollAndFocus();
        });
    },
    fetchNextFilesPage() {
      return this.$apollo.queries.packageFiles
        .fetchMore({
          variables: {
            first: GRAPHQL_PACKAGE_FILES_PAGE_SIZE,
            last: null,
            after: this.pageInfo.endCursor,
          },
        })
        .then(() => {
          this.scrollAndFocus();
        });
    },
    scrollAndFocus() {
      scrollToElement(this.$el);
 
      // get first focusable row
      const focusable = this.$el.querySelector('tbody tr');
      if (focusable) {
        focusable.focus();
      }
    },
  },
  i18n: {
    deleteFile: s__('PackageRegistry|Delete asset'),
    deleteFileModalTitle: s__('PackageRegistry|Delete package asset'),
    deleteFileModalContent: s__(
      'PackageRegistry|You are about to delete %{filename}. This is a destructive action that may render your package unusable. Are you sure?',
    ),
    deleteFilesModalTitle: s__('PackageRegistry|Delete %{count} assets'),
    deleteFilesModalContent: s__(
      'PackageRegistry|You are about to delete %{count} assets. This operation is irreversible.',
    ),
    deleteSelected: s__('PackageRegistry|Delete selected'),
    moreActionsText: __('More actions'),
    fetchPackageFilesErrorMessage: FETCH_PACKAGE_FILES_ERROR_MESSAGE,
    prev: PREV,
    next: NEXT,
  },
  modal: {
    fileDeletePrimaryAction: {
      text: __('Delete'),
      attributes: { variant: 'danger', category: 'primary' },
    },
    filesDeletePrimaryAction: {
      text: s__('PackageRegistry|Permanently delete assets'),
      attributes: { variant: 'danger', category: 'primary' },
    },
    cancelAction: {
      text: __('Cancel'),
    },
  },
};
</script>
 
<template>
  <div class="gl-pt-6">
    <div class="gl-display-flex gl-align-items-center gl-justify-content-space-between">
      <h3 class="gl-font-lg gl-mt-5">{{ __('Assets') }}</h3>
      <gl-button
        v-if="!fetchPackageFilesError && canDelete"
        :disabled="isLoading || !areFilesSelected"
        category="secondary"
        variant="danger"
        data-testid="delete-selected"
        @click="handleFileDeleteSelected"
      >
        {{ $options.i18n.deleteSelected }}
      </gl-button>
    </div>
    <gl-alert
      v-if="fetchPackageFilesError"
      variant="danger"
      @dismiss="fetchPackageFilesError = false"
    >
      {{ $options.i18n.fetchPackageFilesErrorMessage }}
    </gl-alert>
    <template v-else>
      <gl-table
        ref="table"
        :busy="isLoading"
        :fields="filesTableHeaderFields"
        :items="filesTableRows"
        show-empty
        selectable
        select-mode="multi"
        selected-variant="primary"
        :tbody-tr-attr="{ 'data-testid': 'file-row' }"
        @row-selected="updateSelectedReferences"
      >
        <template #table-busy>
          <gl-loading-icon size="lg" class="gl-my-5" />
        </template>
        <template #head(checkbox)="{ selectAllRows, clearSelected }">
          <gl-form-checkbox
            v-if="canDelete"
            class="gl-min-h-0"
            data-testid="package-files-checkbox-all"
            :checked="areAllFilesSelected"
            :indeterminate="hasSelectedSomeFiles"
            @change="areAllFilesSelected ? clearSelected() : selectAllRows()"
          />
        </template>
 
        <template #cell(checkbox)="{ rowSelected, selectRow, unselectRow }">
          <gl-form-checkbox
            v-if="canDelete"
            :checked="rowSelected"
            data-testid="package-files-checkbox"
            @change="rowSelected ? unselectRow() : selectRow()"
          />
        </template>
 
        <template #cell(name)="{ item, toggleDetails, detailsShowing }">
          <gl-button
            v-if="hasDetails(item)"
            :icon="detailsShowing ? 'chevron-up' : 'chevron-down'"
            :aria-label="detailsShowing ? __('Collapse') : __('Expand')"
            data-testid="toggle-details-button"
            category="tertiary"
            class="gl-mt-n2!"
            size="small"
            @click="
              toggleDetails();
              trackToggleDetails(detailsShowing);
            "
          />
          <gl-link
            :href="item.downloadPath"
            class="gl-text-gray-500"
            data-testid="download-link"
            @click="track($options.trackingActions.DOWNLOAD_PACKAGE_ASSET_TRACKING_ACTION)"
          >
            <file-icon
              :file-name="item.fileName"
              css-classes="gl-relative file-icon"
              class="gl-mr-1 gl-relative"
            />
            <span>{{ item.fileName }}</span>
          </gl-link>
        </template>
 
        <template #cell(created)="{ item }">
          <time-ago-tooltip :time="item.createdAt" />
        </template>
 
        <template #cell(actions)="{ item }">
          <gl-disclosure-dropdown
            category="tertiary"
            icon="ellipsis_v"
            placement="right"
            :toggle-text="$options.i18n.moreActionsText"
            text-sr-only
            no-caret
          >
            <gl-disclosure-dropdown-item
              data-testid="delete-file"
              @action="handleFileDelete([item])"
            >
              <template #list-item>
                {{ $options.i18n.deleteFile }}
              </template>
            </gl-disclosure-dropdown-item>
          </gl-disclosure-dropdown>
        </template>
 
        <template #row-details="{ item }">
          <div
            class="gl-display-flex gl-flex-direction-column gl-flex-grow-1 gl-bg-gray-10 gl-rounded-base gl-inset-border-1-gray-100"
          >
            <file-sha
              v-if="item.fileSha256"
              data-testid="sha-256"
              title="SHA-256"
              :sha="item.fileSha256"
            />
            <file-sha v-if="item.fileMd5" data-testid="md5" title="MD5" :sha="item.fileMd5" />
            <file-sha v-if="item.fileSha1" data-testid="sha-1" title="SHA-1" :sha="item.fileSha1" />
          </div>
        </template>
      </gl-table>
      <div class="gl-display-flex gl-justify-content-center">
        <gl-keyset-pagination
          :disabled="isLoading"
          v-bind="pageInfo"
          :prev-text="$options.i18n.prev"
          :next-text="$options.i18n.next"
          class="gl-mt-3"
          @prev="fetchPreviousFilesPage"
          @next="fetchNextFilesPage"
        />
      </div>
    </template>
 
    <gl-modal
      ref="deleteFilesModal"
      size="sm"
      modal-id="delete-files-modal"
      :action-primary="modalAction"
      :action-cancel="$options.modal.cancelAction"
      data-testid="delete-files-modal"
      @primary="confirmFilesDelete"
      @canceled="track($options.trackingActions.CANCEL_DELETE_PACKAGE_FILE)"
    >
      <template #modal-title>
        <gl-sprintf :message="modalTitle">
          <template #count>
            {{ filesToDelete.length }}
          </template>
        </gl-sprintf>
      </template>
 
      <gl-sprintf :message="modalDescription">
        <template #filename>
          <strong>{{ filesToDelete[0].fileName }}</strong>
        </template>
 
        <template #count>
          {{ filesToDelete.length }}
        </template>
      </gl-sprintf>
    </gl-modal>
  </div>
</template>