main.js 7.8 KB
Newer Older
Phil Hughes's avatar
Phil Hughes committed
1
/* eslint-disable import/first */
2 3
/* global ConfirmDangerModal */

4 5
import jQuery from 'jquery';
import Cookies from 'js-cookie';
6
import svg4everybody from 'svg4everybody';
7 8 9 10

// expose common libraries as globals (TODO: remove these)
window.jQuery = jQuery;
window.$ = jQuery;
11 12

// lib/utils
13
import { handleLocationHash } from './lib/utils/common_utils';
Phil Hughes's avatar
Phil Hughes committed
14
import { localTimeAgo } from './lib/utils/datetime_utility';
15
import { getLocationHash, visitUrl } from './lib/utils/url_utility';
16

17 18 19
// behaviors
import './behaviors/';

20
// everything else
21
import loadAwardsHandler from './awards_handler';
22
import bp from './breakpoints';
23
import './confirm_danger_modal';
24
import Flash, { removeFlashClickListener } from './flash';
25
import './gl_dropdown';
26
import initTodoToggle from './header';
27
import initImporterStatus from './importer_status';
28
import initLayoutNav from './layout_nav';
29
import './feature_highlight/feature_highlight_options';
30
import LazyLoader from './lazy_loader';
31
import initLogoAnimation from './logo';
32
import './milestone_select';
33
import './projects_dropdown';
34
import './render_gfm';
35
import initBreadcrumbs from './breadcrumb';
36 37

// EE-only scripts
Phil Hughes's avatar
Phil Hughes committed
38
import 'ee/main';
39

40
import initDispatcher from './dispatcher';
41

42
// eslint-disable-next-line global-require, import/no-commonjs
43
if (process.env.NODE_ENV !== 'production') require('./test_utils/');
44

45 46
svg4everybody();

Phil Hughes's avatar
Phil Hughes committed
47
document.addEventListener('beforeunload', () => {
48 49 50 51
  // Unbind scroll events
  $(document).off('scroll');
  // Close any open tooltips
  $('.has-tooltip, [data-toggle="tooltip"]').tooltip('destroy');
52 53
  // Close any open popover
  $('[data-toggle="popover"]').popover('destroy');
54
});
Fatih Acet's avatar
Fatih Acet committed
55

56
window.addEventListener('hashchange', handleLocationHash);
57 58
window.addEventListener('load', function onLoad() {
  window.removeEventListener('load', onLoad, false);
59
  handleLocationHash();
60
}, false);
61

62 63
gl.lazyLoader = new LazyLoader({
  scrollContainer: window,
Phil Hughes's avatar
Phil Hughes committed
64
  observerNode: '#content-body',
65 66
});

