summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/notes/stores/issue_notes_store.js
blob: 12ba1b06dfc91f28ad47f483dab76956ce1f8b8a (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
/* eslint-disable no-param-reassign */

import service from '../services/issue_notes_service';
import utils from './issue_notes_utils';
import loadAwardsHandler from '../../awards_handler';

const state = {
  notes: [],
  targetNoteHash: null,
  lastFetchedAt: null,
};

const getters = {
  notes(storeState) {
    return storeState.notes;
  },
  targetNoteHash(storeState) {
    return storeState.targetNoteHash;
  },
  notesById(storeState) {
    const notesById = {};

    storeState.notes.forEach((note) => {
      note.notes.forEach((n) => {
        notesById[n.id] = n;
      });
    });

    return notesById;
  },
};

const mutations = {
  setInitialNotes(storeState, notes) {
    storeState.notes = notes;
  },
  setTargetNoteHash(storeState, hash) {
    storeState.targetNoteHash = hash;
  },
  toggleDiscussion(storeState, { discussionId }) {
    const discussion = utils.findNoteObjectById(storeState.notes, discussionId);

    discussion.expanded = !discussion.expanded;
  },
  deleteNote(storeState, note) {
    const noteObj = utils.findNoteObjectById(storeState.notes, note.discussion_id);

    if (noteObj.individual_note) {
      storeState.notes.splice(storeState.notes.indexOf(noteObj), 1);
    } else {
      const comment = utils.findNoteObjectById(noteObj.notes, note.id);
      noteObj.notes.splice(noteObj.notes.indexOf(comment), 1);

      if (!noteObj.notes.length) {
        storeState.notes.splice(storeState.notes.indexOf(noteObj), 1);
      }
    }
  },
  addNewReplyToDiscussion(storeState, note) {
    const noteObj = utils.findNoteObjectById(storeState.notes, note.discussion_id);

    if (noteObj) {
      noteObj.notes.push(note);
    }
  },
  updateNote(storeState, note) {
    const noteObj = utils.findNoteObjectById(storeState.notes, note.discussion_id);

    if (noteObj.individual_note) {
      noteObj.notes.splice(0, 1, note);
    } else {
      const comment = utils.findNoteObjectById(noteObj.notes, note.id);
      noteObj.notes.splice(noteObj.notes.indexOf(comment), 1, note);
    }
  },
  addNewNote(storeState, note) {
    const { discussion_id, type } = note;
    const noteData = {
      expanded: true,
      id: discussion_id,
      individual_note: !(type === 'DiscussionNote'),
      notes: [note],
      reply_id: discussion_id,
    };

    storeState.notes.push(noteData);
  },
  toggleAward(storeState, data) {
    const { awardName, note } = data;
    const { id, name, username } = window.gl.currentUserData;
    let index = -1;

    note.award_emoji.forEach((a, i) => {
      if (a.name === awardName && a.user.id === id) {
        index = i;
      }
    });

    if (index > -1) { // if I am awarded, remove my award
      note.award_emoji.splice(index, 1);
    } else {
      note.award_emoji.push({
        name: awardName,
        user: { id, name, username },
      });
    }
  },
  setLastFetchedAt(storeState, fetchedAt) {
    storeState.lastFetchedAt = fetchedAt;
  },
  showPlaceholderNote(storeState, data) {
    let notesArr = storeState.notes;
    if (data.replyId) {
      notesArr = utils.findNoteObjectById(notesArr, data.replyId).notes;
    }

    notesArr.push({
      individual_note: true,
      isPlaceholderNote: true,
      placeholderType: data.isSystemNote ? 'systemNote' : 'note',
      notes: [
        {
          body: data.noteBody,
        },
      ],
    });
  },
  removePlaceholderNotes(storeState) {
    const { notes } = storeState;

    for (let i = notes.length - 1; i >= 0; i -= 1) {
      const note = notes[i];
      const children = note.notes;

      if (children.length && !note.individual_note) { // remove placeholder from discussions
        for (let j = children.length - 1; j >= 0; j -= 1) {
          if (children[j].isPlaceholderNote) {
            children.splice(j, 1);
          }
        }
      } else if (note.isPlaceholderNote) { // remove placeholders from state root
        notes.splice(i, 1);
      }
    }
  },
};

const actions = {
  fetchNotes(context, path) {
    return service
      .fetchNotes(path)
      .then(res => res.json())
      .then((res) => {
        context.commit('setInitialNotes', res);
      });
  },
  deleteNote(context, note) {
    return service
      .deleteNote(note.path)
      .then(() => {
        context.commit('deleteNote', note);
      });
  },
  updateNote(context, data) {
    const { endpoint, note } = data;

    return service
      .updateNote(endpoint, note)
      .then(res => res.json())
      .then((res) => {
        context.commit('updateNote', res);
      });
  },
  replyToDiscussion(context, noteData) {
    const { endpoint, data } = noteData;

    return service
      .replyToDiscussion(endpoint, data)
      .then(res => res.json())
      .then((res) => {
        context.commit('addNewReplyToDiscussion', res);

        return res;
      });
  },
  createNewNote(context, noteData) {
    const { endpoint, data } = noteData;

    return service
      .createNewNote(endpoint, data)
      .then(res => res.json())
      .then((res) => {
        if (!res.errors) {
          context.commit('addNewNote', res);
        }
        return res;
      });
  },
  saveNote(context, noteData) {
    const { note } = noteData.data.note;
    let placeholderText = note;
    const hasQuickActions = utils.hasQuickActions(placeholderText);
    const replyId = noteData.data.in_reply_to_discussion_id;
    const methodToDispatch = replyId ? 'replyToDiscussion' : 'createNewNote';

    if (hasQuickActions) {
      placeholderText = utils.stripQuickActions(placeholderText);
    }

    if (placeholderText.length) {
      context.commit('showPlaceholderNote', {
        noteBody: placeholderText,
        replyId,
      });
    }

    if (hasQuickActions) {
      context.commit('showPlaceholderNote', {
        isSystemNote: true,
        noteBody: utils.getQuickActionText(note),
        replyId,
      });
    }

    return context.dispatch(methodToDispatch, noteData)
      .then((res) => {
        const { errors } = res;
        const commandsChanges = res.commands_changes;

        if (hasQuickActions && Object.keys(errors).length) {
          context.dispatch('poll');
          $('.js-gfm-input').trigger('clear-commands-cache.atwho');
          Flash('Commands applied', 'notice', $(noteData.flashContainer));
        }

        if (commandsChanges && commandsChanges.emoji_award) {
          const votesBlock = $('.js-awards-block').eq(0);

          loadAwardsHandler().then((awardsHandler) => {
            awardsHandler.addAwardToEmojiBar(votesBlock, commandsChanges.emoji_award);
            awardsHandler.scrollToAwards();
          }).catch(() => {
            const msg = 'Something went wrong while adding your award. Please try again.';
            Flash(msg, $(noteData.flashContainer));
          });
        }

        if (errors && errors.commands_only) {
          Flash(errors.commands_only, 'notice', $(noteData.flashContainer));
        }
        context.commit('removePlaceholderNotes');

        return res;
      });
  },
  poll(context) {
    const { notesPath } = $('.js-notes-wrapper')[0].dataset;

    return service
      .poll(`${notesPath}?full_data=1`, context.state.lastFetchedAt)
      .then(res => res.json())
      .then((res) => {
        if (res.notes.length) {
          const { notesById } = context.getters;

          res.notes.forEach((note) => {
            if (notesById[note.id]) {
              context.commit('updateNote', note);
            } else if (note.type === 'DiscussionNote') {
              const discussion = utils.findNoteObjectById(context.state.notes, note.discussion_id);

              if (discussion) {
                context.commit('addNewReplyToDiscussion', note);
              } else {
                context.commit('addNewNote', note);
              }
            } else {
              context.commit('addNewNote', note);
            }
          });
        }

        return res;
      });
  },
  toggleAward(context, data) {
    const { endpoint, awardName, noteId, skipMutalityCheck } = data;
    const note = context.getters.notesById[noteId];

    return service
      .toggleAward(endpoint, { name: awardName })
      .then(res => res.json())
      .then(() => {
        context.commit('toggleAward', { awardName, note });

        if (!skipMutalityCheck && (awardName === 'thumbsup' || awardName === 'thumbsdown')) {
          const counterAward = awardName === 'thumbsup' ? 'thumbsdown' : 'thumbsup';
          const targetNote = context.getters.notesById[noteId];
          let amIAwarded = false;

          targetNote.award_emoji.forEach((a) => {
            if (a.name === counterAward && a.user.id === window.gon.current_user_id) {
              amIAwarded = true;
            }
          });

          if (amIAwarded) {
            data.awardName = counterAward;
            data.skipMutalityCheck = true;
            context.dispatch('toggleAward', data);
          }
        }
      });
  },
  scrollToNoteIfNeeded(context, el) {
    const isInViewport = gl.utils.isInViewport(el[0]);

    if (!isInViewport) {
      gl.utils.scrollToElement(el);
    }
  },
};

export default {
  state,
  getters,
  mutations,
  actions,
};