summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/notes/components/comment_form.vue
blob: 1785be01a0d2850e3c613f78a55aca8538e08031 (plain)
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
<script>
  import $ from 'jquery';
  import { mapActions, mapGetters } from 'vuex';
  import _ from 'underscore';
  import Autosize from 'autosize';
  import { __, sprintf } from '~/locale';
  import Flash from '../../flash';
  import Autosave from '../../autosave';
  import TaskList from '../../task_list';
  import { capitalizeFirstCharacter, convertToCamelCase } from '../../lib/utils/text_utility';
  import * as constants from '../constants';
  import eventHub from '../event_hub';
  import issueWarning from '../../vue_shared/components/issue/issue_warning.vue';
  import markdownField from '../../vue_shared/components/markdown/field.vue';
  import userAvatarLink from '../../vue_shared/components/user_avatar/user_avatar_link.vue';
  import loadingButton from '../../vue_shared/components/loading_button.vue';
  import noteSignedOutWidget from './note_signed_out_widget.vue';
  import discussionLockedWidget from './discussion_locked_widget.vue';
  import issuableStateMixin from '../mixins/issuable_state';

  export default {
    name: 'CommentForm',
    components: {
      issueWarning,
      noteSignedOutWidget,
      discussionLockedWidget,
      markdownField,
      userAvatarLink,
      loadingButton,
    },
    mixins: [
      issuableStateMixin,
    ],
    props: {
      noteableType: {
        type: String,
        required: true,
      },
    },
    data() {
      return {
        note: '',
        noteType: constants.COMMENT,
        isSubmitting: false,
        isSubmitButtonDisabled: true,
      };
    },
    computed: {
      ...mapGetters([
        'getCurrentUserLastNote',
        'getUserData',
        'getNoteableData',
        'getNotesData',
        'openState',
      ]),
      noteableDisplayName() {
        return this.noteableType.replace(/_/g, ' ');
      },
      isLoggedIn() {
        return this.getUserData.id;
      },
      commentButtonTitle() {
        return this.noteType === constants.COMMENT ? 'Comment' : 'Start discussion';
      },
      isOpen() {
        return this.openState === constants.OPENED || this.openState === constants.REOPENED;
      },
      canCreateNote() {
        return this.getNoteableData.current_user.can_create_note;
      },
      issueActionButtonTitle() {
        const openOrClose = this.isOpen ? 'close' : 'reopen';

        if (this.note.length) {
          return sprintf(
            __('%{actionText} & %{openOrClose} %{noteable}'),
            {
              actionText: this.commentButtonTitle,
              openOrClose,
              noteable: this.noteableDisplayName,
            },
          );
        }

        return sprintf(
          __('%{openOrClose} %{noteable}'),
          {
            openOrClose: capitalizeFirstCharacter(openOrClose),
            noteable: this.noteableDisplayName,
          },
        );
      },
      actionButtonClassNames() {
        return {
          'btn-reopen': !this.isOpen,
          'btn-close': this.isOpen,
          'js-note-target-close': this.isOpen,
          'js-note-target-reopen': !this.isOpen,
        };
      },
      markdownDocsPath() {
        return this.getNotesData.markdownDocsPath;
      },
      quickActionsDocsPath() {
        return this.getNotesData.quickActionsDocsPath;
      },
      markdownPreviewPath() {
        return this.getNoteableData.preview_note_path;
      },
      author() {
        return this.getUserData;
      },
      canUpdateIssue() {
        return this.getNoteableData.current_user.can_update;
      },
      endpoint() {
        return this.getNoteableData.create_note_path;
      },
    },
    watch: {
      note(newNote) {
        this.setIsSubmitButtonDisabled(newNote, this.isSubmitting);
      },
      isSubmitting(newValue) {
        this.setIsSubmitButtonDisabled(this.note, newValue);
      },
    },
    mounted() {
      // jQuery is needed here because it is a custom event being dispatched with jQuery.
      $(document).on('issuable:change', (e, isClosed) => {
        this.toggleIssueLocalState(isClosed ? constants.CLOSED : constants.REOPENED);
      });

      this.initAutoSave();
      this.initTaskList();
    },
    methods: {
      ...mapActions([
        'saveNote',
        'stopPolling',
        'restartPolling',
        'removePlaceholderNotes',
        'closeIssue',
        'reopenIssue',
        'toggleIssueLocalState',
      ]),
      setIsSubmitButtonDisabled(note, isSubmitting) {
        if (!_.isEmpty(note) && !isSubmitting) {
          this.isSubmitButtonDisabled = false;
        } else {
          this.isSubmitButtonDisabled = true;
        }
      },
      handleSave(withIssueAction) {
        this.isSubmitting = true;

        if (this.note.length) {
          const noteData = {
            endpoint: this.endpoint,
            flashContainer: this.$el,
            data: {
              note: {
                noteable_type: this.noteableType,
                noteable_id: this.getNoteableData.id,
                note: this.note,
              },
            },
          };

          if (this.noteType === constants.DISCUSSION) {
            noteData.data.note.type = constants.DISCUSSION_NOTE;
          }
          this.note = ''; // Empty textarea while being requested. Repopulate in catch
          this.resizeTextarea();
          this.stopPolling();

          this.saveNote(noteData)
            .then((res) => {
              this.isSubmitting = false;
              this.restartPolling();

              if (res.errors) {
                if (res.errors.commands_only) {
                  this.discard();
                } else {
                  Flash(
                    'Something went wrong while adding your comment. Please try again.',
                    'alert',
                    this.$refs.commentForm,
                  );
                }
              } else {
                this.discard();
              }

              if (withIssueAction) {
                this.toggleIssueState();
              }
            })
            .catch(() => {
              this.isSubmitting = false;
              this.discard(false);
              const msg =
                `Your comment could not be submitted!
Please check your network connection and try again.`;
              Flash(msg, 'alert', this.$el);
              this.note = noteData.data.note.note; // Restore textarea content.
              this.removePlaceholderNotes();
            });
        } else {
          this.toggleIssueState();
        }
      },
      enableButton() {
        this.isSubmitting = false;
      },
      toggleIssueState() {
        if (this.isOpen) {
          this.closeIssue()
            .then(() => this.enableButton())
            .catch(() => {
              this.enableButton();
              Flash(
                sprintf(
                  __('Something went wrong while closing the %{issuable}. Please try again later'),
                  { issuable: this.noteableDisplayName },
                ),
              );
            });
        } else {
          this.reopenIssue()
            .then(() => this.enableButton())
            .catch(() => {
              this.enableButton();
              Flash(
                sprintf(
                  __('Something went wrong while reopening the %{issuable}. Please try again later'),
                  { issuable: this.noteableDisplayName },
                ),
              );
            });
        }
      },
      discard(shouldClear = true) {
        // `blur` is needed to clear slash commands autocomplete cache if event fired.
        // `focus` is needed to remain cursor in the textarea.
        this.$refs.textarea.blur();
        this.$refs.textarea.focus();

        if (shouldClear) {
          this.note = '';
          this.resizeTextarea();
          this.$refs.markdownField.previewMarkdown = false;
        }

        this.autosave.reset();
      },
      setNoteType(type) {
        this.noteType = type;
      },
      editCurrentUserLastNote() {
        if (this.note === '') {
          const lastNote = this.getCurrentUserLastNote;

          if (lastNote) {
            eventHub.$emit('enterEditMode', {
              noteId: lastNote.id,
            });
          }
        }
      },
      initAutoSave() {
        if (this.isLoggedIn) {
          const noteableType = capitalizeFirstCharacter(convertToCamelCase(this.noteableType));

          this.autosave = new Autosave(
            $(this.$refs.textarea),
            ['Note', noteableType, this.getNoteableData.id],
          );
        }
      },
      initTaskList() {
        return new TaskList({
          dataType: 'note',
          fieldName: 'note',
          selector: '.notes',
        });
      },
      resizeTextarea() {
        this.$nextTick(() => {
          Autosize.update(this.$refs.textarea);
        });
      },
    },
  };
