All files / app/assets/javascripts/diffs/components diff_line_note_form.vue

75.8% Statements 47/62
70% Branches 21/30
80.95% Functions 17/21
78.57% Lines 44/56

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    9x                                                                                                                 26x                                                         6x                     26x     26x                           26x 26x       26x   26x 26x 26x     26x 26x 26x 26x   26x 40x   40x 20x     40x 39x 39x     39x 20x         26x     26x               20x   20x                       26x 19x 7x 7x       26x 1x                         7x 4x   4x         4x 2x     5x                 6x     4x 4x                 4x                                                                                
<script>
import { nextTick } from 'vue';
// eslint-disable-next-line no-restricted-imports
import { mapState, mapGetters, mapActions } from 'vuex';
import { s__, __, sprintf } from '~/locale';
import { createAlert } from '~/alert';
import diffLineNoteFormMixin from '~/notes/mixins/diff_line_note_form';
import { clearDraft } from '~/lib/utils/autosave';
import { confirmAction } from '~/lib/utils/confirm_via_gl_modal/confirm_via_gl_modal';
import { ignoreWhilePending } from '~/lib/utils/ignore_while_pending';
import glFeatureFlagsMixin from '~/vue_shared/mixins/gl_feature_flags_mixin';
import MultilineCommentForm from '~/notes/components/multiline_comment_form.vue';
import { commentLineOptions, formatLineRange } from '~/notes/components/multiline_comment_utils';
import NoteForm from '~/notes/components/note_form.vue';
import { capitalizeFirstCharacter } from '~/lib/utils/text_utility';
import {
  DIFF_NOTE_TYPE,
  INLINE_DIFF_LINES_KEY,
  PARALLEL_DIFF_VIEW_TYPE,
  OLD_LINE_TYPE,
} from '../constants';
import { SAVING_THE_COMMENT_FAILED, SOMETHING_WENT_WRONG } from '../i18n';
 
