All files / app/assets/javascripts/notes/components noteable_note.vue

58.26% Statements 67/115
68.33% Branches 41/60
73.68% Functions 28/38
60.74% Lines 65/107

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 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549        15x                                                                                                                                                                                                                           136x                         142x           171x                   149x     142x     153x     136x     136x                                   10x     142x   33x     33x     33x     2x     142x         140x   2x                 136x 9x 9x     136x 7x     136x     142x 142x       136x   136x                                     136x                                 5x 5x 5x                                                                         6x 6x 6x   6x     10x       10x               10x                   10x   10x 1x             9x                     9x 9x 9x   9x   9x   6x 6x     3x         3x 3x 3x 3x 3x 3x 3x                             1x                         1x 1x 1x     4x   4x       2x                                                                                                                                                                                                                                                                                
<script>
import { GlSprintf, GlAvatarLink, GlAvatar } from '@gitlab/ui';
import $ from 'jquery';
import { escape, isEmpty } from 'lodash';
// eslint-disable-next-line no-restricted-imports
import { mapGetters, mapActions } from 'vuex';
import SafeHtml from '~/vue_shared/directives/safe_html';
import { confirmAction } from '~/lib/utils/confirm_via_gl_modal/confirm_via_gl_modal';
import { INLINE_DIFF_LINES_KEY } from '~/diffs/constants';
import { createAlert } from '~/alert';
import { HTTP_STATUS_GONE } from '~/lib/utils/http_status';
import { ignoreWhilePending } from '~/lib/utils/ignore_while_pending';
import { truncateSha } from '~/lib/utils/text_utility';
import TimelineEntryItem from '~/vue_shared/components/notes/timeline_entry_item.vue';
import { __, s__, sprintf } from '~/locale';
import { renderGFM } from '~/behaviors/markdown/render_gfm';
import { containsSensitiveToken, confirmSensitiveAction } from '~/lib/utils/secret_detection';
import eventHub from '../event_hub';
import noteable from '../mixins/noteable';
import resolvable from '../mixins/resolvable';
import { renderMarkdown, updateNoteErrorMessage } from '../utils';
import {
  getStartLineNumber,
  getEndLineNumber,
  getLineClasses,
  commentLineOptions,
  formatLineRange,
} from './multiline_comment_utils';
import NoteActions from './note_actions.vue';
import NoteBody from './note_body.vue';
import NoteHeader from './note_header.vue';
 