</script>

<template>
  <div>
    <note-signed-out-widget v-if="!isLoggedIn" />
    <discussion-locked-widget
      issuable-type="issue"
      v-else-if="!canCreateNote"
    />
    <ul
      v-else
      class="notes notes-form timeline">
      <li class="timeline-entry">
        <div class="timeline-entry-inner">
          <div class="flash-container error-alert timeline-content"></div>
          <div class="timeline-icon hidden-xs hidden-sm">
            <user-avatar-link
              v-if="author"
              :link-href="author.path"
              :img-src="author.avatar_url"
              :img-alt="author.name"
              :img-size="40"
            />
          </div>
          <div class="timeline-content timeline-content-form">
            <form
              ref="commentForm"
              class="new-note common-note-form gfm-form js-main-target-form"
            >

              <div class="error-alert"></div>

              <issue-warning
                v-if="hasWarning(getNoteableData)"
                :is-locked="isLocked(getNoteableData)"
                :is-confidential="isConfidential(getNoteableData)"
              />

              <markdown-field
                :markdown-preview-path="markdownPreviewPath"
                :markdown-docs-path="markdownDocsPath"
                :quick-actions-docs-path="quickActionsDocsPath"
                :add-spacing-classes="false"
                ref="markdownField">
                <textarea
                  id="note-body"
                  name="note[note]"
                  class="note-textarea js-vue-comment-form
