Commit 6a1b84c7 authored by Filipa Lacerda's avatar Filipa Lacerda

Use modules in common utils

parent 5d952f75
......@@ -2,6 +2,7 @@
/* global Flash */
import _ from 'underscore';
import Cookies from 'js-cookie';
import { isInIssuePage, updateTooltipTitle } from './lib/utils/common_utils';
const animationEndEventString = 'animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd';
const transitionEndEventString = 'transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd';
......@@ -237,7 +238,7 @@ class AwardsHandler {
addAward(votesBlock, awardUrl, emoji, checkMutuality, callback) {
const isMainAwardsBlock = votesBlock.closest('.js-issue-note-awards').length;
if (gl.utils.isInIssuePage() && !isMainAwardsBlock) {
if (isInIssuePage() && !isMainAwardsBlock) {
const id = votesBlock.attr('id').replace('note_', '');
$('.emoji-menu').removeClass('is-visible');
......@@ -288,7 +289,7 @@ class AwardsHandler {
}
getVotesBlock() {
if (gl.utils.isInIssuePage()) {
if (isInIssuePage()) {
const $el = $('.js-add-award.is-active').closest('.note.timeline-entry');
if ($el.length) {
......@@ -452,11 +453,11 @@ class AwardsHandler {
userAuthored($emojiButton) {
const oldTitle = this.getAwardTooltip($emojiButton);
const newTitle = 'You cannot vote on your own issue, MR and note';
gl.utils.updateTooltipTitle($emojiButton, newTitle).tooltip('show');
updateTooltipTitle($emojiButton, newTitle).tooltip('show');
// Restore tooltip back to award list
return setTimeout(() => {
$emojiButton.tooltip('hide');
gl.utils.updateTooltipTitle($emojiButton, oldTitle);
updateTooltipTitle($emojiButton, oldTitle);
}, 2800);
}
......
import '../commons/bootstrap';
import { isInIssuePage } from '../lib/utils/common_utils';
// Quick Submit behavior
//
......@@ -45,7 +46,7 @@ $(document).on('keydown.quick_submit', '.js-quick-submit', (e) => {
if (!$submitButton.attr('disabled')) {
$submitButton.trigger('click', [e]);
if (!gl.utils.isInIssuePage()) {
if (!isInIssuePage()) {
$submitButton.disable();
}
}
......
/* eslint-disable func-names, space-before-function-paren, wrap-iife, one-var, no-var, camelcase, one-var-declaration-per-line, no-else-return, max-len */
import { rstrip } from './lib/utils/common_utils';
window.ConfirmDangerModal = (function() {
function ConfirmDangerModal(form, text) {
......@@ -12,7 +13,7 @@ window.ConfirmDangerModal = (function() {
submit.disable();
$('.js-confirm-danger-input').off('input');
$('.js-confirm-danger-input').on('input', function() {
if (gl.utils.rstrip($(this).val()) === project_path) {
if (rstrip($(this).val()) === project_path) {
return submit.enable();
} else {
return submit.disable();
......
......@@ -77,6 +77,7 @@ import initProjectVisibilitySelector from './project_visibility';
import GpgBadges from './gpg_badges';
import UserFeatureHelper from './helpers/user_feature_helper';
import initChangesDropdown from './init_changes_dropdown';
import { ajaxGet } from './lib/utils/common_utils';
(function() {
var Dispatcher;
......@@ -351,7 +352,7 @@ import initChangesDropdown from './init_changes_dropdown';
if ($('.blob-viewer').length) new BlobViewer();
if ($('.project-show-activity').length) new gl.Activities();
$('#tree-slider').waitForImages(function() {
gl.utils.ajaxGet(document.querySelector('.js-tree-content').dataset.logsPath);
ajaxGet(document.querySelector('.js-tree-content').dataset.logsPath);
});
break;
case 'projects:edit':
......@@ -427,7 +428,7 @@ import initChangesDropdown from './init_changes_dropdown';
new NewCommitForm($('.js-create-dir-form'));
new UserCallout({ setCalloutPerProject: true });
$('#tree-slider').waitForImages(function() {
gl.utils.ajaxGet(document.querySelector('.js-tree-content').dataset.logsPath);
ajaxGet(document.querySelector('.js-tree-content').dataset.logsPath);
});
break;
case 'projects:find_file:show':
......
......@@ -7,6 +7,7 @@ import './flash';
import BlobForkSuggestion from './blob/blob_fork_suggestion';
import initChangesDropdown from './init_changes_dropdown';
import bp from './breakpoints';
import parseUrlPathname from './lib/utils/common_utils';
/* eslint-disable max-len */
// MergeRequestTabs
......@@ -260,7 +261,7 @@ import bp from './breakpoints';
// 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);
const urlPathname = parseUrlPathname(source);
this.ajaxGet({
url: `${urlPathname}.json${location.search}`,
......
......@@ -8,6 +8,7 @@
import EmptyState from './empty_state.vue';
import MonitoringStore from '../stores/monitoring_store';
import eventHub from '../event_hub';
import { backOff } from '../../lib/utils/common_utils';
export default {
......@@ -41,7 +42,7 @@
getGraphsData() {
const maxNumberOfRequests = 3;
this.state = 'loading';
gl.utils.backOff((next, stop) => {
backOff((next, stop) => {
this.service.get().then((resp) => {
if (resp.status === statusCodes.NO_CONTENT) {
this.backOffRequestCounter = this.backOffRequestCounter += 1;
......
......@@ -23,6 +23,7 @@ import loadAwardsHandler from './awards_handler';
import './autosave';
import './dropzone_input';
import TaskList from './task_list';
import { ajaxPost, isInViewport, getPagePath } from './lib/utils/common_utils';
window.autosize = autosize;
window.Dropzone = Dropzone;
......@@ -81,7 +82,7 @@ export default class Notes {
this.setViewType(view);
// We are in the Merge Requests page so we need another edit form for Changes tab
if (gl.utils.getPagePath(1) === 'merge_requests') {
if (getPagePath(1) === 'merge_requests') {
$('.note-edit-form').clone()
.addClass('mr-note-edit-form').insertAfter('.note-edit-form');
}
......@@ -644,10 +645,10 @@ export default class Notes {
}
else {
var $buttons = $el.find('.note-form-actions');
var isWidgetVisible = gl.utils.isInViewport($el.get(0));
var isWidgetVisible = isInViewport($el.get(0));
if (!isWidgetVisible) {
gl.utils.scrollToElement($el);
scrollToElement($el);
}
$el.find('.js-finish-edit-warning').show();
......@@ -1188,7 +1189,7 @@ export default class Notes {
}
static checkMergeRequestStatus() {
if (gl.utils.getPagePath(1) === 'merge_requests') {
if (getPagePath(1) === 'merge_requests') {
gl.mrWidget.checkStatus();
}
}
......@@ -1326,7 +1327,7 @@ export default class Notes {
* 2) Identify comment type; a) Main thread b) Discussion thread c) Discussion resolve
* 3) Build temporary placeholder element (using `createPlaceholderNote`)
* 4) Show placeholder note on UI
* 5) Perform network request to submit the note using `gl.utils.ajaxPost`
* 5) Perform network request to submit the note using `ajaxPost`
* a) If request is successfully completed
* 1. Remove placeholder element
* 2. Show submitted Note element
......@@ -1408,7 +1409,7 @@ export default class Notes {
/* eslint-disable promise/catch-or-return */
// Make request to submit comment on server
gl.utils.ajaxPost(formAction, formData)
ajaxPost(formAction, formData)
.then((note) => {
// Submission successful! remove placeholder
$notesContainer.find(`#${noteUniqueId}`).remove();
......@@ -1510,7 +1511,7 @@ export default class Notes {
/* eslint-disable promise/catch-or-return */
// Make request to update comment on server
gl.utils.ajaxPost(formAction, formData)
ajaxPost(formAction, formData)
.then((note) => {
// Submission successful! render final note element
this.updateNote(note, $editingNote);
......
......@@ -7,6 +7,7 @@ import * as constants from '../constants';
import service from '../services/issue_notes_service';
import loadAwardsHandler from '../../awards_handler';
import sidebarTimeTrackingEventHub from '../../sidebar/event_hub';
import { isInViewport, scrollToElement } from '../../lib/utils/common_utils';
let eTagPoll;
......@@ -211,7 +212,7 @@ export const toggleAwardRequest = ({ commit, getters, dispatch }, data) => {
};
export const scrollToNoteIfNeeded = (context, el) => {
if (!gl.utils.isInViewport(el[0])) {
gl.utils.scrollToElement(el);
if (!isInViewport(el[0])) {
scrollToElement(el);
}
};
/* eslint-disable comma-dangle, no-unused-vars, class-methods-use-this, quotes, consistent-return, func-names, prefer-arrow-callback, space-before-function-paren, max-len */
/* global Flash */
import { getPagePath } from '../lib/utils/common_utils';
((global) => {
class Profile {
......@@ -93,7 +94,7 @@
return $title.val(comment[1]).change();
}
});
if (global.utils.getPagePath() === 'profiles') {
if (getPagePath() === 'profiles') {
return new Profile();
}
});
......
import PANEL_STATE from './constants';
import { backOff } from '../lib/utils/common_utils';
export default class PrometheusMetrics {
constructor(wrapperSelector) {
......@@ -79,7 +80,7 @@ export default class PrometheusMetrics {
loadActiveMetrics() {
this.showMonitoringMetricsPanelState(PANEL_STATE.LOADING);
gl.utils.backOff((next, stop) => {
backOff((next, stop) => {
$.getJSON(this.activeMetricsEndpoint)
.done((res) => {
if (res && res.success) {
......
/* eslint-disable comma-dangle, no-return-assign, one-var, no-var, no-underscore-dangle, one-var-declaration-per-line, no-unused-vars, no-cond-assign, consistent-return, object-shorthand, prefer-arrow-callback, func-names, space-before-function-paren, prefer-template, quotes, class-methods-use-this, no-unused-expressions, no-sequences, wrap-iife, no-lonely-if, no-else-return, no-param-reassign, vars-on-top, max-len */
import { isInGroupsPage, isInProjectPage, getGroupSlug, getProjectSlug } from './lib/utils/common_utils';
((global) => {
const KEYCODE = {
......@@ -146,14 +147,14 @@
}
getCategoryContents() {
var dashboardOptions, groupOptions, issuesPath, items, mrPath, name, options, projectOptions, userId, userName, utils;
var dashboardOptions, groupOptions, issuesPath, items, mrPath, name, options, projectOptions, userId, userName;
userId = gon.current_user_id;
userName = gon.current_username;
utils = gl.utils, projectOptions = gl.projectOptions, groupOptions = gl.groupOptions, dashboardOptions = gl.dashboardOptions;
if (utils.isInGroupsPage() && groupOptions) {
options = groupOptions[utils.getGroupSlug()];
} else if (utils.isInProjectPage() && projectOptions) {
options = projectOptions[utils.getProjectSlug()];
projectOptions = gl.projectOptions, groupOptions = gl.groupOptions, dashboardOptions = gl.dashboardOptions;
if (isInGroupsPage() && groupOptions) {
options = groupOptions[getGroupSlug()];
} else if (isInProjectPage() && projectOptions) {
options = projectOptions[getProjectSlug()];
} else if (dashboardOptions) {
options = dashboardOptions;
}
......
import statusCodes from '../../lib/utils/http_status';
import { bytesToMiB } from '../../lib/utils/number_utils';
import { backOff } from '../../lib/utils/common_utils';
import MemoryGraph from '../../vue_shared/components/memory_graph';
import MRWidgetService from '../services/mr_widget_service';
......@@ -84,7 +84,7 @@ export default {
}
},
loadMetrics() {
gl.utils.backOff((next, stop) => {
backOff((next, stop) => {
MRWidgetService.fetchMetrics(this.metricsUrl)
.then((res) => {
if (res.status === statusCodes.NO_CONTENT) {
......
/* eslint-disable promise/catch-or-return */
import '~/lib/utils/common_utils';
import * as commonUtils from '~/lib/utils/common_utils';
(() => {
describe('common_utils', () => {
describe('gl.utils.parseUrl', () => {
describe('common_utils', () => {
describe('parseUrl', () => {
it('returns an anchor tag with url', () => {
expect(gl.utils.parseUrl('/some/absolute/url').pathname).toContain('some/absolute/url');
expect(commonUtils.parseUrl('/some/absolute/url').pathname).toContain('some/absolute/url');
});
it('url is escaped', () => {
// IE11 will return a relative pathname while other browsers will return a full pathname.
......@@ -14,21 +13,21 @@ import '~/lib/utils/common_utils';
// element will create an absolute url relative to the current execution context.
// The JavaScript test suite is executed at '/' which will lead to an absolute url
// starting with '/'.
expect(gl.utils.parseUrl('" test="asf"').pathname).toContain('/%22%20test=%22asf%22');
expect(commonUtils.parseUrl('" test="asf"').pathname).toContain('/%22%20test=%22asf%22');
});
});
describe('gl.utils.parseUrlPathname', () => {
describe('parseUrlPathname', () => {
beforeEach(() => {
spyOn(gl.utils, 'parseUrl').and.callFake(url => ({
pathname: url,
}));
});
it('returns an absolute url when given an absolute url', () => {
expect(gl.utils.parseUrlPathname('/some/absolute/url')).toEqual('/some/absolute/url');
expect(commonUtils.parseUrlPathname('/some/absolute/url')).toEqual('/some/absolute/url');
});
it('returns an absolute url when given a relative url', () => {
expect(gl.utils.parseUrlPathname('some/relative/url')).toEqual('/some/relative/url');
expect(commonUtils.parseUrlPathname('some/relative/url')).toEqual('/some/relative/url');
});
});
......@@ -53,7 +52,7 @@ import '~/lib/utils/common_utils';
});
});
describe('gl.utils.handleLocationHash', () => {
describe('handleLocationHash', () => {
beforeEach(() => {
spyOn(window.document, 'getElementById').and.callThrough();
});
......@@ -68,7 +67,7 @@ import '~/lib/utils/common_utils';
it('decodes hash parameter', () => {
window.history.pushState({}, null, '#random-hash');
gl.utils.handleLocationHash();
commonUtils.handleLocationHash();
expectGetElementIdToHaveBeenCalledWith('random-hash');
expectGetElementIdToHaveBeenCalledWith('user-content-random-hash');
......@@ -76,7 +75,7 @@ import '~/lib/utils/common_utils';
it('decodes cyrillic hash parameter', () => {
window.history.pushState({}, null, '#definição');
gl.utils.handleLocationHash();
commonUtils.handleLocationHash();
expectGetElementIdToHaveBeenCalledWith('definição');
expectGetElementIdToHaveBeenCalledWith('user-content-definição');
......@@ -84,7 +83,7 @@ import '~/lib/utils/common_utils';
it('decodes encoded cyrillic hash parameter', () => {
window.history.pushState({}, null, '#defini%C3%A7%C3%A3o');
gl.utils.handleLocationHash();
commonUtils.handleLocationHash();
expectGetElementIdToHaveBeenCalledWith('definição');
expectGetElementIdToHaveBeenCalledWith('user-content-definição');
......@@ -265,7 +264,7 @@ import '~/lib/utils/common_utils';
});
});
describe('gl.utils.backOff', () => {
describe('backOff', () => {
beforeEach(() => {
// shortcut our timeouts otherwise these tests will take a long time to finish
const origSetTimeout = window.setTimeout;
......@@ -274,7 +273,7 @@ import '~/lib/utils/common_utils';
it('solves the promise from the callback', (done) => {
const expectedResponseValue = 'Success!';
gl.utils.backOff((next, stop) => (
commonUtils.backOff((next, stop) => (
new Promise((resolve) => {
resolve(expectedResponseValue);
}).then((resp) => {
......@@ -288,7 +287,7 @@ import '~/lib/utils/common_utils';
it('catches the rejected promise from the callback ', (done) => {
const errorMessage = 'Mistakes were made!';
gl.utils.backOff((next, stop) => {
commonUtils.backOff((next, stop) => {
new Promise((resolve, reject) => {
reject(new Error(errorMessage));
}).then((resp) => {
......@@ -304,7 +303,7 @@ import '~/lib/utils/common_utils';
it('solves the promise correctly after retrying a third time', (done) => {
let numberOfCalls = 1;
const expectedResponseValue = 'Success!';
gl.utils.backOff((next, stop) => (
commonUtils.backOff((next, stop) => (
Promise.resolve(expectedResponseValue)
.then((resp) => {
if (numberOfCalls < 3) {
......@@ -323,7 +322,7 @@ import '~/lib/utils/common_utils';
});
it('rejects the backOff promise after timing out', (done) => {
gl.utils.backOff(next => next(), 64000)
commonUtils.backOff(next => next(), 64000)
.catch((errBackoffResp) => {
const timeouts = window.setTimeout.calls.allArgs().map(([, timeout]) => timeout);
expect(timeouts).toEqual([2000, 4000, 8000, 16000, 32000, 32000]);
......@@ -384,15 +383,14 @@ import '~/lib/utils/common_utils';
});
});
describe('gl.utils.ajaxPost', () => {
describe('ajaxPost', () => {
it('should perform `$.ajax` call and do `POST` request', () => {
const requestURL = '/some/random/api';
const data = { keyname: 'value' };
const ajaxSpy = spyOn($, 'ajax').and.callFake(() => {});
gl.utils.ajaxPost(requestURL, data);
commonUtils.ajaxPost(requestURL, data);
expect(ajaxSpy.calls.allArgs()[0][0].type).toEqual('POST');
});
});
});
})();
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment