summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/main.js
blob: 3f22bd36a4aa10e9f55cebef8cb9b3e88b4ea152 (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
/* global $ */
/* eslint-disable import/order */

import jQuery from 'jquery';
import Cookies from 'js-cookie';

// bootstrap webpack, common libs, polyfills, and behaviors
import './webpack';
import './commons';
import './behaviors';

// lib/utils
import applyGitLabUIConfig from '@gitlab/ui/dist/config';
import { GlBreakpointInstance as bp } from '@gitlab/ui/dist/utils';
import { initRails } from '~/lib/utils/rails_ujs';
import * as popovers from '~/popovers';
import * as tooltips from '~/tooltips';
import initAlertHandler from './alert_handler';
import { removeFlashClickListener } from './flash';
import initTodoToggle from './header';
import initLayoutNav from './layout_nav';
import { handleLocationHash, addSelectOnFocusBehaviour } from './lib/utils/common_utils';
import { localTimeAgo } from './lib/utils/datetime_utility';
import { getLocationHash, visitUrl } from './lib/utils/url_utility';

// everything else
import initFeatureHighlight from './feature_highlight';
import LazyLoader from './lazy_loader';
import initLogoAnimation from './logo';
import initFrequentItemDropdowns from './frequent_items';
import initBreadcrumbs from './breadcrumb';
import initPersistentUserCallouts from './persistent_user_callouts';
import { initUserTracking, initDefaultTrackers } from './tracking';
import initUsagePingConsent from './usage_ping_consent';
import GlFieldErrors from './gl_field_errors';
import initUserPopovers from './user_popovers';
import initBroadcastNotifications from './broadcast_notification';

import 'ee_else_ce/main_ee';

applyGitLabUIConfig();

// expose jQuery as global (TODO: remove these)
window.jQuery = jQuery;
window.$ = jQuery;

// inject test utilities if necessary
if (process.env.NODE_ENV !== 'production' && gon?.test_env) {
  import(/* webpackMode: "eager" */ './test_utils/');
}

document.addEventListener('beforeunload', () => {
  // Unbind scroll events
  // eslint-disable-next-line @gitlab/no-global-event-off
  $(document).off('scroll');
  // Close any open tooltips
  tooltips.dispose(document.querySelectorAll('.has-tooltip, [data-toggle="tooltip"]'));
  // Close any open popover
  popovers.dispose();
});

window.addEventListener('hashchange', handleLocationHash);
window.addEventListener(
  'load',
  function onLoad() {
    window.removeEventListener('load', onLoad, false);
    handleLocationHash();
  },
  false,
);

gl.lazyLoader = new LazyLoader({
  scrollContainer: window,
  observerNode: '#content-body',
});

initRails();

// Put all initialisations here that can also wait after everything is rendered and ready
function deferredInitialisation() {
  const $body = $('body');

  initBreadcrumbs();
  initTodoToggle();
  initLogoAnimation();
  initUsagePingConsent();
  initUserPopovers();
  initBroadcastNotifications();
  initFrequentItemDropdowns();
  initPersistentUserCallouts();
  initDefaultTrackers();
  initFeatureHighlight();

  const search = document.querySelector('#search');
  if (search) {
    search.addEventListener(
      'focus',
      () => {
        import(/* webpackChunkName: 'globalSearch' */ './search_autocomplete')
          .then(({ default: initSearchAutocomplete }) => {
            const searchDropdown = initSearchAutocomplete();
            searchDropdown.onSearchInputFocus();
          })
          .catch(() => {});
      },
      { once: true },
    );
  }

  addSelectOnFocusBehaviour('.js-select-on-focus');

  const glTooltipDelay = localStorage.getItem('gl-tooltip-delay');
  const delay = glTooltipDelay ? JSON.parse(glTooltipDelay) : 0;

  // Initialize tooltips
  tooltips.initTooltips({
    selector: '.has-tooltip, [data-toggle="tooltip"]',
    trigger: 'hover',
    boundary: 'viewport',
    delay,
  });

  // Initialize popovers
  popovers.initPopovers();

  // Adding a helper class to activate animations only after all is rendered
  setTimeout(() => $body.addClass('page-initialised'), 1000);
}

document.addEventListener('DOMContentLoaded', () => {
  const $body = $('body');
  const $document = $(document);
  const bootstrapBreakpoint = bp.getBreakpointSize();

  initUserTracking();
  initLayoutNav();
  initAlertHandler();

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

  // `hashchange` is not triggered when link target is already in window.location
  $body.on('click', 'a[href^="#"]', function clickHashLinkCallback() {
    const href = this.getAttribute('href');
    if (href.substr(1) === getLocationHash()) {
      setTimeout(handleLocationHash, 1);
    }
  });

  /**
   * TODO: Apparently we are collapsing the right sidebar on certain screensizes per default
   * except on issue board pages. Why can't we do it with CSS?
   *
   * Proposal: Expose a global sidebar API, which we could import wherever we are manipulating
   * the visibility of the sidebar.
   *
   * Quick fix: Get rid of jQuery for this implementation
   */
  const isBoardsPage = /(projects|groups):boards:show/.test(document.body.dataset.page);
  if (!isBoardsPage && (bootstrapBreakpoint === 'sm' || bootstrapBreakpoint === 'xs')) {
    const $rightSidebar = $('aside.right-sidebar');
    const $layoutPage = $('.layout-page');

    if ($rightSidebar.length > 0) {
      $rightSidebar.removeClass('right-sidebar-expanded').addClass('right-sidebar-collapsed');
      $layoutPage.removeClass('right-sidebar-expanded').addClass('right-sidebar-collapsed');
    } else {
      $layoutPage.removeClass('right-sidebar-expanded right-sidebar-collapsed');
    }
  }

  // prevent default action for disabled buttons
  $('.btn').click(function clickDisabledButtonCallback(e) {
    if ($(this).hasClass('disabled')) {
      e.preventDefault();
      e.stopImmediatePropagation();
      return false;
    }

    return true;
  });

  localTimeAgo($('abbr.timeago, .js-timeago'), true);

  /**
   * This disables form buttons while a form is submitting
   * We do not difinitively know all of the places where this is used
   *
   * TODO: Defer execution, migrate to behaviors, and add sentry logging
   */
  $body.on('ajax:complete, ajax:beforeSend, submit', 'form', function ajaxCompleteCallback(e) {
    const $buttons = $('[type="submit"], .js-disable-on-submit', this).not('.js-no-auto-disable');
    switch (e.type) {
      case 'ajax:beforeSend':
      case 'submit':
        return $buttons.disable();
      default:
        return $buttons.enable();
    }
  });

  $('.navbar-toggler').on('click', () => {
    $('.header-content').toggleClass('menu-expanded');
  });

  /**
   * Show suppressed commit diff
   *
   * TODO: Move to commit diff pages
   */
  $document.on('click', '.diff-content .js-show-suppressed-diff', function showDiffCallback() {
    const $container = $(this).parent();
    $container.next('table').show();
    $container.remove();
  });

  // Show/hide comments on diff
  $body.on('click', '.js-toggle-diff-comments', function toggleDiffCommentsCallback(e) {
    const $this = $(this);
    const notesHolders = $this.closest('.diff-file').find('.notes_holder');

    e.preventDefault();

    $this.toggleClass('selected');

    if ($this.hasClass('active')) {
      notesHolders.show().find('.hide, .content').show();
    } else {
      notesHolders.hide().find('.content').hide();
    }

    $(document).trigger('toggle.comments');
  });

  $('form.filter-form').on('submit', function filterFormSubmitCallback(event) {
    const link = document.createElement('a');
    link.href = this.action;

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

    event.preventDefault();
    // eslint-disable-next-line no-jquery/no-serialize
    visitUrl(`${action}${$(this).serialize()}`);
  });

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

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

  // initialize field errors
  $('.gl-show-field-errors').each((i, form) => new GlFieldErrors(form));

  requestIdleCallback(deferredInitialisation);
});