js-gfm-input js-autosize markdown-area js-vue-textarea"
                  data-supports-quick-actions="true"
                  aria-label="Description"
                  v-model="note"
                  ref="textarea"
                  slot="textarea"
                  :disabled="isSubmitting"
                  placeholder="Write a comment or drag your files here..."
                  @keydown.up="editCurrentUserLastNote()"
                  @keydown.meta.enter="handleSave()"
                  @keydown.ctrl.enter="handleSave()">
                </textarea>
              </markdown-field>
              <div class="note-form-actions">
                <div
                  class="pull-left btn-group
append-right-10 comment-type-dropdown js-comment-type-dropdown droplab-dropdown">
                  <button
                    @click.prevent="handleSave()"
                    :disabled="isSubmitButtonDisabled"
                    class="btn btn-create comment-btn js-comment-button js-comment-submit-button"
                    type="submit">
                    {{ __(commentButtonTitle) }}
                  </button>
                  <button
                    :disabled="isSubmitButtonDisabled"
                    name="button"
                    type="button"
                    class="btn comment-btn note-type-toggle js-note-new-discussion dropdown-toggle"
                    data-toggle="dropdown"
                    aria-label="Open comment type dropdown">
                    <i
                      aria-hidden="true"
                      class="fa fa-caret-down toggle-icon">
                    </i>
                  </button>

                  <ul class="note-type-dropdown dropdown-open-top dropdown-menu">
                    <li :class="{ 'droplab-item-selected': noteType === 'comment' }">
                      <button
                        type="button"
                        class="btn btn-transparent"
                        @click.prevent="setNoteType('comment')">
                        <i
                          aria-hidden="true"
                          class="fa fa-check icon">
                        </i>
                        <div class="description">
                          <strong>Comment</strong>
                          <p>
                            Add a general comment to this {{ noteableDisplayName }}.
                          </p>
                        </div>
                      </button>
                    </li>
                    <li class="divider droplab-item-ignore"></li>
                    <li :class="{ 'droplab-item-selected': noteType === 'discussion' }">
                      <button
                        type="button"
                        class="btn btn-transparent"
                        @click.prevent="setNoteType('discussion')">
                        <i
                          aria-hidden="true"
                          class="fa fa-check icon">
                        </i>
                        <div class="description">
                          <strong>Start discussion</strong>
                          <p>
                            Discuss a specific suggestion or question.
                          </p>
                        </div>
                      </button>
                    </li>
                  </ul>
                </div>

                <loading-button
                  v-if="canUpdateIssue"
                  :loading="isSubmitting"
                  @click="handleSave(true)"
                  :container-class="[
                    actionButtonClassNames,
                    'btn btn-comment btn-comment-and-close js-action-button'
                  ]"
                  :disabled="isSubmitting"
                  :label="issueActionButtonTitle"
                />

                <button
                  type="button"
                  v-if="note.length"
                  @click="discard"
                  class="btn btn-cancel js-note-discard">
                  Discard draft
                </button>
              </div>
            </form>
          </div>
        </div>
      </li>
    </ul>
  </div>
</template>