Commit 3a71d488 authored by Mike Greiling's avatar Mike Greiling

Merge branch 'leipert-prettier-arrow-parens-4' into 'master'

Format files with prettier arrowParens [4/15]

See merge request gitlab-org/gitlab!50529
parents c3691f24 e820c228
......@@ -19,7 +19,7 @@ class RecentSearchesStore {
}
setRecentSearches(searches = []) {
const trimmedSearches = searches.map(search =>
const trimmedSearches = searches.map((search) =>
typeof search === 'string' ? search.trim() : search,
);
......
......@@ -40,7 +40,7 @@ export default class VisualTokenValue {
return (
UsersCache.retrieve(username)
.then(user => {
.then((user) => {
if (!user) {
return;
}
......@@ -68,9 +68,9 @@ export default class VisualTokenValue {
);
return AjaxCache.retrieve(labelsEndpointWithParams)
.then(labels => {
.then((labels) => {
const matchingLabel = (labels || []).find(
label => `~${DropdownUtils.getEscapedText(label.title)}` === tokenValue,
(label) => `~${DropdownUtils.getEscapedText(label.title)}` === tokenValue,
);
if (!matchingLabel) {
......@@ -96,8 +96,8 @@ export default class VisualTokenValue {
);
return AjaxCache.retrieve(epicsEndpointWithParams)
.then(epics => {
const matchingEpic = (epics || []).find(epic => epic.id === Number(tokenValue));
.then((epics) => {
const matchingEpic = (epics || []).find((epic) => epic.id === Number(tokenValue));
if (!matchingEpic) {
return;
......
......@@ -34,7 +34,7 @@ const hideFlash = (flashEl, fadeTransition = true) => {
if (!fadeTransition) flashEl.dispatchEvent(new Event('transitionend'));
};
const createAction = config => `
const createAction = (config) => `
<a
href="${config.href || '#'}"
class="flash-action"
......@@ -97,7 +97,7 @@ const deprecatedCreateFlash = function deprecatedCreateFlash(
if (actionConfig.clickHandler) {
flashEl
.querySelector('.flash-action')
.addEventListener('click', e => actionConfig.clickHandler(e));
.addEventListener('click', (e) => actionConfig.clickHandler(e));
}
}
......@@ -151,7 +151,7 @@ const createFlash = function createFlash({
if (actionConfig.clickHandler) {
flashEl
.querySelector('.flash-action')
.addEventListener('click', e => actionConfig.clickHandler(e));
.addEventListener('click', (e) => actionConfig.clickHandler(e));
}
}
......
......@@ -12,7 +12,7 @@ let sidebar;
export const mousePos = [];
export const setSidebar = el => {
export const setSidebar = (el) => {
sidebar = el;
};
export const getOpenMenu = () => currentOpenMenu;
......@@ -32,7 +32,7 @@ const setHeaderHeight = () => {
export const isSidebarCollapsed = () =>
sidebar && sidebar.classList.contains(SIDEBAR_COLLAPSED_CLASS);
export const canShowActiveSubItems = el => {
export const canShowActiveSubItems = (el) => {
if (el.classList.contains('active') && !isSidebarCollapsed()) {
return false;
}
......@@ -71,7 +71,7 @@ export const calculateTop = (boundingRect, outerHeight) => {
: boundingRect.top;
};
export const hideMenu = el => {
export const hideMenu = (el) => {
if (!el) return;
const parentEl = el.parentNode;
......@@ -112,7 +112,7 @@ export const moveSubItemsToPosition = (el, subItems) => {
}
};
export const showSubLevelItems = el => {
export const showSubLevelItems = (el) => {
const subItems = el.querySelector('.sidebar-sub-level-items');
const isIconOnly = subItems && subItems.classList.contains('is-fly-out-only');
......@@ -139,7 +139,7 @@ export const mouseEnterTopItems = (el, timeout = getHideSubItemsInterval()) => {
}, timeout);
};
export const mouseLeaveTopItem = el => {
export const mouseLeaveTopItem = (el) => {
const subItems = el.querySelector('.sidebar-sub-level-items');
if (
......@@ -152,7 +152,7 @@ export const mouseLeaveTopItem = el => {
el.classList.remove(IS_OVER_CLASS);
};
export const documentMouseMove = e => {
export const documentMouseMove = (e) => {
mousePos.push({
x: e.clientX,
y: e.clientY,
......@@ -161,7 +161,7 @@ export const documentMouseMove = e => {
if (mousePos.length > 6) mousePos.shift();
};
export const subItemsMouseLeave = relatedTarget => {
export const subItemsMouseLeave = (relatedTarget) => {
clearTimeout(timeoutId);
if (relatedTarget && !relatedTarget.closest(`.${IS_OVER_CLASS}`)) {
......@@ -189,15 +189,15 @@ export default () => {
requestIdleCallback(setHeaderHeight);
items.forEach(el => {
items.forEach((el) => {
const subItems = el.querySelector('.sidebar-sub-level-items');
if (subItems) {
subItems.addEventListener('mouseleave', e => subItemsMouseLeave(e.relatedTarget));
subItems.addEventListener('mouseleave', (e) => subItemsMouseLeave(e.relatedTarget));
}
el.addEventListener('mouseenter', e => mouseEnterTopItems(e.currentTarget));
el.addEventListener('mouseleave', e => mouseLeaveTopItem(e.currentTarget));
el.addEventListener('mouseenter', (e) => mouseEnterTopItems(e.currentTarget));
el.addEventListener('mouseleave', (e) => mouseLeaveTopItem(e.currentTarget));
});
document.addEventListener('mousemove', documentMouseMove);
......
......@@ -77,7 +77,7 @@ export default {
// Check if item already exists in list
const itemMatchIndex = storedFrequentItems.findIndex(
frequentItem => frequentItem.id === item.id,
(frequentItem) => frequentItem.id === item.id,
);
if (itemMatchIndex > -1) {
......
......@@ -18,7 +18,7 @@ const frequentItemDropdowns = [
];
export default function initFrequentItemDropdowns() {
frequentItemDropdowns.forEach(dropdown => {
frequentItemDropdowns.forEach((dropdown) => {
const { namespace, key } = dropdown;
const el = document.getElementById(`js-${namespace}-dropdown`);
const navEl = document.getElementById(`nav-${namespace}-dropdown`);
......
......@@ -59,7 +59,7 @@ export const fetchSearchedItems = ({ state, dispatch }, searchQuery) => {
}
return Api[state.namespace](searchQuery, params)
.then(results => {
.then((results) => {
dispatch('receiveSearchedItemsSuccess', results);
})
.catch(() => {
......
export const hasSearchQuery = state => state.searchQuery !== '';
export const hasSearchQuery = (state) => state.searchQuery !== '';
......@@ -50,7 +50,7 @@ export default {
[types.RECEIVE_SEARCHED_ITEMS_SUCCESS](state, results) {
const rawItems = results.data ? results.data : results; // Api.groups returns array, Api.projects returns object
Object.assign(state, {
items: rawItems.map(rawItem => ({
items: rawItems.map((rawItem) => ({
id: rawItem.id,
name: rawItem.name,
namespace: rawItem.name_with_namespace || rawItem.full_name,
......
......@@ -5,7 +5,7 @@ import { FREQUENT_ITEMS, HOUR_IN_MS } from './constants';
export const isMobile = () => ['md', 'sm', 'xs'].includes(bp.getBreakpointSize());
export const getTopFrequentItems = items => {
export const getTopFrequentItems = (items) => {
if (!items) {
return [];
}
......@@ -13,7 +13,7 @@ export const getTopFrequentItems = items => {
? FREQUENT_ITEMS.LIST_COUNT_MOBILE
: FREQUENT_ITEMS.LIST_COUNT_DESKTOP;
const frequentItems = items.filter(item => item.frequency >= FREQUENT_ITEMS.ELIGIBLE_FREQUENCY);
const frequentItems = items.filter((item) => item.frequency >= FREQUENT_ITEMS.ELIGIBLE_FREQUENCY);
if (!frequentItems || frequentItems.length === 0) {
return [];
......@@ -45,9 +45,9 @@ export const updateExistingFrequentItem = (frequentItem, item) => {
};
};
export const sanitizeItem = item => {
export const sanitizeItem = (item) => {
// Only sanitize if the key exists on the item
const maybeSanitize = key => {
const maybeSanitize = (key) => {
if (!Object.prototype.hasOwnProperty.call(item, key)) {
return {};
}
......
......@@ -15,7 +15,7 @@ function sanitize(str) {
}
export function membersBeforeSave(members) {
return members.map(member => {
return members.map((member) => {
const GROUP_TYPE = 'Group';
let title = '';
......@@ -156,7 +156,7 @@ class GfmAutoComplete {
...this.getDefaultCallbacks(),
beforeSave(commands) {
if (GfmAutoComplete.isLoading(commands)) return commands;
return $.map(commands, c => {
return $.map(commands, (c) => {
let search = c.name;
if (c.aliases.length > 0) {
search = `${search} ${c.aliases.join(' ')}`;
......@@ -237,7 +237,7 @@ class GfmAutoComplete {
});
// return to the form atwho wants
return results.map(name => ({ name }));
return results.map((name) => ({ name }));
},
},
});
......@@ -288,7 +288,7 @@ class GfmAutoComplete {
const subtextNodes = subtext.split(/\n+/g).pop().split(GfmAutoComplete.regexSubtext);
// Check if @ is followed by '/assign', '/reassign', '/unassign' or '/cc' commands.
command = subtextNodes.find(node => {
command = subtextNodes.find((node) => {
if (Object.values(MEMBER_COMMAND).includes(node)) {
return node;
}
......@@ -298,7 +298,7 @@ class GfmAutoComplete {
// Cache assignees list for easier filtering later
assignees =
SidebarMediator.singleton?.store?.assignees?.map(
assignee => `${assignee.username} ${assignee.name}`,
(assignee) => `${assignee.username} ${assignee.name}`,
) || [];
const match = GfmAutoComplete.defaultMatcher(flag, subtext, this.app.controllers);
......@@ -316,10 +316,10 @@ class GfmAutoComplete {
if (command === MEMBER_COMMAND.ASSIGN) {
// Only include members which are not assigned to Issuable currently
return data.filter(member => !assignees.includes(member.search));
return data.filter((member) => !assignees.includes(member.search));
} else if (command === MEMBER_COMMAND.UNASSIGN) {
// Only include members which are assigned to Issuable currently
return data.filter(member => assignees.includes(member.search));
return data.filter((member) => assignees.includes(member.search));
}
return data;
......@@ -346,7 +346,7 @@ class GfmAutoComplete {
callbacks: {
...this.getDefaultCallbacks(),
beforeSave(issues) {
return $.map(issues, i => {
return $.map(issues, (i) => {
if (i.title == null) {
return i;
}
......@@ -380,7 +380,7 @@ class GfmAutoComplete {
callbacks: {
...this.getDefaultCallbacks(),
beforeSave(milestones) {
return $.map(milestones, m => {
return $.map(milestones, (m) => {
if (m.title == null) {
return m;
}
......@@ -413,7 +413,7 @@ class GfmAutoComplete {
callbacks: {
...this.getDefaultCallbacks(),
beforeSave(merges) {
return $.map(merges, m => {
return $.map(merges, (m) => {
if (m.title == null) {
return m;
}
......@@ -454,7 +454,7 @@ class GfmAutoComplete {
...this.getDefaultCallbacks(),
beforeSave(merges) {
if (GfmAutoComplete.isLoading(merges)) return merges;
return $.map(merges, m => ({
return $.map(merges, (m) => ({
title: sanitize(m.title),
color: m.color,
search: m.title,
......@@ -465,7 +465,7 @@ class GfmAutoComplete {
const subtextNodes = subtext.split(/\n+/g).pop().split(GfmAutoComplete.regexSubtext);
// Check if ~ is followed by '/label', '/relabel' or '/unlabel' commands.
command = subtextNodes.find(node => {
command = subtextNodes.find((node) => {
if (
node === LABEL_COMMAND.LABEL ||
node === LABEL_COMMAND.RELABEL ||
......@@ -486,7 +486,7 @@ class GfmAutoComplete {
return null;
}
const lastCandidate = subtext.split(flag).pop();
if (labels.find(label => label.title.startsWith(lastCandidate))) {
if (labels.find((label) => label.title.startsWith(lastCandidate))) {
return lastCandidate;
}
} else {
......@@ -513,10 +513,10 @@ class GfmAutoComplete {
// because we want to return all the labels (unfiltered) for that command.
if (command === LABEL_COMMAND.LABEL) {
// Return labels with set: undefined.
return data.filter(label => !label.set);
return data.filter((label) => !label.set);
} else if (command === LABEL_COMMAND.UNLABEL) {
// Return labels with set: true.
return data.filter(label => label.set);
return data.filter((label) => label.set);
}
return data;
......@@ -543,7 +543,7 @@ class GfmAutoComplete {
callbacks: {
...this.getDefaultCallbacks(),
beforeSave(snippets) {
return $.map(snippets, m => {
return $.map(snippets, (m) => {
if (m.title == null) {
return m;
}
......@@ -648,7 +648,7 @@ class GfmAutoComplete {
this.loadEmojiData($input, at).catch(() => {});
} else if (dataSource) {
AjaxCache.retrieve(dataSource, true)
.then(data => {
.then((data) => {
this.loadData($input, at, data);
})
.catch(() => {
......@@ -690,11 +690,11 @@ class GfmAutoComplete {
}
lookup[key].push({ kind, emoji });
};
Object.values(emojis).forEach(emoji => {
Object.values(emojis).forEach((emoji) => {
add(emoji.name, 'name', emoji);
add(emoji.d, 'description', emoji);
add(emoji.e, 'unicode', emoji);
emoji.aliases.forEach(a => add(a, 'alias', emoji));
emoji.aliases.forEach((a) => add(a, 'alias', emoji));
});
this.emojiLookup = lookup;
......@@ -766,7 +766,7 @@ GfmAutoComplete.atTypeMap = {
};
GfmAutoComplete.typesWithBackendFiltering = ['vulnerabilities'];
GfmAutoComplete.isTypeWithBackendFiltering = type =>
GfmAutoComplete.isTypeWithBackendFiltering = (type) =>
GfmAutoComplete.typesWithBackendFiltering.includes(GfmAutoComplete.atTypeMap[type]);
function findEmoji(name) {
......
......@@ -16,14 +16,14 @@ export default class GlFieldErrors {
initValidators() {
// register selectors here as needed
const validateSelectors = [':text', ':password', '[type=email]', '[type=url]', '[type=number]']
.map(selector => `input${selector}`)
.map((selector) => `input${selector}`)
.join(',');
this.state.inputs = this.form
.find(validateSelectors)
.toArray()
.filter(input => !input.classList.contains(customValidationFlag))
.map(input => new GlFieldError({ input, formErrors: this }));
.filter((input) => !input.classList.contains(customValidationFlag))
.map((input) => new GlFieldError({ input, formErrors: this }));
this.form.on('submit', GlFieldErrors.catchInvalidFormSubmit);
}
......@@ -45,7 +45,7 @@ export default class GlFieldErrors {
/* Public method for triggering validity updates manually */
updateFormValidityState() {
this.state.inputs.forEach(field => {
this.state.inputs.forEach((field) => {
if (field.state.submitted) {
field.updateValidity();
}
......
......@@ -20,7 +20,7 @@ export default class GLForm {
// Disable autocomplete for keywords which do not have dataSources available
const dataSources = (gl.GfmAutoComplete && gl.GfmAutoComplete.dataSources) || {};
Object.keys(this.enableGFM).forEach(item => {
Object.keys(this.enableGFM).forEach((item) => {
if (item !== 'emojis' && !dataSources[item]) {
this.enableGFM[item] = false;
}
......
......@@ -28,7 +28,7 @@ export default class GpgBadges {
return axios
.get(endpoint, { params })
.then(({ data }) => {
data.signatures.forEach(signature => {
data.signatures.forEach((signature) => {
badges.filter(`[data-commit-sha="${signature.commit_sha}"]`).replaceWith(signature.html);
});
})
......
......@@ -24,7 +24,7 @@ export const updateGrafanaIntegration = ({ state, dispatch }) =>
},
})
.then(() => dispatch('receiveGrafanaIntegrationUpdateSuccess'))
.catch(error => dispatch('receiveGrafanaIntegrationUpdateError', error));
.catch((error) => dispatch('receiveGrafanaIntegrationUpdateError', error));
export const receiveGrafanaIntegrationUpdateSuccess = () => {
/**
......
......@@ -6,7 +6,7 @@ import mutations from './mutations';
Vue.use(Vuex);
export const createStore = initialState =>
export const createStore = (initialState) =>
new Vuex.Store({
state: createState(initialState),
actions,
......
......@@ -51,4 +51,4 @@ export const convertToGraphQLId = (type, id) => {
* @param {Array} ids An array of id values
* @returns {Array}
*/
export const convertToGraphQLIds = (type, ids) => ids.map(id => convertToGraphQLId(type, id));
export const convertToGraphQLIds = (type, ids) => ids.map((id) => convertToGraphQLId(type, id));
......@@ -12,7 +12,7 @@ export default class Group {
this.resetHandler = this.reset.bind(this);
this.updateGroupPathSlugHandler = this.updateGroupPathSlug.bind(this);
this.groupNames.forEach(groupName => {
this.groupNames.forEach((groupName) => {
if (groupName.value === '') {
groupName.addEventListener('keyup', this.updateHandler);
......@@ -22,7 +22,7 @@ export default class Group {
}
});
this.groupPaths.forEach(groupPath => {
this.groupPaths.forEach((groupPath) => {
groupPath.addEventListener('keydown', this.resetHandler);
});
}
......@@ -30,21 +30,21 @@ export default class Group {
update({ currentTarget: { value: updatedValue } }) {
const slug = slugify(updatedValue);
this.groupNames.forEach(element => {
this.groupNames.forEach((element) => {
element.value = updatedValue;
});
this.groupPaths.forEach(element => {
this.groupPaths.forEach((element) => {
element.value = slug;
});
}
reset() {
this.groupNames.forEach(groupName => {
this.groupNames.forEach((groupName) => {
groupName.removeEventListener('keyup', this.updateHandler);
groupName.removeEventListener('blur', this.checkPathHandler);
});
this.groupPaths.forEach(groupPath => {
this.groupPaths.forEach((groupPath) => {
groupPath.removeEventListener('keydown', this.resetHandler);
});
}
......@@ -59,7 +59,7 @@ export default class Group {
if (exists && suggests.length) {
const [suggestedSlug] = suggests;
this.groupPaths.forEach(element => {
this.groupPaths.forEach((element) => {
element.value = suggestedSlug;
});
} else if (exists && !suggests.length) {
......
......@@ -82,7 +82,7 @@ export default {
.then(() => {
this.isLoading = false;
})
.catch(error => {
.catch((error) => {
const message = [
error.response?.data?.error || __('An error occurred while updating configuration.'),
ERROR_MESSAGE,
......
......@@ -108,7 +108,7 @@ export default {
fetchGroups({ parentId, page, filterGroupsBy, sortBy, archived, updatePagination }) {
return this.service
.getGroups(parentId, page, filterGroupsBy, sortBy, archived)
.then(res => {
.then((res) => {
if (updatePagination) {
this.updatePagination(res.headers);
}
......@@ -135,7 +135,7 @@ export default {
sortBy,
archived,
updatePagination: true,
}).then(res => {
}).then((res) => {
this.isLoading = false;
this.updateGroups(res, Boolean(filterGroupsBy));
});
......@@ -149,7 +149,7 @@ export default {
sortBy,
archived,
updatePagination: true,
}).then(res => {
}).then((res) => {
this.isLoading = false;
$.scrollTo(0);
......@@ -173,7 +173,7 @@ export default {
this.fetchGroups({
parentId: parentGroup.id,
})
.then(res => {
.then((res) => {
this.store.setGroupChildren(parentGroup, res);
})
.catch(() => {
......@@ -194,12 +194,12 @@ export default {
this.targetGroup.isBeingRemoved = true;
this.service
.leaveGroup(this.targetGroup.leavePath)
.then(res => {
.then((res) => {
$.scrollTo(0);
this.store.removeGroup(this.targetGroup, this.targetParentGroup);
this.$toast.show(res.data.notice);
})
.catch(err => {
.catch((err) => {
let message = COMMON_STR.FAILURE;
if (err.status === 403) {
message = COMMON_STR.LEAVE_FORBIDDEN;
......
......@@ -23,7 +23,7 @@ export default {
},
methods: {
getDefaultOption() {
return this.visibilityLevelOptions.find(option => option.level === this.defaultLevel);
return this.visibilityLevelOptions.find((option) => option.level === this.defaultLevel);
},
onClick(option) {
this.selectedOption = option;
......
......@@ -18,6 +18,6 @@ export default function initInviteMembersBanner() {
isDismissedKey,
trackLabel,
},
render: createElement => createElement(InviteMembersBanner),
render: (createElement) => createElement(InviteMembersBanner),
});
}
......@@ -38,6 +38,6 @@ export const initGroupMembersApp = (
el,
components: { App },
store,
render: createElement => createElement('app'),
render: (createElement) => createElement('app'),
});
};
......@@ -7,7 +7,7 @@ import {
GROUP_LINK_ACCESS_LEVEL_PROPERTY_NAME,
} from './constants';
export const parseDataAttributes = el => {
export const parseDataAttributes = (el) => {
const { members, groupId, memberPath, canManageMembers } = el.dataset;
return {
......
......@@ -12,15 +12,15 @@ export default class GroupsStore {
setGroups(rawGroups) {
if (rawGroups && rawGroups.length) {
this.state.groups = rawGroups.map(rawGroup => this.formatGroupItem(rawGroup));
this.state.groups = rawGroups.map((rawGroup) => this.formatGroupItem(rawGroup));
} else {
this.state.groups = [];
}
}
setSearchedGroups(rawGroups) {
const formatGroups = groups =>
groups.map(group => {
const formatGroups = (groups) =>
groups.map((group) => {
const formattedGroup = this.formatGroupItem(group);
if (formattedGroup.children && formattedGroup.children.length) {
formattedGroup.children = formatGroups(formattedGroup.children);
......@@ -37,7 +37,7 @@ export default class GroupsStore {
setGroupChildren(parentGroup, children) {
const updatedParentGroup = parentGroup;
updatedParentGroup.children = children.map(rawChild => this.formatGroupItem(rawChild));
updatedParentGroup.children = children.map((rawChild) => this.formatGroupItem(rawChild));
updatedParentGroup.isOpen = true;
updatedParentGroup.isChildrenLoading = false;
}
......@@ -103,9 +103,9 @@ export default class GroupsStore {
removeGroup(group, parentGroup) {
const updatedParentGroup = parentGroup;
if (updatedParentGroup.children && updatedParentGroup.children.length) {
updatedParentGroup.children = parentGroup.children.filter(child => group.id !== child.id);
updatedParentGroup.children = parentGroup.children.filter((child) => group.id !== child.id);
} else {
this.state.groups = this.state.groups.filter(child => group.id !== child.id);
this.state.groups = this.state.groups.filter((child) => group.id !== child.id);
}
}
}
......@@ -20,11 +20,11 @@ export default class TransferDropdown {
initDeprecatedJQueryDropdown(this.groupDropdown, {
selectable: true,
filterable: true,
toggleLabel: item => item.text,
toggleLabel: (item) => item.text,
search: { fields: ['text'] },
data: extraOptions.concat(this.data),
text: item => item.text,
clicked: options => {
text: (item) => item.text,
clicked: (options) => {
const { e } = options;
e.preventDefault();
this.assignSelected(options.selectedObj);
......
......@@ -6,11 +6,11 @@ import { normalizeHeaders } from './lib/utils/common_utils';
import { __ } from '~/locale';
import { loadCSSFile } from './lib/utils/css_utils';
const fetchGroups = params => {
const fetchGroups = (params) => {
axios[params.type.toLowerCase()](params.url, {
params: params.data,
})
.then(res => {
.then((res) => {
const results = res.data || [];
const headers = normalizeHeaders(res.headers);
const currentPage = parseInt(headers['X-PAGE'], 10) || 0;
......@@ -67,7 +67,7 @@ const groupsSelect = () => {
const groups = data.length ? data : data.results || [];
const more = data.pagination ? data.pagination.more : false;
const results = groups.filter(group => skipGroups.indexOf(group.id) === -1);
const results = groups.filter((group) => skipGroups.indexOf(group.id) === -1);
return {
results,
......
......@@ -45,7 +45,7 @@ class EventHub {
$off(type, handler) {
const handlers = this.$_all.get(type) || [];
const newHandlers = handler ? handlers.filter(x => x !== handler) : [];
const newHandlers = handler ? handlers.filter((x) => x !== handler) : [];
if (newHandlers.length) {
this.$_all.set(type, newHandlers);
......@@ -77,7 +77,7 @@ class EventHub {
$emit(type, ...args) {
const handlers = this.$_all.get(type) || [];
handlers.forEach(handler => {
handlers.forEach((handler) => {
handler(...args);
});
}
......
......@@ -38,7 +38,7 @@ const templatedLabel = (queryLabel, metricAttributes) => {
* @example
* multiMetricLabel('', {__name__: "up", app: "prometheus"}) -> "__name__: up, app: prometheus"
*/
const multiMetricLabel = metricAttributes => {
const multiMetricLabel = (metricAttributes) => {
return Object.entries(metricAttributes)
.map(([templateVar, label]) => `${templateVar}: ${label}`)
.join(', ');
......@@ -64,7 +64,7 @@ export const getSeriesLabel = (queryLabel, metricAttributes) => {
* @returns {Array} The formatted values
*/
export const makeDataSeries = (queryResults, defaultConfig) =>
queryResults.map(result => {
queryResults.map((result) => {
return {
...defaultConfig,
data: result.values,
......
......@@ -23,13 +23,13 @@ const handleStartupEvents = () => {
/* For `waitForCSSLoaded` methods, see docs.gitlab.com/ee/development/fe_guide/performance.html#important-considerations */
export const waitForCSSLoaded = (action = () => {}) => {
if (!gon?.features?.startupCss || allLinksLoaded()) {
return new Promise(resolve => {
return new Promise((resolve) => {
action();
resolve();
});
}
return new Promise(resolve => {
return new Promise((resolve) => {
document.addEventListener(CSS_LOADED_EVENT, resolve, { once: true });
document.addEventListener(STARTUP_LINK_LOADED_EVENT, handleStartupEvents);
}).then(action);
......
import { commitItemIconMap } from './constants';
export default file => {
export default (file) => {
if (file.deleted) {
return commitItemIconMap.deleted;
} else if (file.tempFile && !file.prevPath) {
......
......@@ -63,7 +63,7 @@ export default {
return this.openPendingTab({
file: this.file,
keyPrefix: this.keyPrefix,
}).then(changeViewer => {
}).then((changeViewer) => {
if (changeViewer) {
this.updateViewer(viewerTypes.diff);
}
......
......@@ -29,7 +29,7 @@ export default {
'undoFileTemplate',
]),
setInitialType() {
const initialTemplateType = this.templateTypes.find(t => t.name === this.activeFile.name);
const initialTemplateType = this.templateTypes.find((t) => t.name === this.activeFile.name);
if (initialTemplateType) {
this.setSelectedTemplateType(initialTemplateType);
......
......@@ -44,7 +44,7 @@ export default {
computed: {
...mapState('fileTemplates', ['templates', 'isLoading']),
outputData() {
return (this.isAsyncData ? this.templates : this.data).filter(t => {
return (this.isAsyncData ? this.templates : this.data).filter((t) => {
if (!this.searchable) return true;
return t.name.toLowerCase().indexOf(this.search.toLowerCase()) >= 0;
......
......@@ -73,7 +73,7 @@ export default {
},
},
mounted() {
window.onbeforeunload = e => this.onBeforeUnload(e);
window.onbeforeunload = (e) => this.onBeforeUnload(e);
if (this.themeName)
document.querySelector('.navbar-gitlab').classList.add(`theme-${this.themeName}`);
......
......@@ -37,7 +37,7 @@ export default {
},
methods: {
isActiveTab(tab) {
return this.isOpen && tab.views.some(view => view.name === this.currentView);
return this.isOpen && tab.views.some((view) => view.name === this.currentView);
},
buttonClasses(tab) {
return [
......
......@@ -30,7 +30,7 @@ export default {
const rawContent = encodedContent ? atob(encodedContent) : '';
const isText = isTextFile({ content: rawContent, mimeType, name });
const emitCreateEvent = content =>
const emitCreateEvent = (content) =>
this.$emit('create', {
name: `${this.path ? `${this.path}/` : ''}${name}`,
type: 'blob',
......@@ -42,7 +42,7 @@ export default {
if (isText) {
const reader = new FileReader();
reader.addEventListener('load', e => emitCreateEvent(e.target.result), { once: true });
reader.addEventListener('load', (e) => emitCreateEvent(e.target.result), { once: true });
reader.readAsText(file);
} else {
emitCreateEvent(rawContent);
......@@ -51,11 +51,11 @@ export default {
readFile(file) {
const reader = new FileReader();
reader.addEventListener('load', e => this.createFile(e.target, file), { once: true });
reader.addEventListener('load', (e) => this.createFile(e.target, file), { once: true });
reader.readAsDataURL(file);
},
openFile() {
Array.from(this.$refs.fileUpload.files).forEach(file => this.readFile(file));
Array.from(this.$refs.fileUpload.files).forEach((file) => this.readFile(file));
},
startFileUpload() {
this.$refs.fileUpload.click();
......
......@@ -35,13 +35,13 @@ export default {
return `${this.side}Pane`;
},
tabs() {
return this.extensionTabs.filter(tab => tab.show);
return this.extensionTabs.filter((tab) => tab.show);
},
tabViews() {
return this.tabs.map(tab => tab.views).flat();
return this.tabs.map((tab) => tab.views).flat();
},
aliveTabViews() {
return this.tabViews.filter(view => this.isAliveView(view.name));
return this.tabViews.filter((view) => this.isAliveView(view.name));
},
},
methods: {
......
......@@ -108,7 +108,7 @@ export default {
.then(() => {
this.initManager();
this.listener = listen(e => {
this.listener = listen((e) => {
switch (e.type) {
case 'done':
this.sandpackReady = true;
......@@ -139,8 +139,8 @@ export default {
const settings = {
fileResolver: {
isFile: p => Promise.resolve(Boolean(this.entries[createPathWithExt(p)])),
readFile: p => this.loadFileContent(createPathWithExt(p)).then(content => content),
isFile: (p) => Promise.resolve(Boolean(this.entries[createPathWithExt(p)])),
readFile: (p) => this.loadFileContent(createPathWithExt(p)).then((content) => content),
},
...(bundlerURL ? { bundlerURL } : {}),
};
......
......@@ -31,7 +31,7 @@ export default {
},
},
mounted() {
this.listener = listen(e => {
this.listener = listen((e) => {
switch (e.type) {
case 'urlchange':
this.onUrlChange(e);
......
......@@ -41,12 +41,12 @@ export default {
file,
keyPrefix: file.staged ? stageKeys.staged : stageKeys.unstaged,
})
.then(changeViewer => {
.then((changeViewer) => {
if (changeViewer) {
this.updateViewer('diff');
}
})
.catch(e => {
.catch((e) => {
throw e;
});
},
......
......@@ -219,7 +219,7 @@ export default {
.then(() => {
this.createEditorInstance();
})
.catch(err => {
.catch((err) => {
flash(
__('Error setting up editor. Please try again.'),
'alert',
......@@ -281,7 +281,7 @@ export default {
this.model.updateOptions(this.rules);
this.model.onChange(model => {
this.model.onChange((model) => {
const { file } = model;
if (!file.active) return;
......@@ -329,7 +329,7 @@ export default {
}
},
fetchEditorconfigRules() {
return getRulesWithTraversal(this.file.path, path => {
return getRulesWithTraversal(this.file.path, (path) => {
const entry = this.entries[path];
if (!entry) return Promise.resolve(null);
......@@ -339,7 +339,7 @@ export default {
return this.getFileData({ path: entry.path, makeFileActive: false }).then(() =>
this.getRawFileData({ path: entry.path }),
);
}).then(rules => {
}).then((rules) => {
this.rules = mapRulesToMonaco(rules);
});
},
......@@ -353,7 +353,7 @@ export default {
event.preventDefault();
event.stopImmediatePropagation();
return readFileAsDataURL(file).then(content => {
return readFileAsDataURL(file).then((content) => {
const parentPath = getPathParent(this.file.path);
const path = `${parentPath ? `${parentPath}/` : ''}${file.name}`;
......
......@@ -39,7 +39,7 @@ const EmptyRouterComponent = {
},
};
export const createRouter = store => {
export const createRouter = (store) => {
const router = new IdeRouter({
mode: 'history',
base: joinPaths(gon.relative_url_root || '', '/-/ide/'),
......@@ -54,11 +54,11 @@ export const createRouter = store => {
},
{
path: ':targetmode(edit|tree|blob)/:branchid+/',
redirect: to => joinPaths(to.path, '/-/'),
redirect: (to) => joinPaths(to.path, '/-/'),
},
{
path: ':targetmode(edit|tree|blob)',
redirect: to => joinPaths(to.path, '/master/-/'),
redirect: (to) => joinPaths(to.path, '/master/-/'),
},
{
path: 'merge_requests/:mrid',
......@@ -66,7 +66,7 @@ export const createRouter = store => {
},
{
path: '',
redirect: to => joinPaths(to.path, '/edit/master/-/'),
redirect: (to) => joinPaths(to.path, '/edit/master/-/'),
},
],
},
......@@ -110,7 +110,7 @@ export const createRouter = store => {
});
}
})
.catch(e => {
.catch((e) => {
flash(
__('Error while loading the project data. Please try again.'),
'alert',
......
......@@ -4,11 +4,11 @@ export default class Disposable {
}
add(...disposers) {
disposers.forEach(disposer => this.disposers.add(disposer));
disposers.forEach((disposer) => this.disposers.add(disposer));
}
dispose() {
this.disposers.forEach(disposer => disposer.dispose());
this.disposers.forEach((disposer) => disposer.dispose());
this.disposers.clear();
}
}
......@@ -75,7 +75,7 @@ export default class Model {
}
onChange(cb) {
this.events.add(this.disposable.add(this.model.onDidChangeContent(e => cb(this, e))));
this.events.add(this.disposable.add(this.model.onDidChangeContent((e) => cb(this, e))));
}
onDispose(cb) {
......@@ -121,7 +121,7 @@ export default class Model {
dispose() {
if (!this.model.isDisposed()) this.applyCustomOptions();
this.events.forEach(cb => {
this.events.forEach((cb) => {
if (typeof cb === 'function') cb();
});
......
......@@ -12,13 +12,13 @@ const NEW_LINE = '\n';
*
* - Removes "=======" separator added at the beginning
*/
const cleanTwoFilesPatch = text => text.replace(/^(=+\s*)/, '');
const cleanTwoFilesPatch = (text) => text.replace(/^(=+\s*)/, '');
const endsWithNewLine = val => !val || val[val.length - 1] === NEW_LINE;
const endsWithNewLine = (val) => !val || val[val.length - 1] === NEW_LINE;
const addEndingNewLine = val => (endsWithNewLine(val) ? val : val + NEW_LINE);
const addEndingNewLine = (val) => (endsWithNewLine(val) ? val : val + NEW_LINE);
const removeEndingNewLine = val => (endsWithNewLine(val) ? val.substr(0, val.length - 1) : val);
const removeEndingNewLine = (val) => (endsWithNewLine(val) ? val.substr(0, val.length - 1) : val);
const diffHead = (prevPath, newPath = '') =>
`diff --git "a/${prevPath}" "b/${newPath || prevPath}"`;
......@@ -37,7 +37,7 @@ const createDiffBody = (path, content, isCreate) => {
const chunkHead = isCreate ? `@@ -0,0 +1,${lines.length} @@` : `@@ -1,${lines.length} +0,0 @@`;
const chunk = lines
.map(line => `${prefix}${line}`)
.map((line) => `${prefix}${line}`)
.concat(!hasNewLine ? [NO_NEW_LINE] : [])
.join(NEW_LINE);
......
......@@ -11,7 +11,7 @@ export default class DecorationsController {
const modelDecorations = this.decorations.get(model.url);
const decorations = [];
modelDecorations.forEach(val => decorations.push(...val));
modelDecorations.forEach((val) => decorations.push(...val));
return decorations;
}
......
......@@ -3,7 +3,7 @@ import { throttle } from 'lodash';
import DirtyDiffWorker from './diff_worker';
import Disposable from '../common/disposable';
export const getDiffChangeType = change => {
export const getDiffChangeType = (change) => {
if (change.modified) {
return 'modified';
} else if (change.added) {
......@@ -15,7 +15,7 @@ export const getDiffChangeType = change => {
return '';
};
export const getDecorator = change => ({
export const getDecorator = (change) => ({
range: new Range(change.lineNumber, 1, change.endLineNumber, 1),
options: {
isWholeLine: true,
......@@ -71,7 +71,7 @@ export default class DirtyDiffController {
}
decorate({ data }) {
const decorations = data.changes.map(change => getDecorator(change));
const decorations = data.changes.map((change) => getDecorator(change));
const model = this.modelManager.getModel(data.path);
this.decorationsController.addDecorations(model, 'dirtyDiff', decorations);
}
......
......@@ -11,7 +11,7 @@ export const computeDiff = (originalContent, newContent) => {
let lineNumber = 1;
return changes.reduce((acc, change) => {
const findOnLine = acc.find(c => c.lineNumber === lineNumber);
const findOnLine = acc.find((c) => c.lineNumber === lineNumber);
if (findOnLine) {
Object.assign(findOnLine, change, {
......
import { computeDiff } from './diff';
// eslint-disable-next-line no-restricted-globals
self.addEventListener('message', e => {
self.addEventListener('message', (e) => {
const { data } = e;
// eslint-disable-next-line no-restricted-globals
......
......@@ -12,7 +12,7 @@ import { clearDomElement } from '~/editor/utils';
import { registerLanguages } from '../utils';
function setupThemes() {
themes.forEach(theme => {
themes.forEach((theme) => {
monacoEditor.defineTheme(theme.name, theme.data);
});
}
......@@ -108,7 +108,7 @@ export default class Editor {
this.instance.updateOptions(
editorOptions.reduce((acc, obj) => {
Object.keys(obj).forEach(key => {
Object.keys(obj).forEach((key) => {
Object.assign(acc, {
[key]: obj[key](model),
});
......@@ -177,7 +177,7 @@ export default class Editor {
onPositionChange(cb) {
if (!this.instance.onDidChangeCursorPosition) return;
this.disposable.add(this.instance.onDidChangeCursorPosition(e => cb(this.instance, e)));
this.disposable.add(this.instance.onDidChangeCursorPosition((e) => cb(this.instance, e)));
}
updateDiffView() {
......@@ -213,14 +213,14 @@ export default class Editor {
addCommands() {
const { store } = this;
const getKeyCode = key => {
const getKeyCode = (key) => {
const monacoKeyMod = key.indexOf('KEY_') === 0;
return monacoKeyMod ? KeyCode[key] : KeyMod[key];
};
keymap.forEach(command => {
const keybindings = command.bindings.map(binding => {
keymap.forEach((command) => {
const keybindings = command.bindings.map((binding) => {
const keys = binding.split('+');
// eslint-disable-next-line no-bitwise
......
......@@ -31,7 +31,7 @@ export const defaultModelOptions = {
export const editorOptions = [
{
readOnly: model => Boolean(model.file.file_lock),
quickSuggestions: model => !(model.language === 'markdown'),
readOnly: (model) => Boolean(model.file.file_lock),
quickSuggestions: (model) => !(model.language === 'markdown'),
},
];
......@@ -2,7 +2,7 @@ import { parseString } from 'editorconfig/src/lib/ini';
import minimatch from 'minimatch';
import { getPathParents } from '../../utils';
const dirname = path => path.replace(/\.editorconfig$/, '');
const dirname = (path) => path.replace(/\.editorconfig$/, '');
function isRootConfig(config) {
return config.some(([pattern, rules]) => !pattern && rules?.root === 'true');
......@@ -44,16 +44,16 @@ function getRulesWithConfigs(filePath, configFiles = [], rules = {}) {
export function getRulesWithTraversal(filePath, getFileContent) {
const editorconfigPaths = [
...getPathParents(filePath).map(x => `${x}/.editorconfig`),
...getPathParents(filePath).map((x) => `${x}/.editorconfig`),
'.editorconfig',
];
return Promise.all(
editorconfigPaths.map(path => getFileContent(path).then(content => ({ path, content }))),
).then(results =>
editorconfigPaths.map((path) => getFileContent(path).then((content) => ({ path, content }))),
).then((results) =>
getRulesWithConfigs(
filePath,
results.filter(x => x.content),
results.filter((x) => x.content),
),
);
}
import { isBoolean, isNumber } from 'lodash';
const map = (key, validValues) => value =>
const map = (key, validValues) => (value) =>
value in validValues ? { [key]: validValues[value] } : {};
const bool = key => value => (isBoolean(value) ? { [key]: value } : {});
const bool = (key) => (value) => (isBoolean(value) ? { [key]: value } : {});
const int = (key, isValid) => value =>
const int = (key, isValid) => (value) =>
isNumber(value) && isValid(value) ? { [key]: Math.trunc(value) } : {};
const rulesMapper = {
indent_style: map('insertSpaces', { tab: false, space: true }),
indent_size: int('tabSize', n => n > 0),
tab_width: int('tabSize', n => n > 0),
indent_size: int('tabSize', (n) => n > 0),
tab_width: int('tabSize', (n) => n > 0),
trim_trailing_whitespace: bool('trimTrailingWhitespace'),
end_of_line: map('endOfLine', { crlf: 1, lf: 0 }),
insert_final_newline: bool('insertFinalNewline'),
};
const parseValue = x => {
const parseValue = (x) => {
let value = typeof x === 'string' ? x.toLowerCase() : x;
if (/^[0-9.-]+$/.test(value)) value = Number(value);
if (value === 'true') value = true;
......
......@@ -6,17 +6,17 @@ const CODEOWNERS_REGEX = /Push.*protected branches.*CODEOWNERS/;
const BRANCH_CHANGED_REGEX = /changed.*since.*start.*edit/;
const BRANCH_ALREADY_EXISTS = /branch.*already.*exists/;
const createNewBranchAndCommit = store =>
const createNewBranchAndCommit = (store) =>
store
.dispatch('commit/updateCommitAction', consts.COMMIT_TO_NEW_BRANCH)
.then(() => store.dispatch('commit/commitChanges'));
export const createUnexpectedCommitError = message => ({
export const createUnexpectedCommitError = (message) => ({
title: __('Unexpected error'),
messageHTML: escape(message) || __('Could not commit. An unexpected error occurred.'),
});
export const createCodeownersCommitError = message => ({
export const createCodeownersCommitError = (message) => ({
title: __('CODEOWNERS rule violation'),
messageHTML: escape(message),
primaryAction: {
......@@ -25,7 +25,7 @@ export const createCodeownersCommitError = message => ({
},
});
export const createBranchChangedCommitError = message => ({
export const createBranchChangedCommitError = (message) => ({
title: __('Branch changed'),
messageHTML: `${escape(message)}<br/><br/>${__('Would you like to create a new branch?')}`,
primaryAction: {
......@@ -34,19 +34,19 @@ export const createBranchChangedCommitError = message => ({
},
});
export const branchAlreadyExistsCommitError = message => ({
export const branchAlreadyExistsCommitError = (message) => ({
title: __('Branch already exists'),
messageHTML: `${escape(message)}<br/><br/>${__(
'Would you like to try auto-generating a branch name?',
)}`,
primaryAction: {
text: __('Create new branch'),
callback: store =>
callback: (store) =>
store.dispatch('commit/addSuffixToBranchName').then(() => createNewBranchAndCommit(store)),
},
});
export const parseCommitError = e => {
export const parseCommitError = (e) => {
const { message } = e?.response?.data || {};
if (!message) {
......
import { decorateData, sortTree } from '../stores/utils';
export const splitParent = path => {
export const splitParent = (path) => {
const idx = path.lastIndexOf('/');
return {
......@@ -32,7 +32,7 @@ export const decorateFiles = ({
let file;
let parentPath;
const insertParent = path => {
const insertParent = (path) => {
if (!path) {
return null;
} else if (entries[path]) {
......@@ -67,7 +67,7 @@ export const decorateFiles = ({
return tree;
};
data.forEach(path => {
data.forEach((path) => {
const { parent, name } = splitParent(path);
const fileFolder = parent && insertParent(parent);
......
......@@ -12,23 +12,23 @@ export const MSG_CONNECTION_ERROR = __('Could not connect to Web IDE file mirror
const noop = () => {};
export const SERVICE_DELAY = 8000;
const cancellableWait = time => {
const cancellableWait = (time) => {
let timeoutId = 0;
const cancel = () => clearTimeout(timeoutId);
const promise = new Promise(resolve => {
const promise = new Promise((resolve) => {
timeoutId = setTimeout(resolve, time);
});
return [promise, cancel];
};
const isErrorResponse = error => error && error.code !== 0;
const isErrorResponse = (error) => error && error.code !== 0;
const isErrorPayload = payload => payload && payload.status_code !== 200;
const isErrorPayload = (payload) => payload && payload.status_code !== 200;
const getErrorFromResponse = data => {
const getErrorFromResponse = (data) => {
if (isErrorResponse(data.error)) {
return { message: data.error.Message };
} else if (isErrorPayload(data.payload)) {
......@@ -38,9 +38,9 @@ const getErrorFromResponse = data => {
return null;
};
const getFullPath = path => mergeUrlParams({ service: SERVICE_NAME }, getWebSocketUrl(path));
const getFullPath = (path) => mergeUrlParams({ service: SERVICE_NAME }, getWebSocketUrl(path));
const createWebSocket = fullPath =>
const createWebSocket = (fullPath) =>
new Promise((resolve, reject) => {
const socket = new WebSocket(fullPath, [PROTOCOL]);
const resetCallbacks = () => {
......@@ -59,7 +59,7 @@ const createWebSocket = fullPath =>
};
});
export const canConnect = ({ services = [] }) => services.some(name => name === SERVICE_NAME);
export const canConnect = ({ services = [] }) => services.some((name) => name === SERVICE_NAME);
export const createMirror = () => {
let socket = null;
......@@ -71,23 +71,23 @@ export const createMirror = () => {
cancelHandler = noop;
};
const onCancelConnect = fn => {
const onCancelConnect = (fn) => {
cancelHandler = fn;
};
const receiveMessage = ev => {
const receiveMessage = (ev) => {
const handle = nextMessageHandler;
nextMessageHandler = noop;
handle(JSON.parse(ev.data));
};
const onNextMessage = fn => {
const onNextMessage = (fn) => {
nextMessageHandler = fn;
};
const waitForNextMessage = () =>
new Promise((resolve, reject) => {
onNextMessage(data => {
onNextMessage((data) => {
const err = getErrorFromResponse(data);
if (err) {
......@@ -133,7 +133,7 @@ export const createMirror = () => {
return wait
.then(() => createWebSocket(fullPath))
.then(newSocket => {
.then((newSocket) => {
socket = newSocket;
socket.onmessage = receiveMessage;
});
......
......@@ -4,9 +4,9 @@ import Api from '~/api';
import getUserPermissions from '../queries/getUserPermissions.query.graphql';
import { query } from './gql';
const fetchApiProjectData = projectPath => Api.project(projectPath).then(({ data }) => data);
const fetchApiProjectData = (projectPath) => Api.project(projectPath).then(({ data }) => data);
const fetchGqlProjectData = projectPath =>
const fetchGqlProjectData = (projectPath) =>
query({
query: getUserPermissions,
variables: { projectPath },
......@@ -31,7 +31,7 @@ export default {
return axios
.get(file.rawPath, {
transformResponse: [f => f],
transformResponse: [(f) => f],
...options,
})
.then(({ data }) => data);
......@@ -54,7 +54,7 @@ export default {
escapeFileUrl(filePath),
),
{
transformResponse: [f => f],
transformResponse: [(f) => f],
},
)
.then(({ data }) => data);
......
import axios from '~/lib/utils/axios_utils';
export const baseUrl = projectPath => `/${projectPath}/ide_terminals`;
export const baseUrl = (projectPath) => `/${projectPath}/ide_terminals`;
export const checkConfig = (projectPath, branch) =>
axios.post(`${baseUrl(projectPath)}/check_config`, {
......
......@@ -20,7 +20,7 @@ export const redirectToUrl = (self, url) => visitUrl(url);
export const setInitialData = ({ commit }, data) => commit(types.SET_INITIAL_DATA, data);
export const discardAllChanges = ({ state, commit, dispatch }) => {
state.changedFiles.forEach(file => dispatch('restoreOriginalFile', file.path));
state.changedFiles.forEach((file) => dispatch('restoreOriginalFile', file.path));
commit(types.REMOVE_ALL_CHANGES_FILES);
};
......@@ -106,7 +106,7 @@ export const stageAllChanges = ({ state, commit, dispatch, getters }) => {
commit(types.SET_LAST_COMMIT_MSG, '');
state.changedFiles.forEach(file =>
state.changedFiles.forEach((file) =>
commit(types.STAGE_CHANGE, { path: file.path, diffInfo: getters.getDiffInfo(file.path) }),
);
......@@ -123,7 +123,7 @@ export const stageAllChanges = ({ state, commit, dispatch, getters }) => {
export const unstageAllChanges = ({ state, commit, dispatch, getters }) => {
const openFile = state.openFiles[0];
state.stagedFiles.forEach(file =>
state.stagedFiles.forEach((file) =>
commit(types.UNSTAGE_CHANGE, { path: file.path, diffInfo: getters.getDiffInfo(file.path) }),
);
......@@ -194,7 +194,7 @@ export const deleteEntry = ({ commit, dispatch, state }, path) => {
if (entry.opened) dispatch('closeFile', entry);
if (isTree) {
entry.tree.forEach(f => dispatch('deleteEntry', f.path));
entry.tree.forEach((f) => dispatch('deleteEntry', f.path));
}
commit(types.DELETE_ENTRY, path);
......@@ -221,7 +221,7 @@ export const renameEntry = ({ dispatch, commit, state, getters }, { path, name,
commit(types.RENAME_ENTRY, { path, name, parentPath });
if (entry.type === 'tree') {
state.entries[newPath].tree.forEach(f => {
state.entries[newPath].tree.forEach((f) => {
dispatch('renameEntry', {
path: f.path,
name: f.name,
......@@ -280,7 +280,7 @@ export const getBranchData = ({ commit, state }, { projectId, branchId, force =
commit(types.SET_BRANCH_WORKING_REFERENCE, { projectId, branchId, reference: id });
resolve(data);
})
.catch(e => {
.catch((e) => {
if (e.response.status === 404) {
reject(e);
} else {
......
......@@ -14,7 +14,7 @@ import { viewerTypes, stageKeys } from '../../constants';
export const closeFile = ({ commit, state, dispatch, getters }, file) => {
const { path } = file;
const indexOfClosedFile = state.openFiles.findIndex(f => f.key === file.key);
const indexOfClosedFile = state.openFiles.findIndex((f) => f.key === file.key);
const fileWasActive = file.active;
if (file.pending) {
......@@ -108,7 +108,7 @@ export const getFileData = (
.catch(() => {
dispatch('setErrorMessage', {
text: __('An error occurred while loading the file.'),
action: payload =>
action: (payload) =>
dispatch('getFileData', payload).then(() => dispatch('setErrorMessage', null)),
actionText: __('Please try again'),
actionPayload: { path, makeFileActive },
......@@ -125,13 +125,13 @@ export const setFileMrChange = ({ commit }, { file, mrChange }) => {
export const getRawFileData = ({ state, commit, dispatch, getters }, { path }) => {
const file = state.entries[path];
const stagedFile = state.stagedFiles.find(f => f.path === path);
const stagedFile = state.stagedFiles.find((f) => f.path === path);
const fileDeletedAndReadded = getters.isFileDeletedAndReadded(path);
commit(types.TOGGLE_LOADING, { entry: file, forceValue: true });
return service
.getRawFileData(fileDeletedAndReadded ? stagedFile : file)
.then(raw => {
.then((raw) => {
if (!(file.tempFile && !file.prevPath && !fileDeletedAndReadded))
commit(types.SET_FILE_RAW_DATA, { file, raw, fileDeletedAndReadded });
......@@ -139,7 +139,7 @@ export const getRawFileData = ({ state, commit, dispatch, getters }, { path }) =
const baseSha =
(getters.currentMergeRequest && getters.currentMergeRequest.baseCommitSha) || '';
return service.getBaseRawFileData(file, state.currentProjectId, baseSha).then(baseRaw => {
return service.getBaseRawFileData(file, state.currentProjectId, baseSha).then((baseRaw) => {
commit(types.SET_FILE_BASE_RAW_DATA, {
file,
baseRaw,
......@@ -149,10 +149,10 @@ export const getRawFileData = ({ state, commit, dispatch, getters }, { path }) =
}
return raw;
})
.catch(e => {
.catch((e) => {
dispatch('setErrorMessage', {
text: __('An error occurred while loading the file content.'),
action: payload =>
action: (payload) =>
dispatch('getRawFileData', payload).then(() => dispatch('setErrorMessage', null)),
actionText: __('Please try again'),
actionPayload: { path },
......@@ -178,7 +178,7 @@ export const changeFileContent = ({ commit, state, getters }, { path, content })
content,
});
const indexOfChangedFile = state.changedFiles.findIndex(f => f.path === path);
const indexOfChangedFile = state.changedFiles.findIndex((f) => f.path === path);
if (file.changed && indexOfChangedFile === -1) {
commit(types.STAGE_CHANGE, { path, diffInfo: getters.getDiffInfo(path) });
......@@ -225,7 +225,7 @@ export const discardFileChanges = ({ dispatch, state, commit, getters }, path) =
.then(() => {
dispatch('router/push', getters.getUrlForPath(file.path), { root: true });
})
.catch(e => {
.catch((e) => {
throw e;
});
}
......@@ -275,7 +275,7 @@ export const unstageChange = ({ commit, dispatch, getters }, path) => {
export const openPendingTab = ({ commit, dispatch, getters, state }, { file, keyPrefix }) => {
if (getters.activeFile && getters.activeFile.key === `${keyPrefix}-${file.key}`) return false;
state.openFiles.forEach(f => eventHub.$emit(`editor.update.model.dispose.${f.key}`));
state.openFiles.forEach((f) => eventHub.$emit(`editor.update.model.dispose.${f.key}`));
commit(types.ADD_PENDING_TAB, { file, keyPrefix });
......
......@@ -33,7 +33,7 @@ export const getMergeRequestsForBranch = (
commit(types.SET_CURRENT_MERGE_REQUEST, `${currentMR.iid}`);
}
})
.catch(e => {
.catch((e) => {
flash(
__(`Error fetching merge requests for ${branchId}`),
'alert',
......@@ -66,7 +66,7 @@ export const getMergeRequestData = (
.catch(() => {
dispatch('setErrorMessage', {
text: __('An error occurred while loading the merge request.'),
action: payload =>
action: (payload) =>
dispatch('getMergeRequestData', payload).then(() =>
dispatch('setErrorMessage', null),
),
......@@ -99,7 +99,7 @@ export const getMergeRequestChanges = (
.catch(() => {
dispatch('setErrorMessage', {
text: __('An error occurred while loading the merge request changes.'),
action: payload =>
action: (payload) =>
dispatch('getMergeRequestChanges', payload).then(() =>
dispatch('setErrorMessage', null),
),
......@@ -121,8 +121,8 @@ export const getMergeRequestVersions = (
if (!state.projects[projectId].mergeRequests[mergeRequestId].versions.length || force) {
service
.getProjectMergeRequestVersions(targetProjectId || projectId, mergeRequestId)
.then(res => res.data)
.then(data => {
.then((res) => res.data)
.then((data) => {
commit(types.SET_MERGE_REQUEST_VERSIONS, {
projectPath: projectId,
mergeRequestId,
......@@ -133,7 +133,7 @@ export const getMergeRequestVersions = (
.catch(() => {
dispatch('setErrorMessage', {
text: __('An error occurred while loading the merge request version data.'),
action: payload =>
action: (payload) =>
dispatch('getMergeRequestVersions', payload).then(() =>
dispatch('setErrorMessage', null),
),
......@@ -156,7 +156,7 @@ export const openMergeRequest = (
targetProjectId,
mergeRequestId,
})
.then(mr => {
.then((mr) => {
dispatch('setCurrentBranchId', mr.source_branch);
return dispatch('getBranchData', {
......@@ -186,7 +186,7 @@ export const openMergeRequest = (
mergeRequestId,
}),
)
.then(mrChanges => {
.then((mrChanges) => {
if (mrChanges.changes.length) {
dispatch('updateActivityBarView', leftSidebarViews.review.name);
}
......@@ -210,7 +210,7 @@ export const openMergeRequest = (
}
});
})
.catch(e => {
.catch((e) => {
flash(__('Error while loading the merge request. Please try again.'));
throw e;
});
......@@ -11,8 +11,8 @@ export const getProjectData = ({ commit, state }, { namespace, projectId, force
commit(types.TOGGLE_LOADING, { entry: state });
service
.getProjectData(namespace, projectId)
.then(res => res.data)
.then(data => {
.then((res) => res.data)
.then((data) => {
commit(types.TOGGLE_LOADING, { entry: state });
commit(types.SET_PROJECT, { projectPath: `${namespace}/${projectId}`, project: data });
commit(types.SET_CURRENT_PROJECT, `${namespace}/${projectId}`);
......@@ -61,7 +61,7 @@ export const createNewBranchFromDefault = ({ state, dispatch, getters }, branch)
.catch(() => {
dispatch('setErrorMessage', {
text: __('An error occurred creating the new branch.'),
action: payload => dispatch('createNewBranchFromDefault', payload),
action: (payload) => dispatch('createNewBranchFromDefault', payload),
actionText: __('Please try again'),
actionPayload: branch,
});
......@@ -76,7 +76,7 @@ export const showBranchNotFoundError = ({ dispatch }, branchId) => {
},
false,
),
action: payload => dispatch('createNewBranchFromDefault', payload),
action: (payload) => dispatch('createNewBranchFromDefault', payload),
actionText: __('Create branch'),
actionPayload: branchId,
});
......@@ -102,7 +102,7 @@ export const loadFile = ({ dispatch, state }, { basePath }) => {
if (basePath) {
const path = basePath.slice(-1) === '/' ? basePath.slice(0, -1) : basePath;
const treeEntryKey = Object.keys(state.entries).find(
key => key === path && !state.entries[key].pending,
(key) => key === path && !state.entries[key].pending,
);
const treeEntry = state.entries[treeEntryKey];
......@@ -144,7 +144,7 @@ export const loadBranch = ({ dispatch, getters, state }, { projectId, branchId }
ref: branch.commit.id,
});
})
.catch(err => {
.catch((err) => {
dispatch('showBranchNotFoundError', branchId);
throw err;
});
......
......@@ -87,10 +87,10 @@ export const getFiles = ({ state, commit, dispatch }, payload = {}) => {
resolve();
})
.catch(e => {
.catch((e) => {
dispatch('setErrorMessage', {
text: __('An error occurred while loading all the files.'),
action: actionPayload =>
action: (actionPayload) =>
dispatch('getFiles', actionPayload).then(() => dispatch('setErrorMessage', null)),
actionText: __('Please try again'),
actionPayload: { projectId, branchId },
......
......@@ -8,7 +8,7 @@ const plugins = () => [
export default (store, el) => {
// plugins is actually an array of plugin factories, so we have to create first then call
plugins().forEach(plugin => plugin(el)(store));
plugins().forEach((plugin) => plugin(el)(store));
return store;
};
......@@ -9,19 +9,19 @@ import {
import { addNumericSuffix } from '~/ide/utils';
import Api from '~/api';
export const activeFile = state => state.openFiles.find(file => file.active) || null;
export const activeFile = (state) => state.openFiles.find((file) => file.active) || null;
export const addedFiles = state => state.changedFiles.filter(f => f.tempFile);
export const addedFiles = (state) => state.changedFiles.filter((f) => f.tempFile);
export const modifiedFiles = state => state.changedFiles.filter(f => !f.tempFile);
export const modifiedFiles = (state) => state.changedFiles.filter((f) => !f.tempFile);
export const projectsWithTrees = state =>
Object.keys(state.projects).map(projectId => {
export const projectsWithTrees = (state) =>
Object.keys(state.projects).map((projectId) => {
const project = state.projects[projectId];
return {
...project,
branches: Object.keys(project.branches).map(branchId => {
branches: Object.keys(project.branches).map((branchId) => {
const branch = project.branches[branchId];
return {
......@@ -32,7 +32,7 @@ export const projectsWithTrees = state =>
};
});
export const currentMergeRequest = state => {
export const currentMergeRequest = (state) => {
if (
state.projects[state.currentProjectId] &&
state.projects[state.currentProjectId].mergeRequests
......@@ -42,19 +42,19 @@ export const currentMergeRequest = state => {
return null;
};
export const findProject = state => projectId => state.projects[projectId];
export const findProject = (state) => (projectId) => state.projects[projectId];
export const currentProject = (state, getters) => getters.findProject(state.currentProjectId);
export const emptyRepo = state =>
export const emptyRepo = (state) =>
state.projects[state.currentProjectId] && state.projects[state.currentProjectId].empty_repo;
export const currentTree = state =>
export const currentTree = (state) =>
state.trees[`${state.currentProjectId}/${state.currentBranchId}`];
export const hasMergeRequest = state => Boolean(state.currentMergeRequestId);
export const hasMergeRequest = (state) => Boolean(state.currentMergeRequestId);
export const allBlobs = state =>
export const allBlobs = (state) =>
Object.keys(state.entries)
.reduce((acc, key) => {
const entry = state.entries[key];
......@@ -67,35 +67,35 @@ export const allBlobs = state =>
}, [])
.sort((a, b) => b.lastOpenedAt - a.lastOpenedAt);
export const getChangedFile = state => path => state.changedFiles.find(f => f.path === path);
export const getStagedFile = state => path => state.stagedFiles.find(f => f.path === path);
export const getOpenFile = state => path => state.openFiles.find(f => f.path === path);
export const getChangedFile = (state) => (path) => state.changedFiles.find((f) => f.path === path);
export const getStagedFile = (state) => (path) => state.stagedFiles.find((f) => f.path === path);
export const getOpenFile = (state) => (path) => state.openFiles.find((f) => f.path === path);
export const lastOpenedFile = state =>
export const lastOpenedFile = (state) =>
[...state.changedFiles, ...state.stagedFiles].sort((a, b) => b.lastOpenedAt - a.lastOpenedAt)[0];
export const isEditModeActive = state => state.currentActivityView === leftSidebarViews.edit.name;
export const isCommitModeActive = state =>
export const isEditModeActive = (state) => state.currentActivityView === leftSidebarViews.edit.name;
export const isCommitModeActive = (state) =>
state.currentActivityView === leftSidebarViews.commit.name;
export const isReviewModeActive = state =>
export const isReviewModeActive = (state) =>
state.currentActivityView === leftSidebarViews.review.name;
export const someUncommittedChanges = state =>
export const someUncommittedChanges = (state) =>
Boolean(state.changedFiles.length || state.stagedFiles.length);
export const getChangesInFolder = state => path => {
const changedFilesCount = state.changedFiles.filter(f => filePathMatches(f.path, path)).length;
export const getChangesInFolder = (state) => (path) => {
const changedFilesCount = state.changedFiles.filter((f) => filePathMatches(f.path, path)).length;
const stagedFilesCount = state.stagedFiles.filter(
f => filePathMatches(f.path, path) && !getChangedFile(state)(f.path),
(f) => filePathMatches(f.path, path) && !getChangedFile(state)(f.path),
).length;
return changedFilesCount + stagedFilesCount;
};
export const getUnstagedFilesCountForPath = state => path =>
export const getUnstagedFilesCountForPath = (state) => (path) =>
getChangesCountForFiles(state.changedFiles, path);
export const getStagedFilesCountForPath = state => path =>
export const getStagedFilesCountForPath = (state) => (path) =>
getChangesCountForFiles(state.stagedFiles, path);
export const lastCommit = (state, getters) => {
......@@ -115,7 +115,7 @@ export const currentBranch = (state, getters) =>
export const branchName = (_state, getters) => getters.currentBranch && getters.currentBranch.name;
export const packageJson = state => state.entries[packageJsonPath];
export const packageJson = (state) => state.entries[packageJsonPath];
export const isOnDefaultBranch = (_state, getters) =>
getters.currentProject && getters.currentProject.default_branch === getters.branchName;
......@@ -124,14 +124,14 @@ export const canPushToBranch = (_state, getters) => {
return Boolean(getters.currentBranch ? getters.currentBranch.can_push : getters.canPushCode);
};
export const isFileDeletedAndReadded = (state, getters) => path => {
export const isFileDeletedAndReadded = (state, getters) => (path) => {
const stagedFile = getters.getStagedFile(path);
const file = state.entries[path];
return Boolean(stagedFile && stagedFile.deleted && file.tempFile);
};
// checks if any diff exists in the staged or unstaged changes for this path
export const getDiffInfo = (state, getters) => path => {
export const getDiffInfo = (state, getters) => (path) => {
const stagedFile = getters.getStagedFile(path);
const file = state.entries[path];
const renamed = file.prevPath ? file.path !== file.prevPath : false;
......@@ -149,7 +149,7 @@ export const getDiffInfo = (state, getters) => path => {
};
};
export const findProjectPermissions = (state, getters) => projectId =>
export const findProjectPermissions = (state, getters) => (projectId) =>
getters.findProject(projectId)?.userPermissions || {};
export const canReadMergeRequests = (state, getters) =>
......@@ -161,10 +161,10 @@ export const canCreateMergeRequests = (state, getters) =>
export const canPushCode = (state, getters) =>
Boolean(getters.findProjectPermissions(state.currentProjectId)[PERMISSION_PUSH_CODE]);
export const entryExists = state => path =>
export const entryExists = (state) => (path) =>
Boolean(state.entries[path] && !state.entries[path].deleted);
export const getAvailableFileName = (state, getters) => path => {
export const getAvailableFileName = (state, getters) => (path) => {
let newPath = path;
while (getters.entryExists(newPath)) {
......@@ -174,10 +174,10 @@ export const getAvailableFileName = (state, getters) => path => {
return newPath;
};
export const getUrlForPath = state => path =>
export const getUrlForPath = (state) => (path) =>
`/project/${state.currentProjectId}/tree/${state.currentBranchId}/-/${path}/`;
export const getJsonSchemaForPath = (state, getters) => path => {
export const getJsonSchemaForPath = (state, getters) => (path) => {
const [namespace, ...project] = state.currentProjectId.split('/');
return {
uri:
......
......@@ -8,7 +8,7 @@ export const receiveBranchesError = ({ commit, dispatch }, { search }) => {
'setErrorMessage',
{
text: __('Error loading branches.'),
action: payload =>
action: (payload) =>
dispatch('fetchBranches', payload).then(() =>
dispatch('setErrorMessage', null, { root: true }),
),
......
......@@ -9,7 +9,7 @@ export default {
},
[types.RECEIVE_BRANCHES_SUCCESS](state, data) {
state.isLoading = false;
state.branches = data.map(branch => ({
state.branches = data.map((branch) => ({
name: branch.name,
committedDate: branch.commit.committed_date,
}));
......
......@@ -78,8 +78,8 @@ export const updateFilesAfterCommit = ({ commit, dispatch, rootState, rootGetter
{ root: true },
);
rootState.stagedFiles.forEach(file => {
const changedFile = rootState.changedFiles.find(f => f.path === file.path);
rootState.stagedFiles.forEach((file) => {
const changedFile = rootState.changedFiles.find((f) => f.path === file.path);
commit(
rootTypes.UPDATE_FILE_AFTER_COMMIT,
......@@ -133,7 +133,7 @@ export const commitChanges = ({ commit, state, getters, dispatch, rootState, roo
return service.commit(rootState.currentProjectId, payload);
})
.catch(e => {
.catch((e) => {
commit(types.UPDATE_LOADING, false);
commit(types.SET_ERROR, parseCommitError(e));
......@@ -193,12 +193,12 @@ export const commitChanges = ({ commit, state, getters, dispatch, rootState, roo
},
{ root: true },
)
.then(changeViewer => {
.then((changeViewer) => {
if (changeViewer) {
dispatch('updateViewer', 'diff', { root: true });
}
})
.catch(e => {
.catch((e) => {
throw e;
});
} else {
......
......@@ -11,7 +11,7 @@ const createTranslatedTextForFiles = (files, text) => {
});
};
export const discardDraftButtonDisabled = state =>
export const discardDraftButtonDisabled = (state) =>
state.commitMessage === '' || state.submitCommitLoading;
// Note: If changing the structure of the placeholder branch name, please also
......@@ -37,18 +37,18 @@ export const preBuiltCommitMessage = (state, _, rootState) => {
if (state.commitMessage) return state.commitMessage;
const files = rootState.stagedFiles.length ? rootState.stagedFiles : rootState.changedFiles;
const modifiedFiles = files.filter(f => !f.deleted);
const deletedFiles = files.filter(f => f.deleted);
const modifiedFiles = files.filter((f) => !f.deleted);
const deletedFiles = files.filter((f) => f.deleted);
return [
createTranslatedTextForFiles(modifiedFiles, __('Update')),
createTranslatedTextForFiles(deletedFiles, __('Deleted')),
]
.filter(t => t)
.filter((t) => t)
.join('\n');
};
export const isCreatingNewBranch = state => state.commitAction === consts.COMMIT_TO_NEW_BRANCH;
export const isCreatingNewBranch = (state) => state.commitAction === consts.COMMIT_TO_NEW_BRANCH;
export const shouldHideNewMrOption = (_state, getters, _rootState, rootGetters) =>
!getters.isCreatingNewBranch &&
......
import eventHub from '~/ide/eventhub';
import { commitActionTypes } from '~/ide/constants';
const removeUnusedFileEditors = store => {
const removeUnusedFileEditors = (store) => {
Object.keys(store.state.editor.fileEditors)
.filter(path => !store.state.entries[path])
.forEach(path => store.dispatch('editor/removeFileEditor', path));
.filter((path) => !store.state.entries[path])
.forEach((path) => store.dispatch('editor/removeFileEditor', path));
};
export const setupFileEditorsSync = store => {
export const setupFileEditorsSync = (store) => {
eventHub.$on('ide.files.change', ({ type, ...payload } = {}) => {
if (type === commitActionTypes.move) {
store.dispatch('editor/renameFileEditor', payload);
......
......@@ -68,7 +68,7 @@ export const receiveTemplateError = ({ dispatch }, template) => {
'setErrorMessage',
{
text: __('Error loading template.'),
action: payload =>
action: (payload) =>
dispatch('fetchTemplateTypes', payload).then(() =>
dispatch('setErrorMessage', null, { root: true }),
),
......
......@@ -24,6 +24,6 @@ export const templateTypes = () => [
},
];
export const showFileTemplatesBar = (_, getters, rootState) => name =>
getters.templateTypes.find(t => t.name === name) &&
export const showFileTemplatesBar = (_, getters, rootState) => (name) =>
getters.templateTypes.find((t) => t.name === name) &&
rootState.currentActivityView === leftSidebarViews.edit.name;
......@@ -9,7 +9,7 @@ export const receiveMergeRequestsError = ({ commit, dispatch }, { type, search }
'setErrorMessage',
{
text: __('Error loading merge requests.'),
action: payload =>
action: (payload) =>
dispatch('fetchMergeRequests', payload).then(() =>
dispatch('setErrorMessage', null, { root: true }),
),
......
......@@ -9,7 +9,7 @@ export default {
},
[types.RECEIVE_MERGE_REQUESTS_SUCCESS](state, data) {
state.isLoading = false;
state.mergeRequests = data.map(mergeRequest => ({
state.mergeRequests = data.map((mergeRequest) => ({
id: mergeRequest.id,
iid: mergeRequest.iid,
title: mergeRequest.title,
......
export const isAliveView = state => view =>
export const isAliveView = (state) => (view) =>
state.keepAliveViews[view] || (state.isOpen && state.currentView === view);
......@@ -47,7 +47,7 @@ export const receiveLatestPipelineSuccess = ({ rootGetters, commit }, { pipeline
if (pipelines && pipelines.length) {
const lastCommitHash = rootGetters.lastCommit && rootGetters.lastCommit.id;
lastCommitPipeline = pipelines.find(pipeline => pipeline.commit.id === lastCommitHash);
lastCommitPipeline = pipelines.find((pipeline) => pipeline.commit.id === lastCommitHash);
}
commit(types.RECEIVE_LASTEST_PIPELINE_SUCCESS, lastCommitPipeline);
......@@ -63,7 +63,7 @@ export const fetchLatestPipeline = ({ dispatch, rootGetters }) => {
method: 'lastCommitPipelines',
data: { getters: rootGetters },
successCallback: ({ data }) => dispatch('receiveLatestPipelineSuccess', data),
errorCallback: err => dispatch('receiveLatestPipelineError', err),
errorCallback: (err) => dispatch('receiveLatestPipelineError', err),
});
if (!Visibility.hidden()) {
......@@ -85,7 +85,7 @@ export const receiveJobsError = ({ commit, dispatch }, stage) => {
'setErrorMessage',
{
text: __('An error occurred while loading the pipelines jobs.'),
action: payload =>
action: (payload) =>
dispatch('fetchJobs', payload).then(() =>
dispatch('setErrorMessage', null, { root: true }),
),
......
......@@ -23,7 +23,7 @@ export default {
yamlError: pipeline.yaml_errors,
};
state.stages = pipeline.details.stages.map((stage, i) => {
const foundStage = state.stages.find(s => s.id === i);
const foundStage = state.stages.find((s) => s.id === i);
return {
id: i,
dropdownPath: stage.dropdown_path,
......@@ -39,26 +39,26 @@ export default {
}
},
[types.REQUEST_JOBS](state, id) {
state.stages = state.stages.map(stage => ({
state.stages = state.stages.map((stage) => ({
...stage,
isLoading: stage.id === id ? true : stage.isLoading,
}));
},
[types.RECEIVE_JOBS_ERROR](state, id) {
state.stages = state.stages.map(stage => ({
state.stages = state.stages.map((stage) => ({
...stage,
isLoading: stage.id === id ? false : stage.isLoading,
}));
},
[types.RECEIVE_JOBS_SUCCESS](state, { id, data }) {
state.stages = state.stages.map(stage => ({
state.stages = state.stages.map((stage) => ({
...stage,
isLoading: stage.id === id ? false : stage.isLoading,
jobs: stage.id === id ? data.latest_statuses.map(normalizeJob) : stage.jobs,
}));
},
[types.TOGGLE_STAGE_COLLAPSE](state, id) {
state.stages = state.stages.map(stage => ({
state.stages = state.stages.map((stage) => ({
...stage,
isCollapsed: stage.id === id ? !stage.isCollapsed : stage.isCollapsed,
}));
......
export const normalizeJob = job => ({
export const normalizeJob = (job) => ({
id: job.id,
name: job.name,
status: job.status,
......
......@@ -36,7 +36,7 @@ export const fetchConfigCheck = ({ dispatch, rootState, rootGetters }) => {
.then(() => {
dispatch('receiveConfigCheckSuccess');
})
.catch(e => {
.catch((e) => {
dispatch('receiveConfigCheckError', e);
});
};
......@@ -92,7 +92,7 @@ export const fetchRunnersCheck = ({ dispatch, rootGetters }, options = {}) => {
.then(({ data }) => {
dispatch('receiveRunnersCheckSuccess', data);
})
.catch(e => {
.catch((e) => {
dispatch('receiveRunnersCheckError', e);
});
};
......@@ -45,7 +45,7 @@ export const startSession = ({ state, dispatch, rootGetters, rootState }) => {
.then(({ data }) => {
dispatch('receiveStartSessionSuccess', data);
})
.catch(error => {
.catch((error) => {
dispatch('receiveStartSessionError', error);
});
};
......@@ -73,7 +73,7 @@ export const stopSession = ({ state, dispatch }) => {
.then(() => {
dispatch('receiveStopSessionSuccess');
})
.catch(err => {
.catch((err) => {
dispatch('receiveStopSessionError', err);
});
};
......@@ -103,7 +103,7 @@ export const restartSession = ({ state, dispatch, rootState }) => {
.then(({ data }) => {
dispatch('receiveStartSessionSuccess', data);
})
.catch(error => {
.catch((error) => {
const responseStatus = error.response && error.response.status;
// We may have removed the build, in this case we'll just create a new session
if (
......
......@@ -58,7 +58,7 @@ export const fetchSessionStatus = ({ dispatch, state }) => {
.then(({ data }) => {
dispatch('receiveSessionStatusSuccess', data);
})
.catch(error => {
.catch((error) => {
dispatch('receiveSessionStatusError', error);
});
};
export const allCheck = state => {
export const allCheck = (state) => {
const checks = Object.values(state.checks);
if (checks.some(check => check.isLoading)) {
if (checks.some((check) => check.isLoading)) {
return { isLoading: true };
}
const invalidCheck = checks.find(check => !check.isValid);
const invalidCheck = checks.find((check) => !check.isValid);
const isValid = !invalidCheck;
const message = !invalidCheck ? '' : invalidCheck.message;
......
......@@ -46,7 +46,7 @@ export const configCheckError = (status, helpUrl) => {
return UNEXPECTED_ERROR_CONFIG;
};
export const runnersCheckEmpty = helpUrl =>
export const runnersCheckEmpty = (helpUrl) =>
sprintf(
EMPTY_RUNNERS,
{
......
import { STARTING, PENDING, RUNNING } from './constants';
export const isStartingStatus = status => status === STARTING || status === PENDING;
export const isRunningStatus = status => status === RUNNING;
export const isEndingStatus = status => !isStartingStatus(status) && !isRunningStatus(status);
export const isStartingStatus = (status) => status === STARTING || status === PENDING;
export const isRunningStatus = (status) => status === RUNNING;
export const isEndingStatus = (status) => !isStartingStatus(status) && !isRunningStatus(status);
......@@ -9,7 +9,7 @@ export const upload = ({ rootState, commit }) => {
.then(() => {
commit(types.SET_SUCCESS);
})
.catch(err => {
.catch((err) => {
commit(types.SET_ERROR, err);
});
};
......@@ -34,7 +34,7 @@ export const start = ({ rootState, commit }) => {
.then(() => {
commit(types.SET_SUCCESS);
})
.catch(err => {
.catch((err) => {
commit(types.SET_ERROR, err);
throw err;
});
......
......@@ -61,7 +61,7 @@ export default {
});
} else {
const tree = entry.tree.filter(
f => foundEntry.tree.find(e => e.path === f.path) === undefined,
(f) => foundEntry.tree.find((e) => e.path === f.path) === undefined,
);
Object.assign(foundEntry, {
tree: sortTree(foundEntry.tree.concat(tree)),
......@@ -72,7 +72,7 @@ export default {
}, []);
const currentTree = state.trees[`${state.currentProjectId}/${state.currentBranchId}`];
const foundEntry = currentTree.tree.find(e => e.path === data.treeList[0].path);
const foundEntry = currentTree.tree.find((e) => e.path === data.treeList[0].path);
if (!foundEntry) {
Object.assign(currentTree, {
......@@ -125,7 +125,7 @@ export default {
});
},
[types.UPDATE_FILE_AFTER_COMMIT](state, { file, lastCommit }) {
const changedFile = state.changedFiles.find(f => f.path === file.path);
const changedFile = state.changedFiles.find((f) => f.path === file.path);
const { prevPath } = file;
Object.assign(state.entries[file.path], {
......@@ -172,7 +172,7 @@ export default {
entry.deleted = true;
if (parent) {
parent.tree = parent.tree.filter(f => f.path !== entry.path);
parent.tree = parent.tree.filter((f) => f.path !== entry.path);
}
if (entry.type === 'blob') {
......@@ -181,8 +181,8 @@ export default {
// changed and staged. Otherwise, we'd need to somehow evaluate the difference between
// changed and HEAD.
// https://gitlab.com/gitlab-org/create-stage/-/issues/12669
state.changedFiles = state.changedFiles.filter(f => f.path !== path);
state.stagedFiles = state.stagedFiles.filter(f => f.path !== path);
state.changedFiles = state.changedFiles.filter((f) => f.path !== path);
state.stagedFiles = state.stagedFiles.filter((f) => f.path !== path);
} else {
state.changedFiles = state.changedFiles.concat(entry);
}
......
......@@ -12,7 +12,7 @@ export default {
if (active && !state.entries[path].pending) {
Object.assign(state, {
openFiles: state.openFiles.map(f =>
openFiles: state.openFiles.map((f) =>
Object.assign(f, { active: f.pending ? false : f.active }),
),
});
......@@ -28,21 +28,21 @@ export default {
if (entry.opened) {
Object.assign(state, {
openFiles: state.openFiles.filter(f => f.path !== path).concat(state.entries[path]),
openFiles: state.openFiles.filter((f) => f.path !== path).concat(state.entries[path]),
});
} else {
Object.assign(state, {
openFiles: state.openFiles.filter(f => f.key !== entry.key),
openFiles: state.openFiles.filter((f) => f.key !== entry.key),
});
}
},
[types.SET_FILE_DATA](state, { data, file }) {
const stateEntry = state.entries[file.path];
const stagedFile = state.stagedFiles.find(f => f.path === file.path);
const openFile = state.openFiles.find(f => f.path === file.path);
const changedFile = state.changedFiles.find(f => f.path === file.path);
const stagedFile = state.stagedFiles.find((f) => f.path === file.path);
const openFile = state.openFiles.find((f) => f.path === file.path);
const changedFile = state.changedFiles.find((f) => f.path === file.path);
[stateEntry, stagedFile, openFile, changedFile].forEach(f => {
[stateEntry, stagedFile, openFile, changedFile].forEach((f) => {
if (f) {
Object.assign(
f,
......@@ -57,10 +57,10 @@ export default {
},
[types.SET_FILE_RAW_DATA](state, { file, raw, fileDeletedAndReadded = false }) {
const openPendingFile = state.openFiles.find(
f =>
(f) =>
f.path === file.path && f.pending && !(f.tempFile && !f.prevPath && !fileDeletedAndReadded),
);
const stagedFile = state.stagedFiles.find(f => f.path === file.path);
const stagedFile = state.stagedFiles.find((f) => f.path === file.path);
if (file.tempFile && file.content === '' && !fileDeletedAndReadded) {
Object.assign(state.entries[file.path], { content: raw });
......@@ -86,7 +86,7 @@ export default {
});
},
[types.UPDATE_FILE_CONTENT](state, { path, content }) {
const stagedFile = state.stagedFiles.find(f => f.path === path);
const stagedFile = state.stagedFiles.find((f) => f.path === path);
const rawContent = stagedFile ? stagedFile.content : state.entries[path].raw;
const changed = content !== rawContent;
......@@ -112,7 +112,7 @@ export default {
});
},
[types.DISCARD_FILE_CHANGES](state, path) {
const stagedFile = state.stagedFiles.find(f => f.path === path);
const stagedFile = state.stagedFiles.find((f) => f.path === path);
const entry = state.entries[path];
const { deleted } = entry;
......@@ -137,14 +137,14 @@ export default {
},
[types.REMOVE_FILE_FROM_CHANGED](state, path) {
Object.assign(state, {
changedFiles: state.changedFiles.filter(f => f.path !== path),
changedFiles: state.changedFiles.filter((f) => f.path !== path),
});
},
[types.STAGE_CHANGE](state, { path, diffInfo }) {
const stagedFile = state.stagedFiles.find(f => f.path === path);
const stagedFile = state.stagedFiles.find((f) => f.path === path);
Object.assign(state, {
changedFiles: state.changedFiles.filter(f => f.path !== path),
changedFiles: state.changedFiles.filter((f) => f.path !== path),
entries: Object.assign(state.entries, {
[path]: Object.assign(state.entries[path], {
staged: diffInfo.exists,
......@@ -162,12 +162,12 @@ export default {
}
if (!diffInfo.exists) {
state.stagedFiles = state.stagedFiles.filter(f => f.path !== path);
state.stagedFiles = state.stagedFiles.filter((f) => f.path !== path);
}
},
[types.UNSTAGE_CHANGE](state, { path, diffInfo }) {
const changedFile = state.changedFiles.find(f => f.path === path);
const stagedFile = state.stagedFiles.find(f => f.path === path);
const changedFile = state.changedFiles.find((f) => f.path === path);
const stagedFile = state.stagedFiles.find((f) => f.path === path);
if (!changedFile && stagedFile) {
Object.assign(state.entries[path], {
......@@ -182,11 +182,11 @@ export default {
}
if (!diffInfo.exists) {
state.changedFiles = state.changedFiles.filter(f => f.path !== path);
state.changedFiles = state.changedFiles.filter((f) => f.path !== path);
}
Object.assign(state, {
stagedFiles: state.stagedFiles.filter(f => f.path !== path),
stagedFiles: state.stagedFiles.filter((f) => f.path !== path),
entries: Object.assign(state.entries, {
[path]: Object.assign(state.entries[path], {
staged: false,
......@@ -206,7 +206,7 @@ export default {
state.entries[file.path].opened = false;
state.entries[file.path].active = false;
state.entries[file.path].lastOpenedAt = new Date().getTime();
state.openFiles.forEach(f =>
state.openFiles.forEach((f) =>
Object.assign(f, {
opened: false,
active: false,
......@@ -224,13 +224,13 @@ export default {
},
[types.REMOVE_PENDING_TAB](state, file) {
Object.assign(state, {
openFiles: state.openFiles.filter(f => f.key !== file.key),
openFiles: state.openFiles.filter((f) => f.key !== file.key),
});
},
[types.REMOVE_FILE_FROM_STAGED_AND_CHANGED](state, file) {
Object.assign(state, {
changedFiles: state.changedFiles.filter(f => f.key !== file.key),
stagedFiles: state.stagedFiles.filter(f => f.key !== file.key),
changedFiles: state.changedFiles.filter((f) => f.key !== file.key),
stagedFiles: state.stagedFiles.filter((f) => f.key !== file.key),
});
Object.assign(state.entries[file.path], {
......
......@@ -45,7 +45,7 @@ export default {
? state.entries[entry.parentPath]
: state.trees[`${state.currentProjectId}/${state.currentBranchId}`];
if (!parent.tree.find(f => f.path === path)) {
if (!parent.tree.find((f) => f.path === path)) {
parent.tree = sortTree(parent.tree.concat(entry));
}
},
......
......@@ -11,7 +11,7 @@ function getPathsFromData(el) {
}
export default function createTerminalPlugin(el) {
return store => {
return (store) => {
store.registerModule('terminal', terminalModule());
store.dispatch('terminal/setPaths', getPathsFromData(el));
......
......@@ -12,7 +12,7 @@ const UPLOAD_DEBOUNCE = 200;
* - Listens for file change event to control upload.
*/
export default function createMirrorPlugin() {
return store => {
return (store) => {
store.registerModule('terminalSync', terminalSyncModule());
const upload = debounce(() => {
......@@ -36,8 +36,8 @@ export default function createMirrorPlugin() {
};
store.watch(
x => x.terminal && x.terminal.session && x.terminal.session.status,
val => {
(x) => x.terminal && x.terminal.session && x.terminal.session.status,
(val) => {
if (isRunningStatus(val)) {
start();
} else if (isEndingStatus(val)) {
......
......@@ -34,7 +34,7 @@ export const dataStructure = () => ({
mimeType: '',
});
export const decorateData = entity => {
export const decorateData = (entity) => {
const {
id,
type,
......@@ -69,7 +69,7 @@ export const decorateData = entity => {
});
};
export const setPageTitle = title => {
export const setPageTitle = (title) => {
document.title = title;
};
......@@ -78,7 +78,7 @@ export const setPageTitleForFile = (state, file) => {
setPageTitle(title);
};
export const commitActionForFile = file => {
export const commitActionForFile = (file) => {
if (file.prevPath) {
return commitActionTypes.move;
} else if (file.deleted) {
......@@ -90,7 +90,7 @@ export const commitActionForFile = file => {
return commitActionTypes.update;
};
export const getCommitFiles = stagedFiles =>
export const getCommitFiles = (stagedFiles) =>
stagedFiles.reduce((acc, file) => {
if (file.type === 'tree') return acc;
......@@ -109,7 +109,7 @@ export const createCommitPayload = ({
}) => ({
branch,
commit_message: state.commitMessage || getters.preBuiltCommitMessage,
actions: getCommitFiles(rootState.stagedFiles).map(f => {
actions: getCommitFiles(rootState.stagedFiles).map((f) => {
const isBlob = isBlobUrl(f.rawPath);
const content = isBlob ? btoa(f.content) : f.content;
......@@ -139,9 +139,9 @@ const sortTreesByTypeAndName = (a, b) => {
return 0;
};
export const sortTree = sortedTree =>
export const sortTree = (sortedTree) =>
sortedTree
.map(entity =>
.map((entity) =>
Object.assign(entity, {
tree: entity.tree.length ? sortTree(entity.tree) : [],
}),
......@@ -151,7 +151,7 @@ export const sortTree = sortedTree =>
export const filePathMatches = (filePath, path) => filePath.indexOf(`${path}/`) === 0;
export const getChangesCountForFiles = (files, path) =>
files.filter(f => filePathMatches(f.path, path)).length;
files.filter((f) => filePathMatches(f.path, path)).length;
export const mergeTrees = (fromTree, toTree) => {
if (!fromTree || !fromTree.length) {
......@@ -162,7 +162,7 @@ export const mergeTrees = (fromTree, toTree) => {
if (!n) {
return t;
}
const existingTreeNode = t.find(el => el.path === n.path);
const existingTreeNode = t.find((el) => el.path === n.path);
if (existingTreeNode && n.tree.length > 0) {
existingTreeNode.opened = true;
......@@ -183,7 +183,7 @@ export const mergeTrees = (fromTree, toTree) => {
export const swapInStateArray = (state, arr, key, entryPath) =>
Object.assign(state, {
[arr]: state[arr].map(f => (f.key === key ? state.entries[entryPath] : f)),
[arr]: state[arr].map((f) => (f.key === key ? state.entries[entryPath] : f)),
});
export const getEntryOrRoot = (state, path) =>
......@@ -216,12 +216,12 @@ export const removeFromParentTree = (state, oldKey, parentPath) => {
};
export const updateFileCollections = (state, key, entryPath) => {
['openFiles', 'changedFiles', 'stagedFiles'].forEach(fileCollection => {
['openFiles', 'changedFiles', 'stagedFiles'].forEach((fileCollection) => {
swapInStateArray(state, fileCollection, key, entryPath);
});
};
export const cleanTrailingSlash = path => path.replace(/\/$/, '');
export const cleanTrailingSlash = (path) => path.replace(/\/$/, '');
export const pathsAreEqual = (a, b) => {
const cleanA = a ? cleanTrailingSlash(a) : '';
......
......@@ -21,8 +21,8 @@ export const syncRouterAndStore = (router, store) => {
// sync store to router
disposables.push(
store.watch(
state => state.router.fullPath,
fullPath => {
(state) => state.router.fullPath,
(fullPath) => {
if (currentPath === fullPath) {
return;
}
......@@ -36,7 +36,7 @@ export const syncRouterAndStore = (router, store) => {
// sync router to store
disposables.push(
router.afterEach(to => {
router.afterEach((to) => {
if (currentPath === to.fullPath) {
return;
}
......@@ -47,7 +47,7 @@ export const syncRouterAndStore = (router, store) => {
);
const unsync = () => {
disposables.forEach(fn => fn());
disposables.forEach((fn) => fn());
};
return unsync;
......
......@@ -3,17 +3,17 @@ import { flatten, isString } from 'lodash';
import { SIDE_LEFT, SIDE_RIGHT } from './constants';
import { performanceMarkAndMeasure } from '~/performance/utils';
const toLowerCase = x => x.toLowerCase();
const toLowerCase = (x) => x.toLowerCase();
const monacoLanguages = languages.getLanguages();
const monacoExtensions = new Set(
flatten(monacoLanguages.map(lang => lang.extensions?.map(toLowerCase) || [])),
flatten(monacoLanguages.map((lang) => lang.extensions?.map(toLowerCase) || [])),
);
const monacoMimetypes = new Set(
flatten(monacoLanguages.map(lang => lang.mimetypes?.map(toLowerCase) || [])),
flatten(monacoLanguages.map((lang) => lang.mimetypes?.map(toLowerCase) || [])),
);
const monacoFilenames = new Set(
flatten(monacoLanguages.map(lang => lang.filenames?.map(toLowerCase) || [])),
flatten(monacoLanguages.map((lang) => lang.filenames?.map(toLowerCase) || [])),
);
const KNOWN_TYPES = [
......@@ -44,7 +44,7 @@ const KNOWN_TYPES = [
];
export function isTextFile({ name, raw, content, mimeType = '' }) {
const knownType = KNOWN_TYPES.find(type => type.isMatch(mimeType, name));
const knownType = KNOWN_TYPES.find((type) => type.isMatch(mimeType, name));
if (knownType) return knownType.isText;
// does the string contain ascii characters only (ranges from space to tilde, tabs and new lines)
......@@ -56,20 +56,20 @@ export function isTextFile({ name, raw, content, mimeType = '' }) {
return isString(fileContents) && (fileContents === '' || asciiRegex.test(fileContents));
}
export const createPathWithExt = p => {
export const createPathWithExt = (p) => {
const ext = p.lastIndexOf('.') >= 0 ? p.substring(p.lastIndexOf('.') + 1) : '';
return `${p.substring(1, p.lastIndexOf('.') + 1 || p.length)}${ext || '.js'}`;
};
export const trimPathComponents = path =>
export const trimPathComponents = (path) =>
path
.split('/')
.map(s => s.trim())
.map((s) => s.trim())
.join('/');
export function registerLanguages(def, ...defs) {
defs.forEach(lang => registerLanguages(lang));
defs.forEach((lang) => registerLanguages(lang));
const languageId = def.id;
......@@ -80,7 +80,7 @@ export function registerLanguages(def, ...defs) {
export function registerSchema(schema) {
const defaults = [languages.json.jsonDefaults, languages.yaml.yamlDefaults];
defaults.forEach(d =>
defaults.forEach((d) =>
d.setDiagnosticsOptions({
validate: true,
enableSchemaRequest: true,
......@@ -91,7 +91,7 @@ export function registerSchema(schema) {
);
}
export const otherSide = side => (side === SIDE_RIGHT ? SIDE_LEFT : SIDE_RIGHT);
export const otherSide = (side) => (side === SIDE_RIGHT ? SIDE_LEFT : SIDE_RIGHT);
export function trimTrailingWhitespace(content) {
return content.replace(/[^\S\r\n]+$/gm, '');
......@@ -125,9 +125,9 @@ export function getPathParent(path) {
* @param {File} file
*/
export function readFileAsDataURL(file) {
return new Promise(resolve => {
return new Promise((resolve) => {
const reader = new FileReader();
reader.addEventListener('load', e => resolve(e.target.result), { once: true });
reader.addEventListener('load', (e) => resolve(e.target.result), { once: true });
reader.readAsDataURL(file);
});
}
......
......@@ -3,7 +3,7 @@ import { spriteIcon } from '~/lib/utils/common_utils';
export function createImageBadge(noteId, { x, y }, classNames = []) {
const buttonEl = document.createElement('button');
const classList = classNames.concat(['js-image-badge']);
classList.forEach(className => buttonEl.classList.add(className));
classList.forEach((className) => buttonEl.classList.add(className));
buttonEl.setAttribute('type', 'button');
buttonEl.setAttribute('disabled', true);
buttonEl.dataset.noteId = noteId;
......
......@@ -7,7 +7,7 @@ export default () => {
const renderCommentBadge = true;
const diffFileEls = document.querySelectorAll('.timeline-content .diff-file.js-image-file');
[...diffFileEls].forEach(diffFileEl =>
[...diffFileEls].forEach((diffFileEl) =>
initImageDiffHelper.initImageDiff(diffFileEl, canCreateNote, renderCommentBadge),
);
};
......@@ -26,7 +26,7 @@ export default class ReplacedImageDiff extends ImageDiff {
this.imageEls = {};
const viewTypeNames = Object.getOwnPropertyNames(viewTypes);
viewTypeNames.forEach(viewType => {
viewTypeNames.forEach((viewType) => {
this.imageEls[viewType] = this.imageFrameEls[viewType].querySelector('img');
});
}
......@@ -62,7 +62,7 @@ export default class ReplacedImageDiff extends ImageDiff {
// Clear existing badges on new view
const existingBadges = this.imageFrameEl.querySelectorAll('.badge');
[...existingBadges].map(badge => badge.remove());
[...existingBadges].map((badge) => badge.remove());
// Remove existing references to old view image badges
this.imageBadges = [];
......
......@@ -5,5 +5,5 @@ export const viewTypes = {
};
export function isValidViewType(validate) {
return Boolean(Object.getOwnPropertyNames(viewTypes).find(viewType => viewType === validate));
return Boolean(Object.getOwnPropertyNames(viewTypes).find((viewType) => viewType === validate));
}
......@@ -7,7 +7,7 @@ import setNewNameMutation from '../graphql/mutations/set_new_name.mutation.graph
import importGroupMutation from '../graphql/mutations/import_group.mutation.graphql';
import ImportTableRow from './import_table_row.vue';
const mapApolloMutations = mutations =>
const mapApolloMutations = (mutations) =>
Object.fromEntries(
Object.entries(mutations).map(([key, mutation]) => [
key,
......
......@@ -35,7 +35,7 @@ export default {
select2Options() {
return {
data: this.availableNamespaces.map(namespace => ({
data: this.availableNamespaces.map((namespace) => ({
id: namespace.full_path,
text: namespace.full_path,
})),
......
......@@ -23,7 +23,7 @@ export function createResolvers({ endpoints }) {
} = await client.query({ query: availableNamespacesQuery });
return axios.get(endpoints.status).then(({ data }) => {
return data.importable_data.map(group => ({
return data.importable_data.map((group) => ({
__typename: clientTypenames.BulkImportSourceGroup,
...group,
status: STATUSES.NONE,
......@@ -37,7 +37,7 @@ export function createResolvers({ endpoints }) {
availableNamespaces: () =>
axios.get(endpoints.availableNamespaces).then(({ data }) =>
data.map(namespace => ({
data.map((namespace) => ({
__typename: clientTypenames.AvailableNamespace,
...namespace,
})),
......@@ -45,14 +45,14 @@ export function createResolvers({ endpoints }) {
},
Mutation: {
setTargetNamespace(_, { targetNamespace, sourceGroupId }, { client }) {
new SourceGroupsManager({ client }).updateById(sourceGroupId, sourceGroup => {
new SourceGroupsManager({ client }).updateById(sourceGroupId, (sourceGroup) => {
// eslint-disable-next-line no-param-reassign
sourceGroup.import_target.target_namespace = targetNamespace;
});
},
setNewName(_, { newName, sourceGroupId }, { client }) {
new SourceGroupsManager({ client }).updateById(sourceGroupId, sourceGroup => {
new SourceGroupsManager({ client }).updateById(sourceGroupId, (sourceGroup) => {
// eslint-disable-next-line no-param-reassign
sourceGroup.import_target.new_name = newName;
});
......
......@@ -37,7 +37,7 @@ export class SourceGroupsManager {
}
setImportStatus(group, status) {
this.update(group, sourceGroup => {
this.update(group, (sourceGroup) => {
// eslint-disable-next-line no-param-reassign
sourceGroup.status = status;
});
......
......@@ -5,7 +5,7 @@ import bulkImportSourceGroupsQuery from '../queries/bulk_import_source_groups.qu
import { STATUSES } from '../../../constants';
import { SourceGroupsManager } from './source_groups_manager';
const groupId = i => `group${i}`;
const groupId = (i) => `group${i}`;
function generateGroupsQuery(groups) {
return gql`{
......@@ -46,14 +46,14 @@ export class StatusPoller {
const { bulkImportSourceGroups } = this.client.readQuery({
query: bulkImportSourceGroupsQuery,
});
const groupsInProgress = bulkImportSourceGroups.filter(g => g.status === STATUSES.STARTED);
const groupsInProgress = bulkImportSourceGroups.filter((g) => g.status === STATUSES.STARTED);
if (groupsInProgress.length) {
const { data: results } = await this.client.query({
query: generateGroupsQuery(groupsInProgress),
fetchPolicy: 'no-cache',
});
const completedGroups = groupsInProgress.filter((_, idx) => Boolean(results[groupId(idx)]));
completedGroups.forEach(group => {
completedGroups.forEach((group) => {
this.groupManager.setImportStatus(group, STATUSES.FINISHED);
});
}
......
......@@ -12,9 +12,9 @@ import { capitalizeFirstCharacter } from '~/lib/utils/text_utility';
let eTagPoll;
const hasRedirectInError = e => e?.response?.data?.error?.redirect;
const redirectToUrlInError = e => visitUrl(e.response.data.error.redirect);
const tooManyRequests = e => e.response.status === httpStatusCodes.TOO_MANY_REQUESTS;
const hasRedirectInError = (e) => e?.response?.data?.error?.redirect;
const redirectToUrlInError = (e) => visitUrl(e.response.data.error.redirect);
const tooManyRequests = (e) => e.response.status === httpStatusCodes.TOO_MANY_REQUESTS;
const pathWithParams = ({ path, ...params }) => {
const filteredParams = Object.fromEntries(
Object.entries(params).filter(([, value]) => value !== ''),
......@@ -47,7 +47,7 @@ const importAll = ({ state, dispatch }) => {
return Promise.all(
state.repositories
.filter(isProjectImportable)
.map(r => dispatch('fetchImport', r.importSource.id)),
.map((r) => dispatch('fetchImport', r.importSource.id)),
);
};
......@@ -69,7 +69,7 @@ const fetchReposFactory = ({ reposPath = isRequired() }) => ({ state, commit })
.then(({ data }) => {
commit(types.RECEIVE_REPOS_SUCCESS, convertObjectPropsToCamelCase(data, { deep: true }));
})
.catch(e => {
.catch((e) => {
commit(types.SET_PAGE, nextPage - 1);
if (hasRedirectInError(e)) {
......@@ -114,7 +114,7 @@ const fetchImportFactory = (importPath = isRequired()) => ({ state, commit, gett
repoId,
});
})
.catch(e => {
.catch((e) => {
const serverErrorMessage = e?.response?.data?.errors;
const flashMessage = serverErrorMessage
? sprintf(
......@@ -145,7 +145,7 @@ export const fetchJobsFactory = (jobsPath = isRequired()) => ({ state, commit, d
method: 'fetchJobs',
successCallback: ({ data }) =>
commit(types.RECEIVE_JOBS_SUCCESS, convertObjectPropsToCamelCase(data, { deep: true })),
errorCallback: e => {
errorCallback: (e) => {
if (hasRedirectInError(e)) {
redirectToUrlInError(e);
} else {
......
import { STATUSES } from '../../constants';
import { isProjectImportable, isIncompatible } from '../utils';
export const isLoading = state => state.isLoadingRepos || state.isLoadingNamespaces;
export const isLoading = (state) => state.isLoadingRepos || state.isLoadingNamespaces;
export const isImportingAnyRepo = state =>
state.repositories.some(repo =>
export const isImportingAnyRepo = (state) =>
state.repositories.some((repo) =>
[STATUSES.SCHEDULING, STATUSES.SCHEDULED, STATUSES.STARTED].includes(
repo.importedProject?.importStatus,
),
);
export const hasIncompatibleRepos = state => state.repositories.some(isIncompatible);
export const hasIncompatibleRepos = (state) => state.repositories.some(isIncompatible);
export const hasImportableRepos = state => state.repositories.some(isProjectImportable);
export const hasImportableRepos = (state) => state.repositories.some(isProjectImportable);
export const importAllCount = state => state.repositories.filter(isProjectImportable).length;
export const importAllCount = (state) => state.repositories.filter(isProjectImportable).length;
export const getImportTarget = state => repoId => {
export const getImportTarget = (state) => (repoId) => {
if (state.customImportTargets[repoId]) {
return state.customImportTargets[repoId];
}
const repo = state.repositories.find(r => r.importSource.id === repoId);
const repo = state.repositories.find((r) => r.importSource.id === repoId);
return {
newName: repo.importSource.sanitizedName,
......
......@@ -2,7 +2,7 @@ import Vue from 'vue';
import * as types from './mutation_types';
import { STATUSES } from '../../constants';
const makeNewImportedProject = importedProject => ({
const makeNewImportedProject = (importedProject) => ({
importSource: {
id: importedProject.id,
fullName: importedProject.importSource,
......@@ -12,15 +12,15 @@ const makeNewImportedProject = importedProject => ({
importedProject,
});
const makeNewIncompatibleProject = project => ({
const makeNewIncompatibleProject = (project) => ({
importSource: { ...project, incompatible: true },
importedProject: null,
});
const processLegacyEntries = ({ newRepositories, existingRepositories, factory }) => {
const newEntries = [];
newRepositories.forEach(project => {
const existingProject = existingRepositories.find(p => p.importSource.id === project.id);
newRepositories.forEach((project) => {
const existingProject = existingRepositories.find((p) => p.importSource.id === project.id);
const importedProjectShape = factory(project);
if (existingProject) {
......@@ -66,7 +66,7 @@ export default {
state.repositories = [
...newImportedProjects,
...state.repositories,
...repositories.providerRepos.map(project => ({
...repositories.providerRepos.map((project) => ({
importSource: project,
importedProject: null,
})),
......@@ -91,7 +91,7 @@ export default {
},
[types.REQUEST_IMPORT](state, { repoId, importTarget }) {
const existingRepo = state.repositories.find(r => r.importSource.id === repoId);
const existingRepo = state.repositories.find((r) => r.importSource.id === repoId);
existingRepo.importedProject = {
importStatus: STATUSES.SCHEDULING,
fullPath: `/${importTarget.targetNamespace}/${importTarget.newName}`,
......@@ -99,18 +99,18 @@ export default {
},
[types.RECEIVE_IMPORT_SUCCESS](state, { importedProject, repoId }) {
const existingRepo = state.repositories.find(r => r.importSource.id === repoId);
const existingRepo = state.repositories.find((r) => r.importSource.id === repoId);
existingRepo.importedProject = importedProject;
},
[types.RECEIVE_IMPORT_ERROR](state, repoId) {
const existingRepo = state.repositories.find(r => r.importSource.id === repoId);
const existingRepo = state.repositories.find((r) => r.importSource.id === repoId);
existingRepo.importedProject = null;
},
[types.RECEIVE_JOBS_SUCCESS](state, updatedProjects) {
updatedProjects.forEach(updatedProject => {
const repo = state.repositories.find(p => p.importedProject?.id === updatedProject.id);
updatedProjects.forEach((updatedProject) => {
const repo = state.repositories.find((p) => p.importedProject?.id === updatedProject.id);
if (repo?.importedProject) {
repo.importedProject.importStatus = updatedProject.importStatus;
}
......@@ -131,7 +131,7 @@ export default {
},
[types.SET_IMPORT_TARGET](state, { repoId, importTarget }) {
const existingRepo = state.repositories.find(r => r.importSource.id === repoId);
const existingRepo = state.repositories.find((r) => r.importSource.id === repoId);
if (
importTarget.targetNamespace === state.defaultTargetNamespace &&
......
......@@ -2,7 +2,7 @@ import $ from 'jquery';
import { stickyMonitor } from './lib/utils/sticky';
import initDeprecatedJQueryDropdown from '~/deprecated_jquery_dropdown';
export default stickyTop => {
export default (stickyTop) => {
stickyMonitor(document.querySelector('.js-diff-files-changed'), stickyTop);
initDeprecatedJQueryDropdown($('.js-diff-stats-dropdown'), {
......
......@@ -92,7 +92,7 @@ export default {
return isEmpty(this.value) && this.required;
},
options() {
return this.choices.map(choice => {
return this.choices.map((choice) => {
return {
value: choice[1],
text: choice[0],
......
......@@ -40,7 +40,7 @@ export default {
},
data() {
return {
selected: dropdownOptions.find(x => x.value === this.override),
selected: dropdownOptions.find((x) => x.value === this.override),
};
},
computed: {
......
export const isInheriting = state => (state.defaultState === null ? false : !state.override);
export const isInheriting = (state) => (state.defaultState === null ? false : !state.override);
export const isDisabled = state => state.isSaving || state.isTesting || state.isResetting;
export const isDisabled = (state) => state.isSaving || state.isTesting || state.isResetting;
export const propsSource = (state, getters) =>
getters.isInheriting ? state.defaultState : state.customState;
......
......@@ -23,7 +23,7 @@ export default class IntegrationSettingsForm {
document.querySelector('.js-vue-integration-settings'),
document.querySelector('.js-vue-default-integration-settings'),
);
eventHub.$on('toggle', active => {
eventHub.$on('toggle', (active) => {
this.formActive = active;
this.toggleServiceState();
});
......
......@@ -16,6 +16,6 @@ export default function initInviteMembersModal() {
return new Vue({
el,
provide: { membersPath },
render: createElement => createElement(InviteMemberModal),
render: (createElement) => createElement(InviteMemberModal),
});
}
......@@ -11,6 +11,6 @@ export default function initInviteMembersTrigger() {
return new Vue({
el,
provide: { ...el.dataset },
render: createElement => createElement(InviteMemberTrigger),
render: (createElement) => createElement(InviteMemberTrigger),
});
}
......@@ -93,7 +93,7 @@ export default {
},
selectedRoleName() {
return Object.keys(this.accessLevels).find(
key => this.accessLevels[key] === Number(this.selectedAccessLevel),
(key) => this.accessLevels[key] === Number(this.selectedAccessLevel),
);
},
},
......
......@@ -34,7 +34,7 @@ export default {
computed: {
newUsersToInvite() {
return this.selectedTokens
.map(obj => {
.map((obj) => {
return obj.id;
})
.join(',');
......@@ -55,8 +55,8 @@ export default {
},
retrieveUsers: debounce(function debouncedRetrieveUsers() {
return Api.users(this.query, this.$options.queryOptions)
.then(response => {
this.users = response.data.map(token => ({
.then((response) => {
this.users = response.data.map((token) => ({
id: token.id,
name: token.name,
username: token.username,
......
......@@ -13,7 +13,7 @@ export default function initInviteMembersModal() {
return new Vue({
el,
render: createElement =>
render: (createElement) =>
createElement(InviteMembersModal, {
props: {
...el.dataset,
......
......@@ -10,7 +10,7 @@ export default function initInviteMembersTrigger() {
return new Vue({
el,
render: createElement =>
render: (createElement) =>
createElement(InviteMembersTrigger, {
props: {
...el.dataset,
......
......@@ -101,7 +101,7 @@ export default {
// Collect unique label IDs for all checked issues
this.getElement('.selected-issuable:checked').each((i, el) => {
issuableLabels = this.getElement(`#${this.prefixId}${el.dataset.id}`).data('labels');
issuableLabels.forEach(labelId => {
issuableLabels.forEach((labelId) => {
// Store unique IDs
if (uniqueIds.indexOf(labelId) === -1) {
uniqueIds.push(labelId);
......@@ -113,7 +113,7 @@ export default {
// Add uniqueIds to add it as argument for _.intersection
labelIds.unshift(uniqueIds);
// Return IDs that are present but not in all selected issueables
return uniqueIds.filter(x => !intersection.apply(this, labelIds).includes(x));
return uniqueIds.filter((x) => !intersection.apply(this, labelIds).includes(x));
},
getElement(selector) {
......
......@@ -39,9 +39,9 @@ export default class IssuableBulkUpdateSidebar {
}
bindEvents() {
this.$bulkUpdateEnableBtn.on('click', e => this.toggleBulkEdit(e, true));
this.$bulkEditCancelBtn.on('click', e => this.toggleBulkEdit(e, false));
this.$checkAllContainer.on('click', e => this.selectAll(e));
this.$bulkUpdateEnableBtn.on('click', (e) => this.toggleBulkEdit(e, true));
this.$bulkEditCancelBtn.on('click', (e) => this.toggleBulkEdit(e, false));
this.$checkAllContainer.on('click', (e) => this.selectAll(e));
this.$issuesList.on('change', () => this.updateFormState());
this.$bulkEditSubmitBtn.on('click', () => this.prepForSubmit());
this.$checkAllContainer.on('click', () => this.updateFormState());
......@@ -159,7 +159,7 @@ export default class IssuableBulkUpdateSidebar {
const $checkedIssues = $('.selected-issuable:checked');
if ($checkedIssues.length > 0) {
return $.map($checkedIssues, value => $(value).data('id'));
return $.map($checkedIssues, (value) => $(value).data('id'));
}
return [];
......
......@@ -31,7 +31,7 @@ export default class IssuableContext {
});
$(document)
.off('click', '.issuable-sidebar .dropdown-content a')
.on('click', '.issuable-sidebar .dropdown-content a', e => e.preventDefault());
.on('click', '.issuable-sidebar .dropdown-content a', (e) => e.preventDefault());
$(document)
.off('click', '.edit-link')
......
......@@ -89,9 +89,9 @@ export default class IssuableForm {
theme: 'gitlab-theme animate-picker',
format: 'yyyy-mm-dd',
container: $issuableDueDate.parent().get(0),
parse: dateString => parsePikadayDate(dateString),
toString: date => pikadayToString(date),
onSelect: dateText => $issuableDueDate.val(calendar.toString(dateText)),
parse: (dateString) => parsePikadayDate(dateString),
toString: (date) => pikadayToString(date),
onSelect: (dateText) => $issuableDueDate.val(calendar.toString(dateText)),
firstDay: gon.first_day_of_week,
});
calendar.setDate(parsePikadayDate($issuableDueDate.val()));
......@@ -202,7 +202,7 @@ export default class IssuableForm {
results(data) {
return {
// `data` keys are translated so we can't just access them with a string based key
results: data[Object.keys(data)[0]].map(name => ({
results: data[Object.keys(data)[0]].map((name) => ({
id: name,
text: name,
})),
......
......@@ -13,7 +13,7 @@ export default class IssuableIndex {
static resetIncomingEmailToken() {
const $resetToken = $('.incoming-email-token-reset');
$resetToken.on('click', e => {
$resetToken.on('click', (e) => {
e.preventDefault();
$resetToken.text(s__('EmailToken|resetting...'));
......
......@@ -200,7 +200,7 @@ export default {
this.checkedIssuables[this.issuableId(issuable)].checked = value;
},
handleAllIssuablesCheckedInput(value) {
Object.keys(this.checkedIssuables).forEach(issuableId => {
Object.keys(this.checkedIssuables).forEach((issuableId) => {
this.checkedIssuables[issuableId].checked = value;
});
},
......
......@@ -29,7 +29,7 @@ export default {
skip() {
return this.isSearchEmpty;
},
update: data => data.project.issues.edges.map(({ node }) => node),
update: (data) => data.project.issues.edges.map(({ node }) => node),
variables() {
return {
fullPath: this.projectPath,
......
......@@ -23,7 +23,7 @@ export default class Issue {
}
// Listen to state changes in the Vue app
document.addEventListener('issuable_vue_app:change', event => {
document.addEventListener('issuable_vue_app:change', (event) => {
this.updateTopState(event.detail.isClosed, event.detail.data);
});
}
......@@ -80,7 +80,7 @@ export default class Issue {
alertMovedFromServiceDeskWarning.show();
}
alertMovedFromServiceDeskWarning.on('click', '.js-close', e => {
alertMovedFromServiceDeskWarning.on('click', '.js-close', (e) => {
e.preventDefault();
e.stopImmediatePropagation();
alertMovedFromServiceDeskWarning.remove();
......
......@@ -250,7 +250,7 @@ export default {
this.poll = new Poll({
resource: this.service,
method: 'getData',
successCallback: res => this.store.updateState(res.data),
successCallback: (res) => this.store.updateState(res.data),
errorCallback(err) {
throw new Error(err);
},
......@@ -294,8 +294,8 @@ export default {
updateStoreState() {
return this.service
.getData()
.then(res => res.data)
.then(data => {
.then((res) => res.data)
.then((data) => {
this.store.updateState(data);
})
.catch(() => {
......@@ -320,7 +320,7 @@ export default {
requestTemplatesAndShowForm() {
return this.service
.loadTemplates(this.issuableTemplateNamesPath)
.then(res => {
.then((res) => {
this.updateAndShowForm(res.data);
})
.catch(() => {
......@@ -345,9 +345,9 @@ export default {
updateIssuable() {
return this.service
.updateIssuable(this.store.formState)
.then(res => res.data)
.then(data => this.checkForSpam(data))
.then(data => {
.then((res) => res.data)
.then((data) => this.checkForSpam(data))
.then((data) => {
if (!window.location.pathname.includes(data.web_url)) {
visitUrl(data.web_url);
}
......@@ -384,8 +384,8 @@ export default {
deleteIssuable(payload) {
return this.service
.deleteIssuable(payload)
.then(res => res.data)
.then(data => {
.then((res) => res.data)
.then((data) => {
// Stop the poll so we don't get 404's with the issuable not existing
this.poll.stop();
......
......@@ -34,7 +34,7 @@ export default {
mounted() {
// Create the editor for the template
const editor = document.querySelector('.detail-page-description .note-textarea') || {};
editor.setValue = val => {
editor.setValue = (val) => {
this.formState.description = val;
};
editor.getValue = () => this.formState.description;
......
......@@ -57,6 +57,6 @@ export function initIssueHeaderActions(store) {
reportAbusePath: el.dataset.reportAbusePath,
submitAsSpamPath: el.dataset.submitAsSpamPath,
},
render: createElement => createElement(HeaderActions),
render: (createElement) => createElement(HeaderActions),
});
}
......@@ -4,7 +4,7 @@ import { sanitize } from '~/lib/dompurify';
// We currently load + parse the data from the issue app and related merge request
let cachedParsedData;
export const parseIssuableData = el => {
export const parseIssuableData = (el) => {
try {
if (cachedParsedData) return cachedParsedData;
......
......@@ -110,7 +110,7 @@ export default {
return getDayDifference(new Date(this.issuable.created_at), new Date()) < 1;
},
labelIdsString() {
return JSON.stringify(this.issuable.labels.map(l => l.id));
return JSON.stringify(this.issuable.labels.map((l) => l.id));
},
milestoneDueDate() {
const { due_date: dueDate } = this.issuable.milestone || {};
......
......@@ -208,7 +208,7 @@ export default {
},
mounted() {
if (this.canBulkEdit) {
this.unsubscribeToggleBulkEdit = issueableEventHub.$on('issuables:toggleBulkEdit', val => {
this.unsubscribeToggleBulkEdit = issueableEventHub.$on('issuables:toggleBulkEdit', (val) => {
this.isBulkEditing = val;
});
}
......@@ -223,7 +223,7 @@ export default {
return Boolean(this.selection[issuableId]);
},
setSelection(ids) {
ids.forEach(id => {
ids.forEach((id) => {
this.select(id, true);
});
},
......@@ -254,7 +254,7 @@ export default {
per_page: this.itemsPerPage,
},
})
.then(response => {
.then((response) => {
this.loading = false;
this.issuables = response.data;
this.totalItems = Number(response.headers['x-total']);
......@@ -335,7 +335,7 @@ export default {
handleFilter(filters) {
let search = null;
filters.forEach(filter => {
filters.forEach((filter) => {
if (typeof filter === 'string') {
search = filter;
}
......
......@@ -40,7 +40,7 @@ function mountIssuablesListApp() {
return;
}
document.querySelectorAll('.js-issuables-list').forEach(el => {
document.querySelectorAll('.js-issuables-list').forEach((el) => {
const { canBulkEdit, emptyStateMeta = {}, scopedLabelsAvailable, ...data } = el.dataset;
return new Vue({
......
......@@ -27,7 +27,7 @@ const initJiraFormHandlers = () => {
alert(error);
};
AP.getLocation(location => {
AP.getLocation((location) => {
$('.js-jira-connect-sign-in').each(function updateSignInLink() {
const updatedLink = `${$(this).attr('href')}?return_to=${location}`;
$(this).attr('href', updatedLink);
......@@ -38,7 +38,7 @@ const initJiraFormHandlers = () => {
const actionUrl = $(this).attr('action');
e.preventDefault();
AP.context.getToken(token => {
AP.context.getToken((token) => {
// eslint-disable-next-line no-jquery/no-ajax
$.post(actionUrl, {
jwt: token,
......@@ -46,7 +46,7 @@ const initJiraFormHandlers = () => {
format: 'json',
})
.done(reqComplete)
.fail(err => reqFailed(err, 'Failed to add namespace. Please try again.'));
.fail((err) => reqFailed(err, 'Failed to add namespace. Please try again.'));
});
});
......@@ -54,7 +54,7 @@ const initJiraFormHandlers = () => {
const href = $(this).attr('href');
e.preventDefault();
AP.context.getToken(token => {
AP.context.getToken((token) => {
// eslint-disable-next-line no-jquery/no-ajax
$.ajax({
url: href,
......@@ -65,7 +65,7 @@ const initJiraFormHandlers = () => {
},
})
.done(reqComplete)
.fail(err => reqFailed(err, 'Failed to remove namespace. Please try again.'));
.fail((err) => reqFailed(err, 'Failed to remove namespace. Please try again.'));
});
});
};
......
......@@ -118,7 +118,7 @@ export default {
this.getJiraUserMapping();
this.searchUsers()
.then(data => {
.then((data) => {
this.initialUsers = data;
})
.catch(() => {});
......@@ -219,7 +219,7 @@ export default {
}
},
updateMapping(jiraAccountId, gitlabId, gitlabUsername) {
this.userMappings = this.userMappings.map(userMapping =>
this.userMappings = this.userMappings.map((userMapping) =>
userMapping.jiraAccountId === jiraAccountId
? {
...userMapping,
......
......@@ -20,7 +20,7 @@ export const addInProgressImportToStore = (store, jiraImportStart, fullPath) =>
store.writeQuery({
...queryDetails,
data: produce(sourceData, draftData => {
data: produce(sourceData, (draftData) => {
draftData.project.jiraImportStatus = IMPORT_STATE.SCHEDULED; // eslint-disable-line no-param-reassign
// eslint-disable-next-line no-param-reassign
draftData.project.jiraImports.nodes = [
......
......@@ -9,10 +9,10 @@ export const IMPORT_STATE = {
STARTED: 'started',
};
export const isInProgress = state =>
export const isInProgress = (state) =>
state === IMPORT_STATE.SCHEDULED || state === IMPORT_STATE.STARTED;
export const isFinished = state => state === IMPORT_STATE.FINISHED;
export const isFinished = (state) => state === IMPORT_STATE.FINISHED;
/**
* Converts the list of Jira projects into a format consumable by GlFormSelect.
......@@ -22,7 +22,7 @@ export const isFinished = state => state === IMPORT_STATE.FINISHED;
* @param {string} projects[].name - Jira project name
* @returns {Object[]} - List of Jira projects in a format consumable by GlFormSelect
*/
export const extractJiraProjectsOptions = projects =>
export const extractJiraProjectsOptions = (projects) =>
projects.map(({ key, name }) => ({ text: `${name} (${key})`, value: key }));
/**
......@@ -32,10 +32,10 @@ export const extractJiraProjectsOptions = projects =>
* @param {string} jiraImports[].jiraProjectKey - Jira project key
* @returns {string} - A label title
*/
const calculateJiraImportLabelTitle = jiraImports => {
const calculateJiraImportLabelTitle = (jiraImports) => {
const mostRecentJiraProjectKey = last(jiraImports)?.jiraProjectKey;
const jiraProjectImportCount = jiraImports.filter(
jiraImport => jiraImport.jiraProjectKey === mostRecentJiraProjectKey,
(jiraImport) => jiraImport.jiraProjectKey === mostRecentJiraProjectKey,
).length;
return `jira-import::${mostRecentJiraProjectKey}-${jiraProjectImportCount}`;
};
......@@ -50,7 +50,7 @@ const calculateJiraImportLabelTitle = jiraImports => {
* @returns {string} - The label color associated with the given labelTitle
*/
const calculateJiraImportLabelColor = (labelTitle, labels) =>
labels.find(label => label.title === labelTitle)?.color;
labels.find((label) => label.title === labelTitle)?.color;
/**
* Calculates the label for the most recent Jira import.
......@@ -91,7 +91,7 @@ export const shouldShowFinishedAlert = (labelTitle, importStatus) => {
*
* @param {string} labelTitle - Jira import label, for checking localStorage
*/
export const setFinishedAlertHideMap = labelTitle => {
export const setFinishedAlertHideMap = (labelTitle) => {
const finishedAlertHideMap =
JSON.parse(localStorage.getItem(JIRA_IMPORT_SUCCESS_ALERT_HIDE_MAP_KEY)) || {};
......
......@@ -134,7 +134,7 @@ export default {
if (isEmpty(oldVal) && !isEmpty(newVal.pipeline)) {
const stages = this.job.pipeline.details.stages || [];
const defaultStage = stages.find(stage => stage && stage.name === this.selectedStage);
const defaultStage = stages.find((stage) => stage && stage.name === this.selectedStage);
if (defaultStage) {
this.fetchJobsForStage(defaultStage);
......
......@@ -18,7 +18,7 @@ export default {
render(h, { props }) {
const { line, path } = props;
const chars = line.content.map(content => {
const chars = line.content.map((content) => {
return h(
'span',
{
......@@ -26,7 +26,7 @@ export default {
},
// Simple "tokenization": Split text in chunks of text
// which alternate between text and urls.
content.text.split(linkRegex).map(chunk => {
content.text.split(linkRegex).map((chunk) => {
// Return normal string for non-links
if (!chunk.match(linkRegex)) {
return chunk;
......
......@@ -94,7 +94,7 @@ export default {
},
deleteVariable(id) {
this.variables.splice(
this.variables.findIndex(el => el.id === id),
this.variables.findIndex((el) => el.id === id),
1,
);
},
......
......@@ -27,7 +27,7 @@ export default {
return this.showVariableValues ? __('Hide values') : __('Reveal values');
},
hasValues() {
return this.trigger.variables.some(v => v.value);
return this.trigger.variables.some((v) => v.value);
},
},
methods: {
......
......@@ -188,7 +188,7 @@ export const fetchTrace = ({ dispatch, state }) =>
dispatch('startPollingTrace');
}
})
.catch(e =>
.catch((e) =>
e.response.status === httpStatusCodes.FORBIDDEN
? dispatch('receiveTraceUnauthorizedError')
: dispatch('receiveTraceError'),
......@@ -244,7 +244,7 @@ export const fetchJobsForStage = ({ dispatch }, stage = {}) => {
},
})
.then(({ data }) => {
const retriedJobs = data.retried.map(job => ({ ...job, retried: true }));
const retriedJobs = data.retried.map((job) => ({ ...job, retried: true }));
const jobs = data.latest_statuses.concat(retriedJobs);
dispatch('receiveJobsForStageSuccess', jobs);
......@@ -259,7 +259,7 @@ export const receiveJobsForStageError = ({ commit }) => {
};
export const triggerManualJob = ({ state, dispatch }, variables) => {
const parsedVariables = variables.map(variable => {
const parsedVariables = variables.map((variable) => {
const copyVar = { ...variable };
delete copyVar.id;
return copyVar;
......
import { isEmpty, isString } from 'lodash';
import { isScrolledToBottom } from '~/lib/utils/scroll_utils';
export const headerTime = state => (state.job.started ? state.job.started : state.job.created_at);
export const headerTime = (state) => (state.job.started ? state.job.started : state.job.created_at);
export const hasForwardDeploymentFailure = state =>
export const hasForwardDeploymentFailure = (state) =>
state?.job?.failure_reason === 'forward_deployment_failure';
export const hasUnmetPrerequisitesFailure = state =>
export const hasUnmetPrerequisitesFailure = (state) =>
state?.job?.failure_reason === 'unmet_prerequisites';
export const shouldRenderCalloutMessage = state =>
export const shouldRenderCalloutMessage = (state) =>
!isEmpty(state.job.status) && !isEmpty(state.job.callout_message);
/**
* When job has not started the key will be null
* When job started the key will be a string with a date.
*/
export const shouldRenderTriggeredLabel = state => isString(state.job.started);
export const shouldRenderTriggeredLabel = (state) => isString(state.job.started);
export const hasEnvironment = state => !isEmpty(state.job.deployment_status);
export const hasEnvironment = (state) => !isEmpty(state.job.deployment_status);
/**
* Checks if it the job has trace.
* Used to check if it should render the job log or the empty state
* @returns {Boolean}
*/
export const hasTrace = state =>
export const hasTrace = (state) =>
state.job.has_trace || (!isEmpty(state.job.status) && state.job.status.group === 'running');
export const emptyStateIllustration = state =>
export const emptyStateIllustration = (state) =>
(state.job && state.job.status && state.job.status.illustration) || {};
export const emptyStateAction = state =>
export const emptyStateAction = (state) =>
(state.job && state.job.status && state.job.status.action) || null;
/**
......@@ -40,12 +40,12 @@ export const emptyStateAction = state =>
*
* @returns {Boolean}
*/
export const shouldRenderSharedRunnerLimitWarning = state =>
export const shouldRenderSharedRunnerLimitWarning = (state) =>
!isEmpty(state.job.runners) &&
!isEmpty(state.job.runners.quota) &&
state.job.runners.quota.used >= state.job.runners.quota.limit;
export const isScrollingDown = state => isScrolledToBottom() && !state.isTraceComplete;
export const isScrollingDown = (state) => isScrolledToBottom() && !state.isTraceComplete;
export const hasRunnersForProject = state =>
export const hasRunnersForProject = (state) =>
state.job.runners.available && !state.job.runners.online;
......@@ -43,7 +43,7 @@ export const parseHeaderLine = (line = {}, lineNumber) => ({
* @param Object durationLine
*/
export function addDurationToHeader(data, durationLine) {
data.forEach(el => {
data.forEach((el) => {
if (el.line && el.line.section === durationLine.section) {
el.line.section_duration = durationLine.section_duration;
}
......@@ -72,7 +72,7 @@ export const isCollapsibleSection = (acc = [], last = {}, section = {}) =>
* @param Array acc
* @returns Number
*/
export const getIncrementalLineNumber = acc => {
export const getIncrementalLineNumber = (acc) => {
let lineNumberValue;
const lastIndex = acc.length - 1;
const lastElement = acc[lastIndex];
......
......@@ -124,15 +124,15 @@ export default class LabelsSelect {
const toRemoveIds = Array.from(
$form.find(`input[type="hidden"][name="${fieldName}"]`),
)
.map(el => el.value)
.map((el) => el.value)
.map(Number);
data.labels.forEach(label => {
data.labels.forEach((label) => {
const index = toRemoveIds.indexOf(label.id);
toRemoveIds.splice(index, 1);
});
toRemoveIds.forEach(id => {
toRemoveIds.forEach((id) => {
$form
.find(`input[type="hidden"][name="${fieldName}"][value="${id}"]`)
.last()
......@@ -157,7 +157,7 @@ export default class LabelsSelect {
const labelUrl = $dropdown.attr('data-labels');
axios
.get(labelUrl)
.then(res => {
.then((res) => {
let { data } = res;
if ($dropdown.hasClass('js-extra-options')) {
const extraData = [];
......@@ -390,7 +390,7 @@ export default class LabelsSelect {
);
} else {
let { labels } = boardsStore.detail.issue;
labels = labels.filter(selectedLabel => selectedLabel.id !== label.id);
labels = labels.filter((selectedLabel) => selectedLabel.id !== label.id);
boardsStore.detail.issue.labels = labels;
}
......@@ -401,12 +401,12 @@ export default class LabelsSelect {
.update($dropdown.attr('data-issue-update'))
.then(() => {
if (isScopedLabel(label)) {
const prevIds = oldLabels.map(label => label.id);
const newIds = boardsStore.detail.issue.labels.map(label => label.id);
const differentIds = prevIds.filter(x => !newIds.includes(x));
const prevIds = oldLabels.map((label) => label.id);
const newIds = boardsStore.detail.issue.labels.map((label) => label.id);
const differentIds = prevIds.filter((x) => !newIds.includes(x));
$dropdown.data('marked', newIds);
$dropdownMenu
.find(differentIds.map(id => `[data-label-id="${id}"]`).join(','))
.find(differentIds.map((id) => `[data-label-id="${id}"]`).join(','))
.removeClass('is-active');
}
})
......
......@@ -28,10 +28,10 @@ export default class LazyLoader {
const lazyImages = [].slice.call(document.querySelectorAll('.lazy'));
if (LazyLoader.supportsNativeLazyLoading()) {
lazyImages.forEach(img => LazyLoader.loadImage(img));
lazyImages.forEach((img) => LazyLoader.loadImage(img));
} else if (LazyLoader.supportsIntersectionObserver()) {
if (this.intersectionObserver) {
lazyImages.forEach(img => this.intersectionObserver.observe(img));
lazyImages.forEach((img) => this.intersectionObserver.observe(img));
}
} else if (lazyImages.length) {
this.lazyImages = lazyImages;
......@@ -98,8 +98,8 @@ export default class LazyLoader {
});
};
onIntersection = entries => {
entries.forEach(entry => {
onIntersection = (entries) => {
entries.forEach((entry) => {
// We are using `intersectionRatio > 0` over `isIntersecting`, as some browsers did not ship the latter
// See: https://gitlab.com/gitlab-org/gitlab-foss/issues/54407
if (entry.intersectionRatio > 0) {
......@@ -126,7 +126,7 @@ export default class LazyLoader {
const visHeight = scrollTop + window.innerHeight + SCROLL_THRESHOLD;
// Loading Images which are in the current viewport or close to them
this.lazyImages = this.lazyImages.filter(selectedImage => {
this.lazyImages = this.lazyImages.filter((selectedImage) => {
if (selectedImage.getAttribute('data-src')) {
const imgBoundRect = selectedImage.getBoundingClientRect();
const imgTop = scrollTop + imgBoundRect.top;
......
......@@ -30,7 +30,7 @@ document.addEventListener('DOMContentLoaded', async () => {
const fixSVGs = () => {
requestIdleCallback(() => {
document.querySelectorAll(`use:not([${SKIP_ATTRIBUTE}])`).forEach(use => {
document.querySelectorAll(`use:not([${SKIP_ATTRIBUTE}])`).forEach((use) => {
const href = use?.getAttribute('href') ?? use?.getAttribute('xlink:href') ?? '';
if (href.includes(window.gon.sprite_icons)) {
......@@ -60,7 +60,7 @@ document.addEventListener('DOMContentLoaded', async () => {
div.classList.add('hidden');
const result = await fetch(url);
div.innerHTML = await result.text();
div.querySelectorAll('[id]').forEach(node => {
div.querySelectorAll('[id]').forEach((node) => {
node.setAttribute('id', `${prefix}-${node.getAttribute('id')}`);
});
document.body.append(div);
......
......@@ -11,9 +11,9 @@ const defaultConfig = {
const getAllowedIconUrls = (gon = window.gon) =>
[gon.sprite_file_icons, gon.sprite_icons].filter(Boolean);
const isUrlAllowed = url => getAllowedIconUrls().some(allowedUrl => url.startsWith(allowedUrl));
const isUrlAllowed = (url) => getAllowedIconUrls().some((allowedUrl) => url.startsWith(allowedUrl));
const isHrefSafe = url =>
const isHrefSafe = (url) =>
isUrlAllowed(url) || isUrlAllowed(relativePathToAbsolute(url, getBaseURL()));
const removeUnsafeHref = (node, attr) => {
......@@ -36,7 +36,7 @@ const removeUnsafeHref = (node, attr) => {
*
* @param {Object} node - Node to sanitize
*/
const sanitizeSvgIcon = node => {
const sanitizeSvgIcon = (node) => {
removeUnsafeHref(node, 'href');
// Note: `xlink:href` is deprecated, but still in use
......@@ -44,7 +44,7 @@ const sanitizeSvgIcon = node => {
removeUnsafeHref(node, 'xlink:href');
};
addHook('afterSanitizeAttributes', node => {
addHook('afterSanitizeAttributes', (node) => {
if (node.tagName.toLowerCase() === 'use') {
sanitizeSvgIcon(node);
}
......
......@@ -36,13 +36,13 @@ export default (resolvers = {}, config = {}) => {
};
const uploadsLink = ApolloLink.split(
operation => operation.getContext().hasUpload || operation.getContext().isSingleRequest,
(operation) => operation.getContext().hasUpload || operation.getContext().isSingleRequest,
createUploadLink(httpOptions),
new BatchHttpLink(httpOptions),
);
const performanceBarLink = new ApolloLink((operation, forward) => {
return forward(operation).map(response => {
return forward(operation).map((response) => {
const httpResponse = operation.getContext().response;
if (PerformanceBarService.interceptor) {
......
......@@ -25,7 +25,7 @@ class AjaxCache extends Cache {
this.internalStorage[endpoint] = data;
delete this.pendingRequests[endpoint];
})
.catch(e => {
.catch((e) => {
const error = new Error(`${endpoint}: ${e.message}`);
error.textStatus = e.message;
......
......@@ -7,7 +7,7 @@ import { isEqual, pickBy } from 'lodash';
* @param obj
* @returns {Dictionary<unknown>}
*/
const pickDefinedValues = obj => pickBy(obj, x => x !== undefined);
const pickDefinedValues = (obj) => pickBy(obj, (x) => x !== undefined);
/**
* Compares two set of variables, order independent
......@@ -28,9 +28,9 @@ export class StartupJSLink extends ApolloLink {
// Extract operationNames from the queries and ensure that we can
// match operationName => element from result array
parseStartupCalls(calls) {
calls.forEach(call => {
calls.forEach((call) => {
const { query, variables, fetchCall } = call;
const operationName = parse(query)?.definitions?.find(x => x.kind === 'OperationDefinition')
const operationName = parse(query)?.definitions?.find((x) => x.kind === 'OperationDefinition')
?.name?.value;
if (operationName) {
......@@ -71,9 +71,9 @@ export class StartupJSLink extends ApolloLink {
return forward(operation);
}
return new Observable(observer => {
return new Observable((observer) => {
fetchCall
.then(response => {
.then((response) => {
// Handle HTTP errors
if (!response.ok) {
throw new Error('fetchCall failed');
......@@ -81,7 +81,7 @@ export class StartupJSLink extends ApolloLink {
operation.setContext({ response });
return response.json();
})
.then(result => {
.then((result) => {
if (result && (result.errors || !result.data)) {
throw new Error('Received GraphQL error');
}
......@@ -92,10 +92,10 @@ export class StartupJSLink extends ApolloLink {
})
.catch(() => {
forward(operation).subscribe({
next: result => {
next: (result) => {
observer.next(result);
},
error: error => {
error: (error) => {
observer.error(error);
},
complete: observer.complete.bind(observer),
......
import { capitalizeFirstCharacter } from '~/lib/utils/text_utility';
export const clearDraft = autosaveKey => {
export const clearDraft = (autosaveKey) => {
try {
window.localStorage.removeItem(`autosave/${autosaveKey}`);
} catch (e) {
......@@ -9,7 +9,7 @@ export const clearDraft = autosaveKey => {
}
};
export const getDraft = autosaveKey => {
export const getDraft = (autosaveKey) => {
try {
return window.localStorage.getItem(`autosave/${autosaveKey}`);
} catch (e) {
......
......@@ -3,9 +3,9 @@ import { mergeUrlParams } from './url_utility';
// We should probably not couple this utility to `gon.gitlab_url`
// Also, this would replace occurrences that aren't at the beginning of the string
const removeGitLabUrl = url => url.replace(gon.gitlab_url, '');
const removeGitLabUrl = (url) => url.replace(gon.gitlab_url, '');
const getFullUrl = req => {
const getFullUrl = (req) => {
const url = removeGitLabUrl(req.url);
return mergeUrlParams(req.params || {}, url, { sort: true });
};
......@@ -36,7 +36,7 @@ const handleStartupCall = async ({ fetchCall }, req) => {
});
};
const setupAxiosStartupCalls = axios => {
const setupAxiosStartupCalls = (axios) => {
const { startup_calls: startupCalls } = window.gl || {};
if (!startupCalls || isEmpty(startupCalls)) {
......@@ -45,7 +45,7 @@ const setupAxiosStartupCalls = axios => {
const remainingCalls = new Map(Object.entries(startupCalls));
const interceptor = axios.interceptors.request.use(async req => {
const interceptor = axios.interceptors.request.use(async (req) => {
const fullUrl = getFullUrl(req);
const startupCall = remainingCalls.get(fullUrl);
......
......@@ -9,7 +9,7 @@ axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// Maintain a global counter for active requests
// see: spec/support/wait_for_requests.rb
axios.interceptors.request.use(config => {
axios.interceptors.request.use((config) => {
window.pendingRequests = window.pendingRequests || 0;
window.pendingRequests += 1;
return config;
......@@ -19,11 +19,11 @@ setupAxiosStartupCalls(axios);
// Remove the global counter
axios.interceptors.response.use(
response => {
(response) => {
window.pendingRequests -= 1;
return response;
},
err => {
(err) => {
window.pendingRequests -= 1;
return Promise.reject(err);
},
......@@ -37,8 +37,8 @@ window.addEventListener('beforeunload', () => {
// Ignore AJAX errors caused by requests
// being cancelled due to browser navigation
axios.interceptors.response.use(
response => response,
err => suppressAjaxErrorsDuringNavigation(err, isUserNavigating),
(response) => response,
(err) => suppressAjaxErrorsDuringNavigation(err, isUserNavigating),
);
export default axios;
......
......@@ -68,7 +68,7 @@ export default class LinkedTabs {
// since this is a custom event we need jQuery :(
$(document)
.off('shown.bs.tab', tabSelector)
.on('shown.bs.tab', tabSelector, e => this.tabShown(e));
.on('shown.bs.tab', tabSelector, (e) => this.tabShown(e));
this.activateTab(this.action);
}
......
......@@ -34,7 +34,7 @@ const commonChartOptions = () => ({
legend: false,
});
export const barChartOptions = shouldAdjustFontSize => ({
export const barChartOptions = (shouldAdjustFontSize) => ({
...commonChartOptions(),
scales: {
...yAxesConfig(shouldAdjustFontSize),
......@@ -89,7 +89,7 @@ export const lineChartOptions = ({ width, numberOfPoints, shouldAdjustFontSize }
* @param {Array} data
* @returns {[*, *]}
*/
export const firstAndLastY = data => {
export const firstAndLastY = (data) => {
const [firstEntry] = data;
const [lastEntry] = data.slice(-1);
......
......@@ -4,7 +4,7 @@
* @param hex string
* @returns array|null
*/
export const hexToRgb = hex => {
export const hexToRgb = (hex) => {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
const fullHex = hex.replace(shorthandRegex, (_m, r, g, b) => r + r + g + g + b + b);
......@@ -15,7 +15,7 @@ export const hexToRgb = hex => {
: null;
};
export const textColorForBackground = backgroundColor => {
export const textColorForBackground = (backgroundColor) => {
const [r, g, b] = hexToRgb(backgroundColor);
if (r + g + b > 500) {
......
......@@ -54,7 +54,7 @@ export const getCspNonceValue = () => {
return metaTag && metaTag.content;
};
export const rstrip = val => {
export const rstrip = (val) => {
if (val) {
return val.replace(/\s+$/, '');
}
......@@ -149,13 +149,13 @@ export const isInViewport = (el, offset = {}) => {
);
};
export const parseUrl = url => {
export const parseUrl = (url) => {
const parser = document.createElement('a');
parser.href = url;
return parser;
};
export const parseUrlPathname = url => {
export const parseUrlPathname = (url) => {
const parsedUrl = parseUrl(url);
// parsedUrl.pathname will return an absolute path for Firefox and a relative path for IE11
// We have to make sure we always have an absolute path.
......@@ -166,8 +166,8 @@ const splitPath = (path = '') => path.replace(/^\?/, '').split('&');
export const urlParamsToArray = (path = '') =>
splitPath(path)
.filter(param => param.length > 0)
.map(param => {
.filter((param) => param.length > 0)
.map((param) => {
const split = param.split('=');
return [decodeURI(split[0]), split[1]].join('=');
});
......@@ -209,13 +209,13 @@ export const urlParamsToObject = (path = '') =>
return data;
}, {});
export const isMetaKey = e => e.metaKey || e.ctrlKey || e.altKey || e.shiftKey;
export const isMetaKey = (e) => e.metaKey || e.ctrlKey || e.altKey || e.shiftKey;
// Identify following special clicks
// 1) Cmd + Click on Mac (e.metaKey)
// 2) Ctrl + Click on PC (e.ctrlKey)
// 3) Middle-click or Mouse Wheel Click (e.which is 2)
export const isMetaClick = e => e.metaKey || e.ctrlKey || e.which === 2;
export const isMetaClick = (e) => e.metaKey || e.ctrlKey || e.which === 2;
export const contentTop = () => {
const isDesktop = breakpointInstance.isDesktop();
......@@ -277,7 +277,7 @@ export const scrollToElement = (element, options = {}) => {
);
};
export const scrollToElementWithContext = element => {
export const scrollToElementWithContext = (element) => {
const offsetMultiplier = -0.1;
return scrollToElement(element, { offset: window.innerHeight * offsetMultiplier });
};
......@@ -287,7 +287,7 @@ export const scrollToElementWithContext = element => {
* each browser screen repaint.
* @param {Function} fn
*/
export const debounceByAnimationFrame = fn => {
export const debounceByAnimationFrame = (fn) => {
let requestId;
return function debounced(...args) {
......@@ -334,7 +334,7 @@ const handleSelectedRange = (range, restrictToNode) => {
return range.cloneContents();
};
export const getSelectedFragment = restrictToNode => {
export const getSelectedFragment = (restrictToNode) => {
const selection = window.getSelection();
if (selection.rangeCount === 0) return null;
// Most usages of the selection only want text from a part of the page (e.g. discussion)
......@@ -390,10 +390,10 @@ export const insertText = (target, text) => {
this will take in the headers from an API response and normalize them
this way we don't run into production issues when nginx gives us lowercased header keys
*/
export const normalizeHeaders = headers => {
export const normalizeHeaders = (headers) => {
const upperCaseHeaders = {};
Object.keys(headers || {}).forEach(e => {
Object.keys(headers || {}).forEach((e) => {
upperCaseHeaders[e.toUpperCase()] = headers[e];
});
......@@ -406,7 +406,7 @@ export const normalizeHeaders = headers => {
* @param {Object} paginationInformation
* @returns {Object}
*/
export const parseIntPagination = paginationInformation => ({
export const parseIntPagination = (paginationInformation) => ({
perPage: parseInt(paginationInformation['X-PER-PAGE'], 10),
page: parseInt(paginationInformation['X-PAGE'], 10),
total: parseInt(paginationInformation['X-TOTAL'], 10),
......@@ -445,10 +445,10 @@ export const parseQueryStringIntoObject = (query = '') => {
*/
export const objectToQueryString = (params = {}) =>
Object.keys(params)
.map(param => `${param}=${params[param]}`)
.map((param) => `${param}=${params[param]}`)
.join('&');
export const buildUrlWithCurrentLocation = param => {
export const buildUrlWithCurrentLocation = (param) => {
if (param) return `${window.location.pathname}${param}`;
return window.location.pathname;
......@@ -460,7 +460,7 @@ export const buildUrlWithCurrentLocation = param => {
*
* @param {String} param
*/
export const historyPushState = newUrl => {
export const historyPushState = (newUrl) => {
window.history.pushState({}, document.title, newUrl);
};
......@@ -470,7 +470,7 @@ export const historyPushState = newUrl => {
*
* @param {String} param
*/
export const historyReplaceState = newUrl => {
export const historyReplaceState = (newUrl) => {
window.history.replaceState({}, document.title, newUrl);
};
......@@ -482,7 +482,7 @@ export const historyReplaceState = newUrl => {
* @param {String} value
* @returns {Boolean}
*/
export const parseBoolean = value => (value && value.toString()) === 'true';
export const parseBoolean = (value) => (value && value.toString()) === 'true';
export const BACKOFF_TIMEOUT = 'BACKOFF_TIMEOUT';
......@@ -529,7 +529,7 @@ export const backOff = (fn, timeout = 60000) => {
let timeElapsed = 0;
return new Promise((resolve, reject) => {
const stop = arg => (arg instanceof Error ? reject(arg) : resolve(arg));
const stop = (arg) => (arg instanceof Error ? reject(arg) : resolve(arg));
const next = () => {
if (timeElapsed < timeout) {
......@@ -548,7 +548,7 @@ export const backOff = (fn, timeout = 60000) => {
export const createOverlayIcon = (iconPath, overlayPath) => {
const faviconImage = document.createElement('img');
return new Promise(resolve => {
return new Promise((resolve) => {
faviconImage.onload = () => {
const size = 32;
......@@ -594,7 +594,7 @@ export const createOverlayIcon = (iconPath, overlayPath) => {
});
};
export const setFaviconOverlay = overlayPath => {
export const setFaviconOverlay = (overlayPath) => {
const faviconEl = document.getElementById('favicon');
if (!faviconEl) {
......@@ -603,7 +603,7 @@ export const setFaviconOverlay = overlayPath => {
const iconPath = faviconEl.getAttribute('data-original-href');
return createOverlayIcon(iconPath, overlayPath).then(faviconWithOverlayUrl =>
return createOverlayIcon(iconPath, overlayPath).then((faviconWithOverlayUrl) =>
faviconEl.setAttribute('href', faviconWithOverlayUrl),
);
};
......@@ -617,7 +617,7 @@ export const resetFavicon = () => {
}
};
export const setCiStatusFavicon = pageUrl =>
export const setCiStatusFavicon = (pageUrl) =>
axios
.get(pageUrl)
.then(({ data }) => {
......@@ -626,7 +626,7 @@ export const setCiStatusFavicon = pageUrl =>
}
return resetFavicon();
})
.catch(error => {
.catch((error) => {
resetFavicon();
throw error;
});
......@@ -728,7 +728,7 @@ export const convertObjectPropsToCamelCase = (obj = {}, options = {}) =>
export const convertObjectPropsToSnakeCase = (obj = {}, options = {}) =>
convertObjectProps(convertToSnakeCase, obj, options);
export const imagePath = imgUrl =>
export const imagePath = (imgUrl) =>
`${gon.asset_host || ''}${gon.relative_url_root || ''}/assets/${imgUrl}`;
export const addSelectOnFocusBehaviour = (selector = '.js-select-on-focus') => {
......@@ -737,7 +737,7 @@ export const addSelectOnFocusBehaviour = (selector = '.js-select-on-focus') => {
$(selector).on('focusin', function selectOnFocusCallback() {
$(this)
.select()
.one('mouseup', e => {
.one('mouseup', (e) => {
e.preventDefault();
});
});
......@@ -833,7 +833,7 @@ export const searchBy = (query = '', searchSpace = {}) => {
const normalizedQuery = query.toLowerCase();
const matches = targetKeys
.filter(item => {
.filter((item) => {
const searchItem = `${searchSpace[item]}`.toLowerCase();
return (
......@@ -867,9 +867,9 @@ export const isScopedLabel = ({ title = '' }) => title.indexOf('::') !== -1;
// Methods to set and get Cookie
export const setCookie = (name, value) => Cookies.set(name, value, { expires: 365 });
export const getCookie = name => Cookies.get(name);
export const getCookie = (name) => Cookies.get(name);
export const removeCookie = name => Cookies.remove(name);
export const removeCookie = (name) => Cookies.remove(name);
/**
* Returns the status of a feature flag.
......@@ -884,4 +884,4 @@ export const removeCookie = name => Cookies.remove(name);
* @param {String} flag Feature flag
* @returns {Boolean} on/off
*/
export const isFeatureFlagEnabled = flag => window.gon.features?.[flag];
export const isFeatureFlagEnabled = (flag) => window.gon.features?.[flag];
export function loadCSSFile(path) {
return new Promise(resolve => {
return new Promise((resolve) => {
if (!path) resolve();
if (document.querySelector(`link[href="${path}"]`)) {
......
......@@ -7,7 +7,7 @@ const MINIMUM_DATE = new Date(0);
const DEFAULT_DIRECTION = 'before';
const durationToMillis = duration => {
const durationToMillis = (duration) => {
if (Object.entries(duration).length === 1 && Number.isFinite(duration.seconds)) {
return secondsToMilliseconds(duration.seconds);
}
......@@ -19,9 +19,9 @@ const dateMinusDuration = (date, duration) => new Date(date.getTime() - duration
const datePlusDuration = (date, duration) => new Date(date.getTime() + durationToMillis(duration));
const isValidDuration = duration => Boolean(duration && Number.isFinite(duration.seconds));
const isValidDuration = (duration) => Boolean(duration && Number.isFinite(duration.seconds));
const isValidDateString = dateString => {
const isValidDateString = (dateString) => {
if (typeof dateString !== 'string' || !dateString.trim()) {
return false;
}
......@@ -225,7 +225,7 @@ export function getRangeType(range) {
*
* @returns {FixedRange} An object with a start and end in ISO8601 format.
*/
export const convertToFixedRange = dateTimeRange =>
export const convertToFixedRange = (dateTimeRange) =>
handlers[getRangeType(dateTimeRange)](dateTimeRange);
/**
......@@ -242,7 +242,7 @@ export const convertToFixedRange = dateTimeRange =>
* @param {Object} timeRange - A time range object
* @returns Copy of time range
*/
const pruneTimeRange = timeRange => {
const pruneTimeRange = (timeRange) => {
const res = pick(timeRange, ['start', 'end', 'anchor', 'duration', 'direction']);
if (res.direction === DEFAULT_DIRECTION) {
return omit(res, 'direction');
......@@ -272,7 +272,7 @@ export const isEqualTimeRanges = (timeRange, other) => {
* @param {Array} timeRanges - Array of time tanges (haystack)
*/
export const findTimeRange = (timeRange, timeRanges) =>
timeRanges.find(element => isEqualTimeRanges(element, timeRange));
timeRanges.find((element) => isEqualTimeRanges(element, timeRange));
// Time Ranges as URL Parameters Utils
......@@ -289,11 +289,11 @@ export const timeRangeParamNames = ['start', 'end', 'anchor', 'duration_seconds'
* @param {Object} A time range
* @returns key-value pairs object that can be used as parameters in a URL.
*/
export const timeRangeToParams = timeRange => {
export const timeRangeToParams = (timeRange) => {
let params = pruneTimeRange(timeRange);
if (timeRange.duration) {
const durationParms = {};
Object.keys(timeRange.duration).forEach(key => {
Object.keys(timeRange.duration).forEach((key) => {
durationParms[`duration_${key}`] = timeRange.duration[key].toString();
});
params = { ...durationParms, ...params };
......@@ -309,7 +309,7 @@ export const timeRangeToParams = timeRange => {
*
* @param {params} params - key-value pairs object.
*/
export const timeRangeFromParams = params => {
export const timeRangeFromParams = (params) => {
const timeRangeParams = pick(params, timeRangeParamNames);
let range = Object.entries(timeRangeParams).reduce((acc, [key, val]) => {
// unflatten duration
......
......@@ -12,7 +12,7 @@ window.timeago = timeago;
*
* @param {Date} date
*/
export const newDate = date => (date instanceof Date ? new Date(date.getTime()) : new Date());
export const newDate = (date) => (date instanceof Date ? new Date(date.getTime()) : new Date());
/**
* Returns i18n month names array.
......@@ -21,7 +21,7 @@ export const newDate = date => (date instanceof Date ? new Date(date.getTime())
*
* @param {Boolean} abbreviated
*/
export const getMonthNames = abbreviated => {
export const getMonthNames = (abbreviated) => {
if (abbreviated) {
return [
s__('Jan'),
......@@ -74,7 +74,7 @@ export const getWeekdayNames = () => [
* @param {date} date
* @returns {String}
*/
export const getDayName = date =>
export const getDayName = (date) =>
[
__('Sunday'),
__('Monday'),
......@@ -242,7 +242,7 @@ export const getDayDifference = (a, b) => {
* @param {Number} seconds
* @return {String}
*/
export const timeIntervalInWords = intervalInSeconds => {
export const timeIntervalInWords = (intervalInSeconds) => {
const secondsInteger = parseInt(intervalInSeconds, 10);
const minutes = Math.floor(secondsInteger / 60);
const seconds = secondsInteger - minutes * 60;
......@@ -316,7 +316,7 @@ export const monthInWords = (date, abbreviated = false) => {
*
* @param {Date} date
*/
export const totalDaysInMonth = date => {
export const totalDaysInMonth = (date) => {
if (!date) {
return 0;
}
......@@ -329,7 +329,7 @@ export const totalDaysInMonth = date => {
*
* @param {Array} quarter
*/
export const totalDaysInQuarter = quarter =>
export const totalDaysInQuarter = (quarter) =>
quarter.reduce((acc, month) => acc + totalDaysInMonth(month), 0);
/**
......@@ -338,7 +338,7 @@ export const totalDaysInQuarter = quarter =>
*
* @param {Date} date
*/
export const getSundays = date => {
export const getSundays = (date) => {
if (!date) {
return [];
}
......@@ -449,7 +449,7 @@ window.gl.utils = {
* @param milliseconds
* @returns {string}
*/
export const formatTime = milliseconds => {
export const formatTime = (milliseconds) => {
const remainingSeconds = Math.floor(milliseconds / 1000) % 60;
const remainingMinutes = Math.floor(milliseconds / 1000 / 60) % 60;
const remainingHours = Math.floor(milliseconds / 1000 / 60 / 60);
......@@ -468,7 +468,7 @@ export const formatTime = milliseconds => {
* @param {String} dateString Date in yyyy-mm-dd format
* @return {Date} UTC format
*/
export const parsePikadayDate = dateString => {
export const parsePikadayDate = (dateString) => {
const parts = dateString.split('-');
const year = parseInt(parts[0], 10);
const month = parseInt(parts[1] - 1, 10);
......@@ -482,7 +482,7 @@ export const parsePikadayDate = dateString => {
* @param {Date} date UTC format
* @return {String} Date formatted in yyyy-mm-dd
*/
export const pikadayToString = date => {
export const pikadayToString = (date) => {
const day = pad(date.getDate());
const month = pad(date.getMonth() + 1);
const year = date.getFullYear();
......@@ -523,7 +523,7 @@ export const parseSeconds = (
let unorderedMinutes = Math.abs(seconds / SECONDS_PER_MINUTE);
return mapValues(timePeriodConstraints, minutesPerPeriod => {
return mapValues(timePeriodConstraints, (minutesPerPeriod) => {
if (minutesPerPeriod === 0) {
return 0;
}
......@@ -567,7 +567,7 @@ export const stringifyTime = (timeObject, fullNameFormat = false) => {
* @param endDate date string that the time difference is calculated for
* @return {Number} number of milliseconds remaining until the given date
*/
export const calculateRemainingMilliseconds = endDate => {
export const calculateRemainingMilliseconds = (endDate) => {
const remainingMilliseconds = new Date(endDate).getTime() - Date.now();
return Math.max(remainingMilliseconds, 0);
};
......@@ -598,7 +598,7 @@ export const getDateInFuture = (date, daysInFuture) =>
* @param {Date} date
* @returns boolean
*/
export const isValidDate = date => date instanceof Date && !Number.isNaN(date.getTime());
export const isValidDate = (date) => date instanceof Date && !Number.isNaN(date.getTime());
/*
* Appending T00:00:00 makes JS assume local time and prevents it from shifting the date
......@@ -606,7 +606,7 @@ export const isValidDate = date => date instanceof Date && !Number.isNaN(date.ge
* be consistent with the "edit issue -> due date" UI.
*/
export const newDateAsLocaleTime = date => {
export const newDateAsLocaleTime = (date) => {
const suffix = 'T00:00:00';
return new Date(`${date}${suffix}`);
};
......@@ -620,7 +620,7 @@ export const endOfDayTime = 'T23:59:59Z';
* @param {Function} formatter
* @return {Any[]} an array of formatted dates between 2 given dates (including start&end date)
*/
export const getDatesInRange = (d1, d2, formatter = x => x) => {
export const getDatesInRange = (d1, d2, formatter = (x) => x) => {
if (!(d1 instanceof Date) || !(d2 instanceof Date)) {
return [];
}
......@@ -643,7 +643,7 @@ export const getDatesInRange = (d1, d2, formatter = x => x) => {
* @param {Number} seconds
* @return {Number} number of milliseconds
*/
export const secondsToMilliseconds = seconds => seconds * 1000;
export const secondsToMilliseconds = (seconds) => seconds * 1000;
/**
* Converts the supplied number of seconds to days.
......@@ -651,7 +651,7 @@ export const secondsToMilliseconds = seconds => seconds * 1000;
* @param {Number} seconds
* @return {Number} number of days
*/
export const secondsToDays = seconds => Math.round(seconds / 86400);
export const secondsToDays = (seconds) => Math.round(seconds / 86400);
/**
* Converts a numeric utc offset in seconds to +/- hours
......@@ -662,7 +662,7 @@ export const secondsToDays = seconds => Math.round(seconds / 86400);
*
* @return {String} the + or - offset in hours
*/
export const secondsToHours = offset => {
export const secondsToHours = (offset) => {
const parsed = parseInt(offset, 10);
if (Number.isNaN(parsed) || parsed === 0) {
return `0`;
......@@ -687,7 +687,7 @@ export const nDaysAfter = (date, numberOfDays) =>
* @param {Date} date the initial date
* @return {Date} the date following the date provided
*/
export const dayAfter = date => new Date(newDate(date).setDate(date.getDate() + 1));
export const dayAfter = (date) => new Date(newDate(date).setDate(date.getDate() + 1));
/**
* Mimics the behaviour of the rails distance_of_time_in_words function
......@@ -795,7 +795,7 @@ export const differenceInMilliseconds = (startDate, endDate = Date.now()) => {
*
* @return {Date} the date at the first day of the month
*/
export const dateAtFirstDayOfMonth = date => new Date(newDate(date).setDate(1));
export const dateAtFirstDayOfMonth = (date) => new Date(newDate(date).setDate(1));
/**
* A utility function which checks if two dates match.
......
......@@ -6,7 +6,7 @@ import { isInIssuePage, isInMRPage, isInEpicPage } from './common_utils';
*
* @param element DOM element to check
*/
export const hasHorizontalOverflow = element =>
export const hasHorizontalOverflow = (element) =>
Boolean(element && element.scrollWidth > element.offsetWidth);
export const addClassIfElementExists = (element, className) => {
......@@ -64,7 +64,7 @@ export const parseBooleanDataAttributes = ({ dataset }, names) =>
* @param {HTMLElement} element The element to test
* @returns {Boolean} `true` if the element is currently visible, otherwise false
*/
export const isElementVisible = element =>
export const isElementVisible = (element) =>
Boolean(element.offsetWidth || element.offsetHeight || element.getClientRects().length);
/**
......@@ -76,4 +76,4 @@ export const isElementVisible = element =>
* @param {HTMLElement} element The element to test
* @returns {Boolean} `true` if the element is currently hidden, otherwise false
*/
export const isElementHidden = element => !isElementVisible(element);
export const isElementHidden = (element) => !isElementVisible(element);
export const serializeFormEntries = entries =>
export const serializeFormEntries = (entries) =>
entries.reduce((acc, { name, value }) => Object.assign(acc, { [name]: value }), {});
export const serializeForm = form => {
export const serializeForm = (form) => {
const fdata = new FormData(form);
const entries = Array.from(fdata.keys()).map(key => {
const entries = Array.from(fdata.keys()).map((key) => {
let val = fdata.getAll(key);
// Microsoft Edge has a bug in FormData.getAll() that returns an undefined
// value for each form element that does not match the given key:
// https://github.com/jimmywarting/FormData/issues/80
val = val.filter(n => n);
val = val.filter((n) => n);
return { name: key, value: val.length === 1 ? val[0] : val };
});
......@@ -27,7 +27,7 @@ export const serializeForm = form => {
* @example
* returns true for '', [], null, undefined
*/
export const isEmptyValue = value => value == null || value.length === 0;
export const isEmptyValue = (value) => value == null || value.length === 0;
/**
* A form object serializer
......@@ -42,7 +42,7 @@ export const isEmptyValue = value => value == null || value.length === 0;
* Returns
* {"project": "hello", "username": "john"}
*/
export const serializeFormObject = form =>
export const serializeFormObject = (form) =>
Object.fromEntries(
Object.entries(form).reduce((acc, [name, { value }]) => {
if (!isEmptyValue(value)) {
......
......@@ -16,7 +16,7 @@ import { sprintf, s__ } from '~/locale';
*
* @param {String[]} items
*/
export const toNounSeriesText = items => {
export const toNounSeriesText = (items) => {
if (items.length === 0) {
return '';
} else if (items.length === 1) {
......
......@@ -9,7 +9,7 @@ const getSvgDom = memoize(() =>
axios
.get(gon.sprite_icons)
.then(({ data: svgs }) => new DOMParser().parseFromString(svgs, 'text/xml'))
.catch(e => {
.catch((e) => {
getSvgDom.cache.clear();
throw e;
......@@ -34,9 +34,9 @@ export const clearSvgIconPathContentCache = () => {
* @param {String} name - Icon name
* @returns A promise that resolves to the svg path
*/
export const getSvgIconPathContent = name =>
export const getSvgIconPathContent = (name) =>
getSvgDom()
.then(doc => {
.then((doc) => {
return doc.querySelector(`#${name} path`).getAttribute('d');
})
.catch(() => null);
......@@ -32,7 +32,7 @@ function notifyMe(message, body, icon, onclick) {
// If it's okay let's create a notification
return notificationGranted(message, opts, onclick);
} else if (Notification.permission !== 'denied') {
return Notification.requestPermission(permission => {
return Notification.requestPermission((permission) => {
// If the user accepts, let's create a notification
if (permission === 'granted') {
return notificationGranted(message, opts, onclick);
......
......@@ -112,7 +112,7 @@ export const isOdd = (number = 0) => number % 2;
* @param {Array} arr An array of numbers
* @returns {Number} The median of the given array
*/
export const median = arr => {
export const median = (arr) => {
const middle = Math.floor(arr.length / 2);
const sorted = arr.sort((a, b) => a - b);
return arr.length % 2 !== 0 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
......
......@@ -102,11 +102,11 @@ export default class Poll {
notificationCallback(true);
return resource[method](data)
.then(response => {
.then((response) => {
this.checkConditions(response);
notificationCallback(false);
})
.catch(error => {
.catch((error) => {
notificationCallback(false);
if (error.status === httpStatusCodes.ABORTED) {
return;
......
......@@ -29,7 +29,7 @@ export default (url, config = {}) =>
},
data: { url, config },
method: 'axiosGet',
successCallback: response => {
successCallback: (response) => {
if (response.status === httpStatusCodes.OK) {
resolve(response);
eTagPoll.stop();
......
......@@ -5,4 +5,4 @@
* @returns {boolean}
*/
export const isSubset = (subset, superset) =>
Array.from(subset).every(value => superset.has(value));
Array.from(subset).every((value) => superset.has(value));
......@@ -4,7 +4,7 @@ export default (fn, { interval = 2000, timeout = 60000 } = {}) => {
const startTime = Date.now();
return new Promise((resolve, reject) => {
const stop = arg => (arg instanceof Error ? reject(arg) : resolve(arg));
const stop = (arg) => (arg instanceof Error ? reject(arg) : resolve(arg));
const next = () => {
if (timeout === 0 || differenceInMilliseconds(startTime) < timeout) {
setTimeout(fn.bind(null, next, stop), interval);
......
......@@ -67,6 +67,6 @@ export const stickyMonitor = (el, stickyTop, insertPlaceholder = true) => {
* - If the current environment supports `position: sticky`, do nothing.
* - Can receive an iterable element list (NodeList, jQuery collection, etc.) or single HTMLElement.
*/
export const polyfillSticky = el => {
export const polyfillSticky = (el) => {
StickyFill.add(el);
};
......@@ -220,7 +220,7 @@ export function insertMarkdownText({
: blockTagText(text, textArea, blockTag, selected);
} else {
textToInsert = selectedSplit
.map(val => {
.map((val) => {
if (tag.indexOf(textPlaceholder) > -1) {
return tag.replace(textPlaceholder, val);
}
......@@ -349,7 +349,7 @@ export function addEditorMarkdownListeners(editor) {
// eslint-disable-next-line @gitlab/no-global-event-off
$('.js-md')
.off('click')
.on('click', e => {
.on('click', (e) => {
const { mdTag, mdBlock, mdPrepend, mdSelect } = $(e.currentTarget).data();
insertMarkdownText({
......
......@@ -14,7 +14,7 @@ import {
* @param {String} text
* @returns {String}
*/
export const addDelimiter = text =>
export const addDelimiter = (text) =>
text ? text.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') : text;
/**
......@@ -23,7 +23,7 @@ export const addDelimiter = text =>
* @param {Number} count
* @return {Number|String}
*/
export const highCountTrim = count => (count > 99 ? '99+' : count);
export const highCountTrim = (count) => (count > 99 ? '99+' : count);
/**
* Converts first char to uppercase and replaces the given separator with spaces
......@@ -43,7 +43,7 @@ export const humanize = (string, separator = '_') => {
* @param {*} str
* @returns {String}
*/
export const dasherize = str => str.replace(/[_\s]+/g, '-');
export const dasherize = (str) => str.replace(/[_\s]+/g, '-');
/**
* Replaces whitespace and non-sluggish characters with a given separator
......@@ -69,7 +69,7 @@ export const slugify = (str, separator = '-') => {
* @param {String} str
* @returns {String}
*/
export const slugifyWithUnderscore = str => slugify(str, '_');
export const slugifyWithUnderscore = (str) => slugify(str, '_');
/**
* Truncates given text
......@@ -158,7 +158,7 @@ export const truncateWidth = (string, options = {}) => {
* @param {String} sha
* @returns {String}
*/
export const truncateSha = sha => sha.substring(0, 8);
export const truncateSha = (sha) => sha.substring(0, 8);
const ELLIPSIS_CHAR = '';
export const truncatePathMiddleToLength = (text, maxWidth) => {
......@@ -166,7 +166,7 @@ export const truncatePathMiddleToLength = (text, maxWidth) => {
let ellipsisCount = 0;
while (returnText.length >= maxWidth) {
const textSplit = returnText.split('/').filter(s => s !== ELLIPSIS_CHAR);
const textSplit = returnText.split('/').filter((s) => s !== ELLIPSIS_CHAR);
if (textSplit.length === 0) {
// There are n - 1 path separators for n segments, so 2n - 1 <= maxWidth
......@@ -243,7 +243,7 @@ export const stripHtml = (string, replace = '') => {
* // returns "trailingUnderscore_"
* convertToCamelCase('trailing_underscore_')
*/
export const convertToCamelCase = string =>
export const convertToCamelCase = (string) =>
string.replace(/([a-z0-9])_([a-z0-9])/gi, (match, p1, p2) => `${p1}${p2.toUpperCase()}`);
/**
......@@ -251,7 +251,7 @@ export const convertToCamelCase = string =>
*
* @param {*} string
*/
export const convertToSnakeCase = string =>
export const convertToSnakeCase = (string) =>
slugifyWithUnderscore((string.match(/([a-zA-Z][^A-Z]*)/g) || [string]).join(' '));
/**
......@@ -260,7 +260,7 @@ export const convertToSnakeCase = string =>
*
* @param {*} string
*/
export const convertToSentenceCase = string => {
export const convertToSentenceCase = (string) => {
const splitWord = string.split(' ').map((word, index) => (index > 0 ? word.toLowerCase() : word));
return splitWord.join(' ');
......@@ -273,7 +273,7 @@ export const convertToSentenceCase = string => {
* @param {String} string
* @returns {String}
*/
export const convertToTitleCase = string => string.replace(/\b[a-z]/g, s => s.toUpperCase());
export const convertToTitleCase = (string) => string.replace(/\b[a-z]/g, (s) => s.toUpperCase());
const unicodeConversion = [
[/[ÀÁÂÃÅĀĂĄ]/g, 'A'],
......@@ -340,7 +340,7 @@ const unicodeConversion = [
* @param {String} string
* @returns {String}
*/
export const convertUnicodeToAscii = string => {
export const convertUnicodeToAscii = (string) => {
let convertedString = string;
unicodeConversion.forEach(([regex, replacer]) => {
......@@ -356,7 +356,7 @@ export const convertUnicodeToAscii = string => {
*
* @param {*} string
*/
export const splitCamelCase = string =>
export const splitCamelCase = (string) =>
string
.replace(/([A-Z]+)([A-Z][a-z])/g, ' $1 $2')
.replace(/([a-z\d])([A-Z])/g, '$1 $2')
......@@ -398,7 +398,7 @@ export const truncateNamespace = (string = '') => {
* @param {String} obj The object to test
* @returns {Boolean}
*/
export const hasContent = obj => isString(obj) && obj.trim() !== '';
export const hasContent = (obj) => isString(obj) && obj.trim() !== '';
/**
* A utility function that validates if a
......@@ -408,7 +408,7 @@ export const hasContent = obj => isString(obj) && obj.trim() !== '';
*
* @return {Boolean} true if valid
*/
export const isValidSha1Hash = str => {
export const isValidSha1Hash = (str) => {
return /^[0-9a-f]{5,40}$/.test(str);
};
......
export const isObject = obj => obj && obj.constructor === Object;
export const isObject = (obj) => obj && obj.constructor === Object;
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