67
document.addEventListener('DOMContentLoaded', () => {
Phil Hughes's avatar
Phil Hughes committed
68 69 70 71 72
  const $body = $('body');
  const $document = $(document);
  const $window = $(window);
  const $sidebarGutterToggle = $('.js-sidebar-toggle');
  let bootstrapBreakpoint = bp.getBreakpointSize();
73

74
  initBreadcrumbs();
75
  initLayoutNav();
76
  initImporterStatus();
77
  initTodoToggle();
78
  initLogoAnimation();
79

80 81
  // Set the default path for all cookies to GitLab's root directory
  Cookies.defaults.path = gon.relative_url_root || '/';
82

83
  // `hashchange` is not triggered when link target is already in window.location
Phil Hughes's avatar
Phil Hughes committed
84 85
  $body.on('click', 'a[href^="#"]', function clickHashLinkCallback() {
    const href = this.getAttribute('href');
86
    if (href.substr(1) === getLocationHash()) {
87
      setTimeout(handleLocationHash, 1);
88 89
    }
  });
90

91
  if (bootstrapBreakpoint === 'xs') {
92
    const $rightSidebar = $('aside.right-sidebar, .layout-page');
93 94 95 96 97 98

    $rightSidebar
      .removeClass('right-sidebar-expanded')
      .addClass('right-sidebar-collapsed');
  }

99
  // prevent default action for disabled buttons
Phil Hughes's avatar
Phil Hughes committed
100
  $('.btn').click(function clickDisabledButtonCallback(e) {
101 102 103 104
    if ($(this).hasClass('disabled')) {
      e.preventDefault();
      e.stopImmediatePropagation();
      return false;
Fatih Acet's avatar
Fatih Acet committed
105
    }
Phil Hughes's avatar
Phil Hughes committed
106 107

    return true;
108 109 110 111
  });

  // Click a .js-select-on-focus field, select the contents
  // Prevent a mouseup event from deselecting the input
Phil Hughes's avatar
Phil Hughes committed
112 113 114 115
  $('.js-select-on-focus').on('focusin', function selectOnFocusCallback() {
    $(this).select().one('mouseup', (e) => {
      e.preventDefault();
    });
116
  });
Phil Hughes's avatar
Phil Hughes committed
117 118

  $('.remove-row').on('ajax:success', function removeRowAjaxSuccessCallback() {
119 120 121 122
    $(this).tooltip('destroy')
      .closest('li')
      .fadeOut();
  });
Phil Hughes's avatar
Phil Hughes committed
123 124 125

  $('.js-remove-tr').on('ajax:before', function removeTRAjaxBeforeCallback() {
    $(this).hide();
126
  });
Phil Hughes's avatar
Phil Hughes committed
127 128 129

  $('.js-remove-tr').on('ajax:success', function removeTRAjaxSuccessCallback() {
    $(this).closest('tr').fadeOut();
130
  });
Phil Hughes's avatar
Phil Hughes committed
131 132

  // Initialize select2 selects
133 134
  $('select.select2').select2({
    width: 'resolve',
Phil Hughes's avatar
Phil Hughes committed
135
    dropdownAutoWidth: true,
136
  });
Phil Hughes's avatar
Phil Hughes committed
137

138
  // Close select2 on escape
Phil Hughes's avatar
Phil Hughes committed
139 140 141 142 143
  $('.js-select2').on('select2-close', () => {
    setTimeout(() => {
      $('.select2-container-active').removeClass('select2-container-active');
      $(':focus').blur();
    }, 1);
144
  });
Phil Hughes's avatar
Phil Hughes committed
145

146 147 148 149
  // Initialize tooltips
  $.fn.tooltip.Constructor.DEFAULTS.trigger = 'hover';
  $body.tooltip({
    selector: '.has-tooltip, [data-toggle="tooltip"]',
Phil Hughes's avatar
Phil Hughes committed
150
    placement(tip, el) {
151
      return $(el).data('placement') || 'bottom';
Phil Hughes's avatar
Phil Hughes committed
152
    },
153
  });
Phil Hughes's avatar
Phil Hughes committed
154

155 156
  // Initialize popovers
  $body.popover({
157
    selector: '[data-toggle="popover"]',
158 159 160
    trigger: 'focus',
    // set the viewport to the main content, excluding the navigation bar, so
    // the navigation can't overlap the popover
Phil Hughes's avatar
Phil Hughes committed
161
    viewport: '.layout-page',
162
  });
Phil Hughes's avatar
Phil Hughes committed
163

164
  // Form submitter
Phil Hughes's avatar
Phil Hughes committed
165 166
  $('.trigger-submit').on('change', function triggerSubmitCallback() {
    $(this).parents('form').submit();
167
  });
Phil Hughes's avatar
Phil Hughes committed
168

169
  localTimeAgo($('abbr.timeago, .js-timeago'), true);
Phil Hughes's avatar
Phil Hughes committed
170

171
  // Disable form buttons while a form is submitting
Phil Hughes's avatar
Phil Hughes committed
172 173
  $body.on('ajax:complete, ajax:beforeSend, submit', 'form', function ajaxCompleteCallback(e) {
    const $buttons = $('[type="submit"], .js-disable-on-submit', this);
174 175 176
    switch (e.type) {
      case 'ajax:beforeSend':
      case 'submit':
Phil Hughes's avatar
Phil Hughes committed
177
        return $buttons.disable();
178
      default:
Phil Hughes's avatar
Phil Hughes committed
179
        return $buttons.enable();
180 181
    }
  });
Phil Hughes's avatar
Phil Hughes committed
182 183 184 185 186 187

  $(document).ajaxError((e, xhrObj) => {
    const ref = xhrObj.status;

    if (ref === 401) {
      Flash('You need to be logged in.');
188
    } else if (ref === 404 || ref === 500) {
Phil Hughes's avatar
Phil Hughes committed
189
      Flash('Something went wrong on our end.');
190 191
    }
  });
Phil Hughes's avatar
Phil Hughes committed
192

193
  // Commit show suppressed diff
Phil Hughes's avatar
Phil Hughes committed
194 195 196 197
  $document.on('click', '.diff-content .js-show-suppressed-diff', function showDiffCallback() {
    const $container = $(this).parent();
    $container.next('table').show();
    $container.remove();
198
  });
Phil Hughes's avatar
Phil Hughes committed
199

200 201 202 203
  $('.navbar-toggle').on('click', () => {
    $('.header-content').toggleClass('menu-expanded');
    gl.lazyLoader.loadCheck();
  });
Phil Hughes's avatar
Phil Hughes committed
204

205
  // Show/hide comments on diff
Phil Hughes's avatar
Phil Hughes committed
206 207 208 209 210 211
  $body.on('click', '.js-toggle-diff-comments', function toggleDiffCommentsCallback(e) {
    const $this = $(this);
    const notesHolders = $this.closest('.diff-file').find('.notes_holder');

    e.preventDefault();

212
    $this.toggleClass('active');
Phil Hughes's avatar
Phil Hughes committed
213

214 215 216 217 218
    if ($this.hasClass('active')) {
      notesHolders.show().find('.hide, .content').show();
    } else {
      notesHolders.hide().find('.content').hide();
    }
Phil Hughes's avatar
Phil Hughes committed
219

220 221
    $(document).trigger('toggle.comments');
  });
Phil Hughes's avatar
Phil Hughes committed
222 223 224 225

  $document.on('click', '.js-confirm-danger', (e) => {
    const btn = $(e.target);
    const form = btn.closest('form');
Phil Hughes's avatar
Phil Hughes committed
226
    const text = btn.data('confirmDangerMessage');
227
    e.preventDefault();
Phil Hughes's avatar
Phil Hughes committed
228 229 230

    // eslint-disable-next-line no-new
    new ConfirmDangerModal(form, text);
231
  });
Phil Hughes's avatar
Phil Hughes committed
232 233

  $document.on('breakpoint:change', (e, breakpoint) => {
234
    if (breakpoint === 'sm' || breakpoint === 'xs') {
Phil Hughes's avatar
Phil Hughes committed
235
      const $gutterIcon = $sidebarGutterToggle.find('i');
236
      if ($gutterIcon.hasClass('fa-angle-double-right')) {
Phil Hughes's avatar
Phil Hughes committed
237
        $sidebarGutterToggle.trigger('click');
Fatih Acet's avatar
Fatih Acet committed
238
      }
239
    }
240
  });
Phil Hughes's avatar
Phil Hughes committed
241 242 243

  function fitSidebarForSize() {
    const oldBootstrapBreakpoint = bootstrapBreakpoint;
244
    bootstrapBreakpoint = bp.getBreakpointSize();
Phil Hughes's avatar
Phil Hughes committed
245

246
    if (bootstrapBreakpoint !== oldBootstrapBreakpoint) {
Phil Hughes's avatar
Phil Hughes committed
247
      $document.trigger('breakpoint:change', [bootstrapBreakpoint]);
248
    }
Phil Hughes's avatar
Phil Hughes committed
249
  }
250

Phil Hughes's avatar
Phil Hughes committed
251
  $window.on('resize.app', fitSidebarForSize);
252

Phil Hughes's avatar
Phil Hughes committed
253 254 255
  loadAwardsHandler();

  $('form.filter-form').on('submit', function filterFormSubmitCallback(event) {
Phil Hughes's avatar
Phil Hughes committed
256 257 258 259 260
    const link = document.createElement('a');
    link.href = this.action;

    const action = `${this.action}${link.search === '' ? '?' : '&'}`;

Phil Hughes's avatar
Phil Hughes committed
261
    event.preventDefault();
262
    visitUrl(`${action}${$(this).serialize()}`);
Phil Hughes's avatar
Phil Hughes committed
263
  });
264

265 266 267
  const flashContainer = document.querySelector('.flash-container');

  if (flashContainer && flashContainer.children.length) {
268 269 270
    flashContainer.querySelectorAll('.flash-alert, .flash-notice, .flash-success').forEach((flashEl) => {
      removeFlashClickListener(flashEl);
    });
271
  }
272 273

  initDispatcher();
274
});