export default {
  name: 'NoteableNote',
  components: {
    GlSprintf,
    NoteHeader,
    NoteActions,
    NoteBody,
    TimelineEntryItem,
    GlAvatarLink,
    GlAvatar,
  },
  directives: {
    SafeHtml,
  },
  mixins: [noteable, resolvable],
  inject: {
    reportAbusePath: {
      default: '',
    },
  },
  props: {
    note: {
      type: Object,
      required: true,
    },
    line: {
      type: Object,
      required: false,
      default: null,
    },
    discussionFile: {
      type: Object,
      required: false,
      default: null,
    },
    helpPagePath: {
      type: String,
      required: false,
      default: '',
    },
    commit: {
      type: Object,
      required: false,
      default: () => null,
    },
    showReplyButton: {
      type: Boolean,
      required: false,
      default: false,
    },
    diffLines: {
      type: Array,
      required: false,
      default: null,
    },
    discussionRoot: {
      type: Boolean,
      required: false,
      default: false,
    },
    discussionResolvePath: {
      type: String,
      required: false,
      default: '',
    },
    isOverviewTab: {
      type: Boolean,
      required: false,
      default: false,
    },
    shouldScrollToNote: {
      type: Boolean,
      required: false,
      default: true,
    },
    discussion: {
      type: Object,
      required: false,
      default: null,
    },
  },
  data() {
    return {
      isEditing: false,
      isDeleting: false,
      isRequesting: false,
      isResolving: false,
      commentLineStart: {},
      resolveAsThread: true,
    };
  },
  computed: {
    ...mapGetters('diffs', ['getDiffFileByHash']),
    ...mapGetters(['targetNoteHash', 'getNoteableData', 'getUserData', 'commentsDisabled']),
    author() {
      return this.note.author;
    },
    commentType() {
      return this.note.internal ? __('internal note') : __('comment');
    },
    classNameBindings() {
      return {
        [`note-row-${this.note.id}`]: true,
        'is-editing': this.isEditing && !this.isRequesting,
        'is-requesting being-posted': this.isRequesting,
        'disabled-content': this.isDeleting,
        target: this.isTarget,
        'is-editable': this.note.current_user.can_edit,
      };
    },
    canReportAsAbuse() {
      return Boolean(this.reportAbusePath) && this.author.id !== this.getUserData.id;
    },
    noteAnchorId() {
      return `note_${this.note.id}`;
    },
    isTarget() {
      return this.targetNoteHash === this.noteAnchorId;
    },
    discussionId() {
      Iif (this.discussion) {
        return this.discussion.id;
      }
      return '';
    },
    actionText() {
      Iif (!this.commit) {
        return '';
      }
 
      // We need to do this to ensure we have the correct sentence order
      // when translating this as the sentence order may change from one
      // language to the next. See:
      // https://gitlab.com/gitlab-org/gitlab-foss/merge_requests/24427#note_133713771
      const { id, url } = this.commit;
      const commitLink = `<a class="commit-sha monospace" href="${escape(url)}">${truncateSha(
        id,
      )}</a>`;
      return sprintf(s__('MergeRequests|commented on commit %{commitLink}'), { commitLink }, false);
    },
    isDraft() {
      return this.note.isDraft;
    },
    canResolve() {
      if (!this.discussionRoot) return false;
 
      return this.note.current_user.can_resolve_discussion;
    },
    lineRange() {
      return this.note.position?.line_range;
    },
    startLineNumber() {
      return getStartLineNumber(this.lineRange);
    },
    endLineNumber() {
      return getEndLineNumber(this.lineRange);
    },
    showMultiLineComment() {
      if (
        !this.discussionRoot ||
        this.startLineNumber.length === 0 ||
        this.endLineNumber.length === 0
      )
        return false;
 
      return this.line && this.startLineNumber !== this.endLineNumber;
    },
    commentLineOptions() {
      const lines = this.diffFile[INLINE_DIFF_LINES_KEY].length;
      return commentLineOptions(lines, this.commentLineStart, this.line.line_code);
    },
    diffFile() {
      let fileResolvedFromAvailableSource;
 
      if (this.commentLineStart.line_code) {
        const lineCode = this.commentLineStart.line_code.split('_')[0];
        fileResolvedFromAvailableSource = this.getDiffFileByHash(lineCode);
      }
 
      if (!fileResolvedFromAvailableSource && this.discussionFile) {
        fileResolvedFromAvailableSource = this.discussionFile;
      }
 
      return fileResolvedFromAvailableSource || null;
    },
    isMRDiffView() {
      const isFileComment = this.note.position?.position_type === 'file';
      return !this.isOverviewTab && (this.line || isFileComment);
    },
  },
  created() {
    const line = this.note.position?.line_range?.start || this.line;
 
    this.commentLineStart = line
      ? {
          line_code: line.line_code,
          type: line.type,
          old_line: line.old_line,
          new_line: line.new_line,
        }
      : {};
 
    eventHub.$on('enterEditMode', ({ noteId }) => {
      Iif (noteId === this.note.id) {
        this.isEditing = true;
        this.setSelectedCommentPositionHover();
        this.scrollToNoteIfNeeded($(this.$el));
      }
    });
  },
 
  mounted() {
    Iif (this.isTarget && this.shouldScrollToNote) {
      this.scrollToNoteIfNeeded($(this.$el));
    }
  },
 
  methods: {
    ...mapActions([
      'deleteNote',
      'removeNote',
      'updateNote',
      'toggleResolveNote',
      'scrollToNoteIfNeeded',
      'updateAssignees',
      'setSelectedCommentPositionHover',
      'updateDiscussionPosition',
    ]),
    editHandler() {
      this.isEditing = true;
      this.setSelectedCommentPositionHover();
      this.$emit('handleEdit');
    },
    async deleteHandler() {
      let { commentType } = this;
 
      Iif (this.note.isDraft) {
        // Draft internal notes (i.e. MR review comments) are not supported.
        commentType = __('pending comment');
      }
 
      const msg = sprintf(__('Are you sure you want to delete this %{commentType}?'), {
        commentType,
      });
      const confirmed = await confirmAction(msg, {
        primaryBtnVariant: 'danger',
        primaryBtnText: this.note.internal ? __('Delete internal note') : __('Delete comment'),
      });
 
      Iif (confirmed) {
        this.isDeleting = true;
        this.$emit('handleDeleteNote', this.note);
 
        Iif (this.note.isDraft) return;
 
        this.deleteNote(this.note)
          .then(() => {
            this.isDeleting = false;
          })
          .catch(() => {
            createAlert({
              message: __('Something went wrong while deleting your note. Please try again.'),
            });
            this.isDeleting = false;
          });
      }
    },
    updateSuccess() {
      this.isEditing = false;
      this.isRequesting = false;
      this.oldContent = null;
      renderGFM(this.$refs.noteBody.$el);
      this.$emit('updateSuccess');
    },
    async formUpdateHandler({ noteText, callback, resolveDiscussion }) {
      const position = {
        ...this.note.position,
      };
 
      Iif (this.discussionRoot && this.commentLineStart && this.line) {
        position.line_range = formatLineRange(this.commentLineStart, this.line);
        this.updateDiscussionPosition({
          discussionId: this.note.discussion_id,
          position,
        });
      }
 
      this.$emit('handleUpdateNote', {
        note: this.note,
        noteText,
        resolveDiscussion,
        position,
        flashContainer: this.$el,
        callback: () => this.updateSuccess(),
        errorCallback: () => callback(),
      });
 
      Iif (this.isDraft) return;
 
      if (containsSensitiveToken(noteText)) {
        const confirmed = await confirmSensitiveAction();
        Iif (!confirmed) {
          callback();
          return;
        }
      }
 
      const data = {
        endpoint: this.note.path,
        note: {
          target_type: this.getNoteableData.targetType,
          target_id: this.note.noteable_id,
          note: { note: noteText },
        },
      };
 
      // Stringifying an empty object yields `{}` which breaks graphql queries
      // https://gitlab.com/gitlab-org/gitlab/-/issues/298827
      if (!isEmpty(position)) data.note.note.position = JSON.stringify(position);
      this.isRequesting = true;
      this.oldContent = this.note.note_html;
      // eslint-disable-next-line vue/no-mutating-props
      this.note.note_html = renderMarkdown(noteText);
 
      this.updateNote(data)
        .then(() => {
          this.updateSuccess();
          callback();
        })
        .catch((e) => {
          Iif (e.status === HTTP_STATUS_GONE) {
            this.removeNote(this.note);
            this.updateSuccess();
            callback();
          } else {
            this.isRequesting = false;
            this.isEditing = true;
            this.setSelectedCommentPositionHover();
            this.$nextTick(() => {
              this.handleUpdateError(e); // The 'e' parameter is being used in JH, don't remove it
              this.recoverNoteContent();
              callback();
            });
          }
        });
    },
    handleUpdateError(e) {
      createAlert({
        message: updateNoteErrorMessage(e),
        parent: this.$el,
      });
    },
    formCancelHandler: ignoreWhilePending(async function formCancelHandler({
      shouldConfirm,
      isDirty,
    }) {
      Iif (shouldConfirm && isDirty) {
        const msg = sprintf(__('Are you sure you want to cancel editing this %{commentType}?'), {
          commentType: this.commentType,
        });
        const confirmed = await confirmAction(msg, {
          primaryBtnText: __('Cancel editing'),
          primaryBtnVariant: 'danger',
          secondaryBtnVariant: 'default',
          secondaryBtnText: __('Continue editing'),
          hideCancel: true,
        });
        Iif (!confirmed) return;
      }
      this.recoverNoteContent();
      this.isEditing = false;
      this.$emit('cancelForm');
    }),
    recoverNoteContent() {
      if (this.oldContent) {
        // eslint-disable-next-line vue/no-mutating-props
        this.note.note_html = this.oldContent;
      }
    },
    getLineClasses(lineNumber) {
      return getLineClasses(lineNumber);
    },
    assigneesUpdate(assignees) {
      this.updateAssignees(assignees);
    },
  },
};
</script>
 