export default {
  components: {
    NoteForm,
    MultilineCommentForm,
  },
  mixins: [diffLineNoteFormMixin, glFeatureFlagsMixin()],
  props: {
    diffFileHash: {
      type: String,
      required: true,
    },
    line: {
      type: Object,
      required: true,
    },
    range: {
      type: Object,
      required: false,
      default: null,
    },
    linePosition: {
      type: String,
      required: false,
      default: '',
    },
    noteTargetLine: {
      type: Object,
      required: true,
    },
    helpPagePath: {
      type: String,
      required: false,
      default: '',
    },
  },
  data() {
    return {
      lines: null,
      commentLineStart: {
        line_code: this.line.line_code,
        type: this.line.type,
        old_line: this.line.old_line,
        new_line: this.line.new_line,
      },
    };
  },
  computed: {
    ...mapState({
      diffViewType: ({ diffs }) => diffs.diffViewType,
      showSuggestPopover: ({ diffs }) => diffs.showSuggestPopover,
      noteableData: ({ notes }) => notes.noteableData,
      selectedCommentPosition: ({ notes }) => notes.selectedCommentPosition,
    }),
    ...mapGetters('diffs', ['getDiffFileByHash', 'diffLines']),
    ...mapGetters([
      'isLoggedIn',
      'noteableType',
      'getNoteableData',
      'getNotesDataByProp',
      'getUserData',
    ]),
    author() {
      return this.getUserData;
    },
    formData() {
      return {
        noteableData: this.noteableData,
        noteableType: this.noteableType,
        noteTargetLine: this.noteTargetLine,
        diffViewType: this.diffViewType,
        diffFile: this.diffFile,
        linePosition: this.linePosition,
        lineRange: formatLineRange(this.commentLineStart, this.line),
      };
    },
    diffFile() {
      return this.getDiffFileByHash(this.diffFileHash);
    },
    commentLineOptions() {
      const combineSides = (acc, { left, right }) => {
        // ignore null values match lines
        Iif (left) acc.push(left);
        // if the line_codes are identically, return to avoid duplicates
        Iif (
          left?.line_code === right?.line_code ||
          left?.type === 'old-nonewline' ||
          right?.type === 'new-nonewline'
        ) {
          return acc;
        }
        Iif (right && right.type !== 'match') acc.push(right);
        return acc;
      };
      const getDiffLines = () => {
        Iif (this.diffViewType === PARALLEL_DIFF_VIEW_TYPE) {
          return this.diffLines(this.diffFile).reduce(combineSides, []);
        }
 
        return this.diffFile[INLINE_DIFF_LINES_KEY];
      };
      const side = this.line.type === 'new' ? 'right' : 'left';
      const lines = getDiffLines();
      return commentLineOptions(lines, this.line, this.line.line_code, side);
    },
    commentLines() {
      const lines = [];
      const { start, end } = this.lines;
      const diffLines = this.diffFile[INLINE_DIFF_LINES_KEY];
      let isAdding = false;
 
      for (let i = 0, diffLinesLength = diffLines.length - 1; i <= diffLinesLength; i += 1) {
        const line = diffLines[i];
 
        if (start.line_code === line.line_code) {
          isAdding = true;
        }
 
        if (isAdding) {
          if (line.type !== OLD_LINE_TYPE) {
            lines.push(line);
          }
 
          if (end.line_code === line.line_code) {
            break;
          }
        }
      }
 
      return lines;
    },
    autosaveKey() {
      if (!this.isLoggedIn) return '';
 
      const {
        id,
        noteable_type: noteableTypeUnderscored,
        noteableType,
        diff_head_sha: diffHeadSha,
        source_project_id: sourceProjectId,
      } = this.noteableData;
 
      return [
        s__('Autosave|Note'),
        capitalizeFirstCharacter(noteableTypeUnderscored || noteableType),
        id,
        diffHeadSha,
        DIFF_NOTE_TYPE,
        sourceProjectId,
        this.line.line_code,
      ].join('/');
    },
  },
  created() {
    if (this.range) {
      this.lines = { ...this.range };
    } else if (this.line) {
      this.lines = { start: this.line, end: this.line };
    }
  },
  mounted() {
    if (this.selectedCommentPosition) {
      this.commentLineStart = this.selectedCommentPosition.start;
    }
  },
  methods: {
    ...mapActions('diffs', [
      'cancelCommentForm',
      'saveDiffDiscussion',
      'setSuggestPopoverDismissed',
    ]),
    handleCancelCommentForm: ignoreWhilePending(async function handleCancelCommentForm(
      shouldConfirm,
      isDirty,
    ) {
      if (shouldConfirm && isDirty) {
        const msg = s__('Notes|Are you sure you want to cancel creating this comment?');
 
        const confirmed = await confirmAction(msg, {
          primaryBtnText: __('Discard changes'),
          cancelBtnText: __('Continue editing'),
        });
 
        if (!confirmed) {
          return;
        }
      }
      this.cancelCommentForm({
        lineCode: this.line.line_code,
        fileHash: this.diffFileHash,
      });
      nextTick(() => {
        clearDraft(this.autosaveKey);
      });
    }),
    handleSaveNote(note, parentElement, errorCallback) {
      return this.saveDiffDiscussion({ note, formData: this.formData })
        .then(() => this.handleCancelCommentForm())
        .catch((e) => {
          const reason = e.response?.data?.errors;
          const errorMessage = reason
            ? sprintf(SAVING_THE_COMMENT_FAILED, { reason })
            : SOMETHING_WENT_WRONG;
 
          createAlert({
            message: errorMessage,
            parent: parentElement,
          });
 
          errorCallback();
        });
    },
    updateStartLine(line) {
      this.commentLineStart = line;
      this.lines.start = line;
    },
  },
};
</script>
 
<template>
  <div class="content discussion-form discussion-form-container discussion-notes">
    <div class="gl-mb-3 gl-text-gray-500 gl-pb-3">
      <multiline-comment-form
        :line="line"
        :line-range="lines"
        :comment-line-options="commentLineOptions"
        @input="updateStartLine"
      />
    </div>
    <note-form
      ref="noteForm"
      :line-code="line.line_code"
      :line="line"
      :lines="commentLines"
      :help-page-path="helpPagePath"
      :diff-file="diffFile"
      :show-suggest-popover="showSuggestPopover"
      :save-button-title="__('Comment')"
      :autosave-key="autosaveKey"
      :autofocus="false"
      class="diff-comment-form gl-mt-3"
      @handleFormUpdateAddToReview="addToReview"
      @cancelForm="handleCancelCommentForm"
      @handleFormUpdate="handleSaveNote"
      @handleSuggestDismissed="setSuggestPopoverDismissed"
    />
  </div>
</template>