summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/merge_request_tabs.js
blob: 7840f05a8aefd5ac25009012014c84ecb0b74ee6 (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
/* eslint-disable no-new, class-methods-use-this */
/* global Breakpoints */
/* global Flash */
/* global notes */

import Cookies from 'js-cookie';
import './breakpoints';
import './flash';
import BlobForkSuggestion from './blob/blob_fork_suggestion';

/* eslint-disable max-len */
// MergeRequestTabs
//
// Handles persisting and restoring the current tab selection and lazily-loading
// content on the MergeRequests#show page.
//
// ### Example Markup
//
//   <ul class="nav-links merge-request-tabs">
//     <li class="notes-tab active">
//       <a data-action="notes" data-target="#notes" data-toggle="tab" href="/foo/bar/merge_requests/1">
//         Discussion
//       </a>
//     </li>
//     <li class="commits-tab">
//       <a data-action="commits" data-target="#commits" data-toggle="tab" href="/foo/bar/merge_requests/1/commits">
//         Commits
//       </a>
//     </li>
//     <li class="diffs-tab">
//       <a data-action="diffs" data-target="#diffs" data-toggle="tab" href="/foo/bar/merge_requests/1/diffs">
//         Diffs
//       </a>
//     </li>
//   </ul>
//
//   <div class="tab-content">
//     <div class="notes tab-pane active" id="notes">
//       Notes Content
//     </div>
//     <div class="commits tab-pane" id="commits">
//       Commits Content
//     </div>
//     <div class="diffs tab-pane" id="diffs">
//       Diffs Content
//     </div>
//   </div>
//
//   <div class="mr-loading-status">
//     <div class="loading">
//       Loading Animation
//     </div>
//   </div>
//
/* eslint-enable max-len */

(() => {
  // Store the `location` object, allowing for easier stubbing in tests
  let location = window.location;

  class MergeRequestTabs {

    constructor({ action, setUrl, stubLocation } = {}) {
      this.diffsLoaded = false;
      this.pipelinesLoaded = false;
      this.commitsLoaded = false;
      this.fixedLayoutPref = null;

      this.setUrl = setUrl !== undefined ? setUrl : true;
      this.setCurrentAction = this.setCurrentAction.bind(this);
      this.tabShown = this.tabShown.bind(this);
      this.showTab = this.showTab.bind(this);

      if (stubLocation) {
        location = stubLocation;
      }

      this.bindEvents();
      this.activateTab(action);
      this.initAffix();
    }

    bindEvents() {
      $(document)
        .on('shown.bs.tab', '.merge-request-tabs a[data-toggle="tab"]', this.tabShown)
        .on('click', '.js-show-tab', this.showTab);

      $('.merge-request-tabs a[data-toggle="tab"]')
        .on('click', this.clickTab);
    }

    // Used in tests
    unbindEvents() {
      $(document)
        .off('shown.bs.tab', '.merge-request-tabs a[data-toggle="tab"]', this.tabShown)
        .off('click', '.js-show-tab', this.showTab);

      $('.merge-request-tabs a[data-toggle="tab"]')
        .off('click', this.clickTab);
    }

    destroyPipelinesView() {
      if (this.commitPipelinesTable) {
        this.commitPipelinesTable.$destroy();
        this.commitPipelinesTable = null;

        document.querySelector('#commit-pipeline-table-view').innerHTML = '';
      }
    }

    showTab(e) {
      e.preventDefault();
      this.activateTab($(e.target).data('action'));
    }

    clickTab(e) {
      if (e.currentTarget && gl.utils.isMetaClick(e)) {
        const targetLink = e.currentTarget.getAttribute('href');
        e.stopImmediatePropagation();
        e.preventDefault();
        window.open(targetLink, '_blank');
      }
    }

    tabShown(e) {
      const $target = $(e.target);
      const action = $target.data('action');

      if (action === 'commits') {
        this.loadCommits($target.attr('href'));
        this.expandView();
        this.resetViewContainer();
        this.destroyPipelinesView();
      } else if (this.isDiffAction(action)) {
        this.loadDiff($target.attr('href'));
        if (Breakpoints.get().getBreakpointSize() !== 'lg') {
          this.shrinkView();
        }
        if (this.diffViewType() === 'parallel') {
          this.expandViewContainer();
        }
        this.destroyPipelinesView();
      } else if (action === 'pipelines') {
        this.resetViewContainer();
        this.mountPipelinesView();
      } else {
        if (Breakpoints.get().getBreakpointSize() !== 'xs') {
          this.expandView();
        }
        this.resetViewContainer();
        this.destroyPipelinesView();
      }
      if (this.setUrl) {
        this.setCurrentAction(action);
      }
    }

    scrollToElement(container) {
      if (location.hash) {
        const offset = 0 - (
          $('.navbar-gitlab').outerHeight() +
          $('.js-tabs-affix').outerHeight()
        );
        const $el = $(`${container} ${location.hash}:not(.match)`);
        if ($el.length) {
          $.scrollTo($el[0], { offset });
        }
      }
    }

    // Activate a tab based on the current action
    activateTab(action) {
      // important note: the .tab('show') method triggers 'shown.bs.tab' event itself
      $(`.merge-request-tabs a[data-action='${action}']`).tab('show');
    }

    // Replaces the current Merge Request-specific action in the URL with a new one
    //
    // If the action is "notes", the URL is reset to the standard
    // `MergeRequests#show` route.
    //
    // Examples:
    //
    //   location.pathname # => "/namespace/project/merge_requests/1"
    //   setCurrentAction('diffs')
    //   location.pathname # => "/namespace/project/merge_requests/1/diffs"
    //
    //   location.pathname # => "/namespace/project/merge_requests/1/diffs"
    //   setCurrentAction('show')
    //   location.pathname # => "/namespace/project/merge_requests/1"
    //
    //   location.pathname # => "/namespace/project/merge_requests/1/diffs"
    //   setCurrentAction('commits')
    //   location.pathname # => "/namespace/project/merge_requests/1/commits"
    //
    // Returns the new URL String
    setCurrentAction(action) {
      this.currentAction = action;

      // Remove a trailing '/commits' '/diffs' '/pipelines'
      let newState = location.pathname.replace(/\/(commits|diffs|pipelines)(\.html)?\/?$/, '');

      // Append the new action if we're on a tab other than 'notes'
      if (this.currentAction !== 'show' && this.currentAction !== 'new') {
        newState += `/${this.currentAction}`;
      }

      // Ensure parameters and hash come along for the ride
      newState += location.search + location.hash;

      // TODO: Consider refactoring in light of turbolinks removal.

      // Replace the current history state with the new one without breaking
      // Turbolinks' history.
      //
      // See https://github.com/rails/turbolinks/issues/363
      window.history.replaceState({
        url: newState,
      }, document.title, newState);

      return newState;
    }

    loadCommits(source) {
      if (this.commitsLoaded) {
        return;
      }
      this.ajaxGet({
        url: `${source}.json`,
        success: (data) => {
          document.querySelector('div#commits').innerHTML = data.html;
          gl.utils.localTimeAgo($('.js-timeago', 'div#commits'));
          this.commitsLoaded = true;
          this.scrollToElement('#commits');
        },
      });
    }

    mountPipelinesView() {
      const pipelineTableViewEl = document.querySelector('#commit-pipeline-table-view');
      const CommitPipelinesTable = gl.CommitPipelinesTable;
      this.commitPipelinesTable = new CommitPipelinesTable({
        propsData: {
          endpoint: pipelineTableViewEl.dataset.endpoint,
          helpPagePath: pipelineTableViewEl.dataset.helpPagePath,
        },
      }).$mount();

      // $mount(el) replaces the el with the new rendered component. We need it in order to mount
      // it everytime this tab is clicked - https://vuejs.org/v2/api/#vm-mount
      pipelineTableViewEl.appendChild(this.commitPipelinesTable.$el);
    }

    loadDiff(source) {
      if (this.diffsLoaded) {
        return;
      }

      // We extract pathname for the current Changes tab anchor href
      // some pages like MergeRequestsController#new has query parameters on that anchor
      const urlPathname = gl.utils.parseUrlPathname(source);

      this.ajaxGet({
        url: `${urlPathname}.json${location.search}`,
        success: (data) => {
          const $container = $('#diffs');
          $container.html(data.html);

          if (typeof gl.diffNotesCompileComponents !== 'undefined') {
            gl.diffNotesCompileComponents();
          }

          gl.utils.localTimeAgo($('.js-timeago', 'div#diffs'));
          $('#diffs .js-syntax-highlight').syntaxHighlight();

          if (this.diffViewType() === 'parallel' && this.isDiffAction(this.currentAction)) {
            this.expandViewContainer();
          }
          this.diffsLoaded = true;

          new gl.Diff();
          this.scrollToElement('#diffs');

          $('.diff-file').each((i, el) => {
            new BlobForkSuggestion({
              openButtons: $(el).find('.js-edit-blob-link-fork-toggler'),
              forkButtons: $(el).find('.js-fork-suggestion-button'),
              cancelButtons: $(el).find('.js-cancel-fork-suggestion-button'),
              suggestionSections: $(el).find('.js-file-fork-suggestion-section'),
              actionTextPieces: $(el).find('.js-file-fork-suggestion-section-action'),
            })
              .init();
          });

          // Scroll any linked note into view
          // Similar to `toggler_behavior` in the discussion tab
          const hash = window.gl.utils.getLocationHash();
          const anchor = hash && $container.find(`.note[id="${hash}"]`);
          if (anchor && anchor.length > 0) {
            const notesContent = anchor.closest('.notes_content');
            const lineType = notesContent.hasClass('new') ? 'new' : 'old';
            notes.toggleDiffNote({
              target: anchor,
              lineType,
              forceShow: true,
            });
            anchor[0].scrollIntoView();
            window.gl.utils.handleLocationHash();
            // We have multiple elements on the page with `#note_xxx`
            // (discussion and diff tabs) and `:target` only applies to the first
            anchor.addClass('target');
          }
        },
      });
    }

    // Show or hide the loading spinner
    //
    // status - Boolean, true to show, false to hide
    toggleLoading(status) {
      $('.mr-loading-status .loading').toggle(status);
    }

    ajaxGet(options) {
      const defaults = {
        beforeSend: () => this.toggleLoading(true),
        error: () => new Flash('An error occurred while fetching this tab.', 'alert'),
        complete: () => this.toggleLoading(false),
        dataType: 'json',
        type: 'GET',
      };
      $.ajax($.extend({}, defaults, options));
    }

    diffViewType() {
      return $('.inline-parallel-buttons a.active').data('view-type');
    }

    isDiffAction(action) {
      return action === 'diffs' || action === 'new/diffs';
    }

    expandViewContainer() {
      const $wrapper = $('.content-wrapper .container-fluid');
      if (this.fixedLayoutPref === null) {
        this.fixedLayoutPref = $wrapper.hasClass('container-limited');
      }
      $wrapper.removeClass('container-limited');
    }

    resetViewContainer() {
      if (this.fixedLayoutPref !== null) {
        $('.content-wrapper .container-fluid')
          .toggleClass('container-limited', this.fixedLayoutPref);
      }
    }

    shrinkView() {
      const $gutterIcon = $('.js-sidebar-toggle i:visible');

      // Wait until listeners are set
      setTimeout(() => {
        // Only when sidebar is expanded
        if ($gutterIcon.is('.fa-angle-double-right')) {
          $gutterIcon.closest('a').trigger('click', [true]);
        }
      }, 0);
    }

    // Expand the issuable sidebar unless the user explicitly collapsed it
    expandView() {
      if (Cookies.get('collapsed_gutter') === 'true') {
        return;
      }
      const $gutterIcon = $('.js-sidebar-toggle i:visible');

      // Wait until listeners are set
      setTimeout(() => {
        // Only when sidebar is collapsed
        if ($gutterIcon.is('.fa-angle-double-left')) {
          $gutterIcon.closest('a').trigger('click', [true]);
        }
      }, 0);
    }

    initAffix() {
      const $tabs = $('.js-tabs-affix');
      const $fixedNav = $('.navbar-gitlab');

      // Screen space on small screens is usually very sparse
      // So we dont affix the tabs on these
      if (Breakpoints.get().getBreakpointSize() === 'xs' || !$tabs.length) return;

      /**
        If the browser does not support position sticky, it returns the position as static.
        If the browser does support sticky, then we allow the browser to handle it, if not
        then we default back to Bootstraps affix
      **/
      if ($tabs.css('position') !== 'static') return;

      const $diffTabs = $('#diff-notes-app');

      $tabs.off('affix.bs.affix affix-top.bs.affix')
        .affix({
          offset: {
            top: () => (
              $diffTabs.offset().top - $tabs.height() - $fixedNav.height()
            ),
          },
        })
        .on('affix.bs.affix', () => $diffTabs.css({ marginTop: $tabs.height() }))
        .on('affix-top.bs.affix', () => $diffTabs.css({ marginTop: '' }));

      // Fix bug when reloading the page already scrolling
      if ($tabs.hasClass('affix')) {
        $tabs.trigger('affix.bs.affix');
      }
    }
  }

  window.gl = window.gl || {};
  window.gl.MergeRequestTabs = MergeRequestTabs;
})();