<template>
  <timeline-entry-item
    :id="noteAnchorId"
    :class="{ ...classNameBindings, 'internal-note': note.internal }"
    :data-award-url="note.toggle_award_path"
    :data-note-id="note.id"
    class="note note-wrapper note-comment"
    data-testid="noteable-note-container"
  >
    <div
      v-if="showMultiLineComment"
      data-testid="multiline-comment"
      class="gl-text-gray-500 gl-border-gray-100 gl-border-b-solid gl-border-b-1 gl-px-5 gl-py-3"
    >
      <gl-sprintf :message="__('Comment on lines %{startLine} to %{endLine}')">
        <template #startLine>
          <span :class="getLineClasses(startLineNumber)">{{ startLineNumber }}</span>
        </template>
        <template #endLine>
          <span :class="getLineClasses(endLineNumber)">{{ endLineNumber }}</span>
        </template>
      </gl-sprintf>
    </div>
 
    <div v-if="isMRDiffView" class="timeline-avatar gl-float-left gl-pt-2">
      <gl-avatar-link
        :href="author.path"
        :data-user-id="author.id"
        :data-username="author.username"
        class="js-user-link"
      >
        <gl-avatar
          :src="author.avatar_url"
          :entity-name="author.username"
          :alt="author.name"
          :size="24"
        />
 
        <slot name="avatar-badge"></slot>
      </gl-avatar-link>
    </div>
 
    <div v-else class="timeline-avatar gl-float-left">
      <gl-avatar-link
        :href="author.path"
        :data-user-id="author.id"
        :data-username="author.username"
        class="js-user-link gl-relative"
      >
        <gl-avatar
          :src="author.avatar_url"
          :entity-name="author.username"
          :alt="author.name"
          :size="32"
        />
 
        <slot name="avatar-badge"></slot>
      </gl-avatar-link>
    </div>
 
    <div class="timeline-content">
      <div class="note-header">
        <note-header
          :author="author"
          :created-at="note.created_at"
          :note-id="note.id"
          :is-internal-note="note.internal"
          :noteable-type="noteableType"
          :email-participant="note.external_author"
        >
          <template #note-header-info>
            <slot name="note-header-info"></slot>
          </template>
          <span v-if="commit" v-safe-html="actionText"></span>
          <span v-else-if="note.created_at" class="d-none d-sm-inline">&middot;</span>
        </note-header>
        <note-actions
          :author="author"
          :author-id="author.id"
          :note-id="note.id"
          :note-url="note.noteable_note_url"
          :access-level="note.human_access"
          :is-contributor="note.is_contributor"
          :is-author="note.is_noteable_author"
          :project-name="note.project_name"
          :noteable-type="note.noteable_type"
          :show-reply="showReplyButton"
          :can-edit="note.current_user.can_edit"
          :can-award-emoji="note.current_user.can_award_emoji"
          :can-delete="note.current_user.can_edit"
          :can-report-as-abuse="canReportAsAbuse"
          :can-resolve="canResolve"
          :resolvable="note.resolvable || note.isDraft"
          :is-resolved="note.resolved || note.resolve_discussion"
          :is-resolving="isResolving"
          :resolved-by="note.resolved_by"
          :is-draft="note.isDraft"
          :resolve-discussion="note.isDraft && note.resolve_discussion"
          :discussion-id="discussionId"
          :award-path="note.toggle_award_path"
          @handleEdit="editHandler"
          @handleDelete="deleteHandler"
          @handleResolve="resolveHandler"
          @startReplying="$emit('startReplying')"
          @updateAssignees="assigneesUpdate"
        />
      </div>
      <div class="timeline-discussion-body">
        <slot name="discussion-resolved-text"></slot>
        <note-body
          ref="noteBody"
          :note="note"
          :can-edit="note.current_user.can_edit"
          :line="line"
          :file="diffFile"
          :is-editing="isEditing"
          :help-page-path="helpPagePath"
          @handleFormUpdate="formUpdateHandler"
          @cancelForm="formCancelHandler"
        />
        <div class="timeline-discussion-body-footer">
          <slot name="after-note-body"></slot>
        </div>
      </div>
    </div>
  </timeline-entry-item>
</template>