Commit 8639c778 authored by Mike Greiling's avatar Mike Greiling

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

Format files with prettier arrowParens [3/15]

See merge request gitlab-org/gitlab!50528
parents ac332957 73993b43
...@@ -10,177 +10,6 @@ doc/api/graphql/reference/gitlab_schema.graphql ...@@ -10,177 +10,6 @@ doc/api/graphql/reference/gitlab_schema.graphql
*.scss *.scss
*.md *.md
## relaxed-kilby
app/assets/javascripts/ci_variable_list/store/actions.js
app/assets/javascripts/ci_variable_list/store/getters.js
app/assets/javascripts/ci_variable_list/store/utils.js
app/assets/javascripts/clone_panel.js
app/assets/javascripts/clusters/clusters_bundle.js
app/assets/javascripts/clusters/components/fluentd_output_settings.vue
app/assets/javascripts/clusters/forms/stores/index.js
app/assets/javascripts/clusters/stores/clusters_store.js
app/assets/javascripts/clusters/stores/new_cluster/index.js
app/assets/javascripts/clusters_list/components/clusters.vue
app/assets/javascripts/clusters_list/load_clusters.js
app/assets/javascripts/clusters_list/store/actions.js
app/assets/javascripts/clusters_list/store/index.js
app/assets/javascripts/code_navigation/index.js
app/assets/javascripts/code_navigation/store/actions.js
app/assets/javascripts/code_navigation/utils/index.js
app/assets/javascripts/commit/image_file.js
app/assets/javascripts/commit/pipelines/pipelines_bundle.js
app/assets/javascripts/commit_merge_requests.js
app/assets/javascripts/commons/nav/user_merge_requests.js
app/assets/javascripts/compare_autocomplete.js
app/assets/javascripts/confidential_merge_request/components/project_form_group.vue
app/assets/javascripts/confirm_danger_modal.js
app/assets/javascripts/confirm_modal.js
app/assets/javascripts/contributors/components/contributors.vue
app/assets/javascripts/contributors/stores/actions.js
app/assets/javascripts/contributors/stores/getters.js
app/assets/javascripts/contributors/utils.js
app/assets/javascripts/create_cluster/components/cluster_form_dropdown.vue
app/assets/javascripts/create_cluster/eks_cluster/index.js
app/assets/javascripts/create_cluster/eks_cluster/services/aws_services_facade.js
## lucid-lederberg
app/assets/javascripts/create_cluster/eks_cluster/store/actions.js
app/assets/javascripts/create_cluster/eks_cluster/store/state.js
app/assets/javascripts/create_cluster/gke_cluster/components/gke_dropdown_mixin.js
app/assets/javascripts/create_cluster/gke_cluster/components/gke_project_id_dropdown.vue
app/assets/javascripts/create_cluster/gke_cluster/index.js
app/assets/javascripts/create_cluster/gke_cluster/store/actions.js
app/assets/javascripts/create_cluster/gke_cluster/store/getters.js
app/assets/javascripts/create_cluster/gke_cluster_namespace/index.js
app/assets/javascripts/create_cluster/init_create_cluster.js
app/assets/javascripts/create_cluster/store/cluster_dropdown/actions.js
app/assets/javascripts/create_item_dropdown.js
app/assets/javascripts/create_label.js
app/assets/javascripts/create_merge_request_dropdown.js
app/assets/javascripts/custom_metrics/components/custom_metrics_form_fields.vue
app/assets/javascripts/custom_metrics/constants.js
app/assets/javascripts/cycle_analytics/cycle_analytics_bundle.js
app/assets/javascripts/cycle_analytics/cycle_analytics_service.js
app/assets/javascripts/cycle_analytics/cycle_analytics_store.js
app/assets/javascripts/deploy_freeze/store/actions.js
app/assets/javascripts/deploy_freeze/store/index.js
app/assets/javascripts/deploy_freeze/store/mutations.js
app/assets/javascripts/deploy_keys/components/app.vue
app/assets/javascripts/deploy_keys/components/key.vue
app/assets/javascripts/deploy_keys/service/index.js
app/assets/javascripts/deploy_keys/store/index.js
app/assets/javascripts/deprecated_jquery_dropdown/gl_dropdown.js
app/assets/javascripts/deprecated_jquery_dropdown/gl_dropdown_filter.js
app/assets/javascripts/deprecated_jquery_dropdown/gl_dropdown_input.js
app/assets/javascripts/deprecated_jquery_dropdown/gl_dropdown_remote.js
app/assets/javascripts/design_management/components/design_notes/design_discussion.vue
app/assets/javascripts/design_management/components/design_presentation.vue
app/assets/javascripts/design_management/components/design_sidebar.vue
app/assets/javascripts/design_management/components/design_todo_button.vue
## loving-feistel
app/assets/javascripts/design_management/components/toolbar/design_navigation.vue
app/assets/javascripts/design_management/components/toolbar/index.vue
app/assets/javascripts/design_management/components/upload/design_version_dropdown.vue
app/assets/javascripts/design_management/graphql.js
app/assets/javascripts/design_management/mixins/all_designs.js
app/assets/javascripts/design_management/mixins/all_versions.js
app/assets/javascripts/design_management/pages/design/index.vue
app/assets/javascripts/design_management/pages/index.vue
app/assets/javascripts/design_management/utils/cache_update.js
app/assets/javascripts/design_management/utils/design_management_utils.js
app/assets/javascripts/design_management/utils/error_messages.js
app/assets/javascripts/diff.js
app/assets/javascripts/diffs/components/app.vue
app/assets/javascripts/diffs/components/compare_dropdown_layout.vue
app/assets/javascripts/diffs/components/diff_content.vue
app/assets/javascripts/diffs/components/diff_expansion_cell.vue
app/assets/javascripts/diffs/components/diff_file.vue
app/assets/javascripts/diffs/components/diff_gutter_avatars.vue
app/assets/javascripts/diffs/components/diff_line_note_form.vue
app/assets/javascripts/diffs/components/diff_row_utils.js
app/assets/javascripts/diffs/components/parallel_diff_table_row.vue
app/assets/javascripts/diffs/components/tree_list.vue
app/assets/javascripts/diffs/index.js
app/assets/javascripts/diffs/store/actions.js
app/assets/javascripts/diffs/store/getters_versions_dropdowns.js
app/assets/javascripts/diffs/store/mutations.js
app/assets/javascripts/diffs/store/utils.js
app/assets/javascripts/diffs/utils/diff_file.js
app/assets/javascripts/diffs/workers/tree_worker.js
app/assets/javascripts/dirty_submit/dirty_submit_collection.js
app/assets/javascripts/dirty_submit/dirty_submit_form.js
## distracted-nash
app/assets/javascripts/droplab/drop_down.js
app/assets/javascripts/droplab/drop_lab.js
app/assets/javascripts/droplab/hook_button.js
app/assets/javascripts/droplab/hook_input.js
app/assets/javascripts/droplab/plugins/ajax.js
app/assets/javascripts/droplab/plugins/ajax_filter.js
app/assets/javascripts/droplab/plugins/input_setter.js
app/assets/javascripts/due_date_select.js
app/assets/javascripts/editor/editor_lite.js
app/assets/javascripts/editor/editor_markdown_ext.js
app/assets/javascripts/editor/utils.js
app/assets/javascripts/emoji/index.js
app/assets/javascripts/emoji/no_emoji_validator.js
app/assets/javascripts/emoji/support/is_emoji_unicode_supported.js
app/assets/javascripts/emoji/support/unicode_support_map.js
app/assets/javascripts/environments/components/environment_item.vue
app/assets/javascripts/environments/components/environment_rollback.vue
app/assets/javascripts/environments/components/environments_app.vue
app/assets/javascripts/environments/components/environments_table.vue
app/assets/javascripts/environments/mixins/environments_mixin.js
app/assets/javascripts/environments/stores/environments_store.js
app/assets/javascripts/error_tracking/components/error_details.vue
app/assets/javascripts/error_tracking/store/actions.js
app/assets/javascripts/error_tracking/store/details/actions.js
app/assets/javascripts/error_tracking/store/details/getters.js
app/assets/javascripts/error_tracking/store/list/mutations.js
app/assets/javascripts/error_tracking/utils.js
app/assets/javascripts/error_tracking_settings/store/actions.js
app/assets/javascripts/error_tracking_settings/store/getters.js
app/assets/javascripts/error_tracking_settings/store/mutations.js
app/assets/javascripts/error_tracking_settings/utils.js
## modest-mayer
app/assets/javascripts/experimental_flags.js
app/assets/javascripts/feature_flags/components/edit_feature_flag.vue
app/assets/javascripts/feature_flags/components/feature_flags.vue
app/assets/javascripts/feature_flags/components/feature_flags_table.vue
app/assets/javascripts/feature_flags/components/form.vue
app/assets/javascripts/feature_flags/components/new_feature_flag.vue
app/assets/javascripts/feature_flags/store/edit/actions.js
app/assets/javascripts/feature_flags/store/edit/index.js
app/assets/javascripts/feature_flags/store/gitlab_user_list/actions.js
app/assets/javascripts/feature_flags/store/gitlab_user_list/index.js
app/assets/javascripts/feature_flags/store/helpers.js
app/assets/javascripts/feature_flags/store/index/actions.js
app/assets/javascripts/feature_flags/store/index/index.js
app/assets/javascripts/feature_flags/store/index/mutations.js
app/assets/javascripts/feature_flags/store/new/actions.js
app/assets/javascripts/feature_flags/store/new/index.js
app/assets/javascripts/feature_flags/utils.js
app/assets/javascripts/feature_highlight/feature_highlight.js
app/assets/javascripts/feature_highlight/feature_highlight_helper.js
app/assets/javascripts/file_pickers.js
app/assets/javascripts/files_comment_button.js
app/assets/javascripts/filterable_list.js
app/assets/javascripts/filtered_search/available_dropdown_mappings.js
app/assets/javascripts/filtered_search/components/recent_searches_dropdown_content.vue
app/assets/javascripts/filtered_search/dropdown_ajax_filter.js
app/assets/javascripts/filtered_search/dropdown_emoji.js
app/assets/javascripts/filtered_search/dropdown_hint.js
app/assets/javascripts/filtered_search/dropdown_non_user.js
app/assets/javascripts/filtered_search/dropdown_utils.js
app/assets/javascripts/filtered_search/filtered_search_dropdown.js
app/assets/javascripts/filtered_search/filtered_search_dropdown_manager.js
app/assets/javascripts/filtered_search/filtered_search_manager.js
app/assets/javascripts/filtered_search/filtered_search_token_keys.js
app/assets/javascripts/filtered_search/filtered_search_visual_tokens.js
app/assets/javascripts/filtered_search/issuable_filtered_search_token_keys.js
## stoic-merkle ## stoic-merkle
app/assets/javascripts/filtered_search/stores/recent_searches_store.js app/assets/javascripts/filtered_search/stores/recent_searches_store.js
app/assets/javascripts/filtered_search/visual_token_value.js app/assets/javascripts/filtered_search/visual_token_value.js
......
...@@ -47,7 +47,7 @@ export const addVariable = ({ state, dispatch }) => { ...@@ -47,7 +47,7 @@ export const addVariable = ({ state, dispatch }) => {
dispatch('receiveAddVariableSuccess'); dispatch('receiveAddVariableSuccess');
dispatch('fetchVariables'); dispatch('fetchVariables');
}) })
.catch(error => { .catch((error) => {
createFlash(error.response.data[0]); createFlash(error.response.data[0]);
dispatch('receiveAddVariableError', error); dispatch('receiveAddVariableError', error);
}); });
...@@ -77,7 +77,7 @@ export const updateVariable = ({ state, dispatch }) => { ...@@ -77,7 +77,7 @@ export const updateVariable = ({ state, dispatch }) => {
dispatch('receiveUpdateVariableSuccess'); dispatch('receiveUpdateVariableSuccess');
dispatch('fetchVariables'); dispatch('fetchVariables');
}) })
.catch(error => { .catch((error) => {
createFlash(error.response.data[0]); createFlash(error.response.data[0]);
dispatch('receiveUpdateVariableError', error); dispatch('receiveUpdateVariableError', error);
}); });
...@@ -132,7 +132,7 @@ export const deleteVariable = ({ dispatch, state }) => { ...@@ -132,7 +132,7 @@ export const deleteVariable = ({ dispatch, state }) => {
dispatch('receiveDeleteVariableSuccess'); dispatch('receiveDeleteVariableSuccess');
dispatch('fetchVariables'); dispatch('fetchVariables');
}) })
.catch(error => { .catch((error) => {
createFlash(error.response.data[0]); createFlash(error.response.data[0]);
dispatch('receiveDeleteVariableError', error); dispatch('receiveDeleteVariableError', error);
}); });
...@@ -150,7 +150,7 @@ export const fetchEnvironments = ({ dispatch, state }) => { ...@@ -150,7 +150,7 @@ export const fetchEnvironments = ({ dispatch, state }) => {
dispatch('requestEnvironments'); dispatch('requestEnvironments');
return Api.environments(state.projectId) return Api.environments(state.projectId)
.then(res => { .then((res) => {
dispatch('receiveEnvironmentsSuccess', prepareEnvironments(res.data)); dispatch('receiveEnvironmentsSuccess', prepareEnvironments(res.data));
}) })
.catch(() => { .catch(() => {
......
import { uniq } from 'lodash'; import { uniq } from 'lodash';
export const joinedEnvironments = state => { export const joinedEnvironments = (state) => {
const scopesFromVariables = (state.variables || []).map(variable => variable.environment_scope); const scopesFromVariables = (state.variables || []).map((variable) => variable.environment_scope);
return uniq(state.environments.concat(scopesFromVariables)).sort(); return uniq(state.environments.concat(scopesFromVariables)).sort();
}; };
import { cloneDeep } from 'lodash'; import { cloneDeep } from 'lodash';
import { displayText, types } from '../constants'; import { displayText, types } from '../constants';
const variableTypeHandler = type => const variableTypeHandler = (type) =>
type === displayText.variableText ? types.variableType : types.fileType; type === displayText.variableText ? types.variableType : types.fileType;
export const prepareDataForDisplay = variables => { export const prepareDataForDisplay = (variables) => {
const variablesToDisplay = []; const variablesToDisplay = [];
variables.forEach(variable => { variables.forEach((variable) => {
const variableCopy = variable; const variableCopy = variable;
if (variableCopy.variable_type === types.variableType) { if (variableCopy.variable_type === types.variableType) {
variableCopy.variable_type = displayText.variableText; variableCopy.variable_type = displayText.variableText;
...@@ -42,4 +42,4 @@ export const prepareDataForApi = (variable, destroy = false) => { ...@@ -42,4 +42,4 @@ export const prepareDataForApi = (variable, destroy = false) => {
return variableCopy; return variableCopy;
}; };
export const prepareEnvironments = environments => environments.map(e => e.name); export const prepareEnvironments = (environments) => environments.map((e) => e.name);
...@@ -14,7 +14,7 @@ export default function initClonePanel() { ...@@ -14,7 +14,7 @@ export default function initClonePanel() {
$(`a:contains('${selectedCloneOption}')`, $cloneOptions).addClass('is-active'); $(`a:contains('${selectedCloneOption}')`, $cloneOptions).addClass('is-active');
} }
$('a', $cloneOptions).on('click', e => { $('a', $cloneOptions).on('click', (e) => {
e.preventDefault(); e.preventDefault();
const $this = $(e.currentTarget); const $this = $(e.currentTarget);
const url = $this.attr('href'); const url = $this.attr('href');
......
...@@ -128,7 +128,7 @@ export default class Clusters { ...@@ -128,7 +128,7 @@ export default class Clusters {
this.initPolling( this.initPolling(
'fetchClusterEnvironments', 'fetchClusterEnvironments',
data => this.handleClusterEnvironmentsSuccess(data), (data) => this.handleClusterEnvironmentsSuccess(data),
() => this.handleEnvironmentsPollError(), () => this.handleEnvironmentsPollError(),
); );
} }
...@@ -139,7 +139,7 @@ export default class Clusters { ...@@ -139,7 +139,7 @@ export default class Clusters {
if (statusPath && !this.environments) { if (statusPath && !this.environments) {
this.initPolling( this.initPolling(
'fetchClusterStatus', 'fetchClusterStatus',
data => this.handleClusterStatusSuccess(data), (data) => this.handleClusterStatusSuccess(data),
() => this.handlePollError(), () => this.handlePollError(),
); );
} }
...@@ -248,15 +248,15 @@ export default class Clusters { ...@@ -248,15 +248,15 @@ export default class Clusters {
addListeners() { addListeners() {
eventHub.$on('installApplication', this.installApplication); eventHub.$on('installApplication', this.installApplication);
eventHub.$on('updateApplication', data => this.updateApplication(data)); eventHub.$on('updateApplication', (data) => this.updateApplication(data));
eventHub.$on('saveKnativeDomain', data => this.saveKnativeDomain(data)); eventHub.$on('saveKnativeDomain', (data) => this.saveKnativeDomain(data));
eventHub.$on('setKnativeDomain', data => this.setKnativeDomain(data)); eventHub.$on('setKnativeDomain', (data) => this.setKnativeDomain(data));
eventHub.$on('uninstallApplication', data => this.uninstallApplication(data)); eventHub.$on('uninstallApplication', (data) => this.uninstallApplication(data));
eventHub.$on('setCrossplaneProviderStack', data => this.setCrossplaneProviderStack(data)); eventHub.$on('setCrossplaneProviderStack', (data) => this.setCrossplaneProviderStack(data));
eventHub.$on('setIngressModSecurityEnabled', data => this.setIngressModSecurityEnabled(data)); eventHub.$on('setIngressModSecurityEnabled', (data) => this.setIngressModSecurityEnabled(data));
eventHub.$on('setIngressModSecurityMode', data => this.setIngressModSecurityMode(data)); eventHub.$on('setIngressModSecurityMode', (data) => this.setIngressModSecurityMode(data));
eventHub.$on('resetIngressModSecurityChanges', id => this.resetIngressModSecurityChanges(id)); eventHub.$on('resetIngressModSecurityChanges', (id) => this.resetIngressModSecurityChanges(id));
eventHub.$on('setFluentdSettings', data => this.setFluentdSettings(data)); eventHub.$on('setFluentdSettings', (data) => this.setFluentdSettings(data));
// Add event listener to all the banner close buttons // Add event listener to all the banner close buttons
this.addBannerCloseHandler(this.unreachableContainer, 'unreachable'); this.addBannerCloseHandler(this.unreachableContainer, 'unreachable');
this.addBannerCloseHandler(this.authenticationFailureContainer, 'authentication_failure'); this.addBannerCloseHandler(this.authenticationFailureContainer, 'authentication_failure');
...@@ -343,12 +343,12 @@ export default class Clusters { ...@@ -343,12 +343,12 @@ export default class Clusters {
checkForNewInstalls(prevApplicationMap, newApplicationMap) { checkForNewInstalls(prevApplicationMap, newApplicationMap) {
const appTitles = Object.keys(newApplicationMap) const appTitles = Object.keys(newApplicationMap)
.filter( .filter(
appId => (appId) =>
newApplicationMap[appId].status === APPLICATION_STATUS.INSTALLED && newApplicationMap[appId].status === APPLICATION_STATUS.INSTALLED &&
prevApplicationMap[appId].status !== APPLICATION_STATUS.INSTALLED && prevApplicationMap[appId].status !== APPLICATION_STATUS.INSTALLED &&
prevApplicationMap[appId].status !== null, prevApplicationMap[appId].status !== null,
) )
.map(appId => newApplicationMap[appId].title); .map((appId) => newApplicationMap[appId].title);
if (appTitles.length > 0) { if (appTitles.length > 0) {
const text = sprintf( const text = sprintf(
...@@ -450,7 +450,7 @@ export default class Clusters { ...@@ -450,7 +450,7 @@ export default class Clusters {
); );
}); });
}) })
.catch(error => this.store.updateAppProperty(appId, 'validationError', error)); .catch((error) => this.store.updateAppProperty(appId, 'validationError', error));
} }
static validateInstallation(appId, params) { static validateInstallation(appId, params) {
......
...@@ -127,7 +127,7 @@ export default { ...@@ -127,7 +127,7 @@ export default {
}); });
}, },
updateCurrentServerSideSettings(settings) { updateCurrentServerSideSettings(settings) {
Object.keys(settings).forEach(key => { Object.keys(settings).forEach((key) => {
if (this.currentServerSideSettings[key] === null) { if (this.currentServerSideSettings[key] === null) {
this.currentServerSideSettings[key] = this[key]; this.currentServerSideSettings[key] = this[key];
} }
......
...@@ -4,7 +4,7 @@ import state from './state'; ...@@ -4,7 +4,7 @@ import state from './state';
Vue.use(Vuex); Vue.use(Vuex);
export const createStore = initialState => export const createStore = (initialState) =>
new Vuex.Store({ new Vuex.Store({
state: state(initialState), state: state(initialState),
}); });
......
...@@ -17,7 +17,7 @@ import { ...@@ -17,7 +17,7 @@ import {
} from '../constants'; } from '../constants';
import transitionApplicationState from '../services/application_state_machine'; import transitionApplicationState from '../services/application_state_machine';
const isApplicationInstalled = appStatus => APPLICATION_INSTALLED_STATUSES.includes(appStatus); const isApplicationInstalled = (appStatus) => APPLICATION_INSTALLED_STATUSES.includes(appStatus);
const applicationInitialState = { const applicationInitialState = {
status: null, status: null,
...@@ -195,7 +195,7 @@ export default class ClusterStore { ...@@ -195,7 +195,7 @@ export default class ClusterStore {
this.state.status = serverState.status; this.state.status = serverState.status;
this.state.statusReason = serverState.status_reason; this.state.statusReason = serverState.status_reason;
serverState.applications.forEach(serverAppEntry => { serverState.applications.forEach((serverAppEntry) => {
const { const {
name: appId, name: appId,
status, status,
...@@ -284,7 +284,7 @@ export default class ClusterStore { ...@@ -284,7 +284,7 @@ export default class ClusterStore {
} }
updateEnvironments(environments = []) { updateEnvironments(environments = []) {
this.state.environments = environments.map(environment => ({ this.state.environments = environments.map((environment) => ({
name: environment.name, name: environment.name,
project: environment.project, project: environment.project,
environmentPath: environment.environment_path, environmentPath: environment.environment_path,
......
...@@ -4,7 +4,7 @@ import state from './state'; ...@@ -4,7 +4,7 @@ import state from './state';
Vue.use(Vuex); Vue.use(Vuex);
export const createStore = initialState => export const createStore = (initialState) =>
new Vuex.Store({ new Vuex.Store({
state: state(initialState), state: state(initialState),
}); });
......
...@@ -79,7 +79,7 @@ export default { ...@@ -79,7 +79,7 @@ export default {
{ {
key: 'cluster_type', key: 'cluster_type',
label: __('Cluster level'), label: __('Cluster level'),
formatter: value => CLUSTER_TYPES[value], formatter: (value) => CLUSTER_TYPES[value],
}, },
]; ];
}, },
......
import Clusters from './components/clusters.vue'; import Clusters from './components/clusters.vue';
import { createStore } from './store'; import { createStore } from './store';
export default Vue => { export default (Vue) => {
const el = document.querySelector('#js-clusters-list-app'); const el = document.querySelector('#js-clusters-list-app');
if (!el) { if (!el) {
......
...@@ -13,11 +13,11 @@ const allNodesPresent = (clusters, retryCount) => { ...@@ -13,11 +13,11 @@ const allNodesPresent = (clusters, retryCount) => {
They may fail for reasons GitLab cannot control. They may fail for reasons GitLab cannot control.
MAX_REQUESTS will ensure this poll stops at some point. MAX_REQUESTS will ensure this poll stops at some point.
*/ */
return retryCount > MAX_REQUESTS || clusters.every(cluster => cluster.nodes != null); return retryCount > MAX_REQUESTS || clusters.every((cluster) => cluster.nodes != null);
}; };
export const reportSentryError = (_store, { error, tag }) => { export const reportSentryError = (_store, { error, tag }) => {
Sentry.withScope(scope => { Sentry.withScope((scope) => {
scope.setTag('javascript_clusters_list', tag); scope.setTag('javascript_clusters_list', tag);
Sentry.captureException(error); Sentry.captureException(error);
}); });
...@@ -30,7 +30,7 @@ export const fetchClusters = ({ state, commit, dispatch }) => { ...@@ -30,7 +30,7 @@ export const fetchClusters = ({ state, commit, dispatch }) => {
const poll = new Poll({ const poll = new Poll({
resource: { resource: {
fetchClusters: paginatedEndPoint => axios.get(paginatedEndPoint), fetchClusters: (paginatedEndPoint) => axios.get(paginatedEndPoint),
}, },
data: `${state.endpoint}?page=${state.page}`, data: `${state.endpoint}?page=${state.page}`,
method: 'fetchClusters', method: 'fetchClusters',
...@@ -59,7 +59,7 @@ export const fetchClusters = ({ state, commit, dispatch }) => { ...@@ -59,7 +59,7 @@ export const fetchClusters = ({ state, commit, dispatch }) => {
dispatch('reportSentryError', { error, tag: 'fetchClustersSuccessCallback' }); dispatch('reportSentryError', { error, tag: 'fetchClustersSuccessCallback' });
} }
}, },
errorCallback: response => { errorCallback: (response) => {
poll.stop(); poll.stop();
commit(types.SET_LOADING_CLUSTERS, false); commit(types.SET_LOADING_CLUSTERS, false);
......
...@@ -6,7 +6,7 @@ import * as actions from './actions'; ...@@ -6,7 +6,7 @@ import * as actions from './actions';
Vue.use(Vuex); Vue.use(Vuex);
export const createStore = initialState => export const createStore = (initialState) =>
new Vuex.Store({ new Vuex.Store({
actions, actions,
mutations, mutations,
......
...@@ -3,7 +3,7 @@ import Vuex from 'vuex'; ...@@ -3,7 +3,7 @@ import Vuex from 'vuex';
import createStore from './store'; import createStore from './store';
import App from './components/app.vue'; import App from './components/app.vue';
export default initialData => { export default (initialData) => {
const el = document.getElementById('js-code-navigation'); const el = document.getElementById('js-code-navigation');
if (!el) return null; if (!el) return null;
......
...@@ -34,7 +34,7 @@ export default { ...@@ -34,7 +34,7 @@ export default {
}, },
showBlobInteractionZones({ state }, path) { showBlobInteractionZones({ state }, path) {
if (state.data && state.data[path]) { if (state.data && state.data[path]) {
Object.values(state.data[path]).forEach(d => addInteractionClass(path, d)); Object.values(state.data[path]).forEach((d) => addInteractionClass(path, d));
} }
}, },
showDefinition({ commit, state }, { target: el }) { showDefinition({ commit, state }, { target: el }) {
......
export const cachedData = new Map(); export const cachedData = new Map();
export const getCurrentHoverElement = () => cachedData.get('current'); export const getCurrentHoverElement = () => cachedData.get('current');
export const setCurrentHoverElement = el => cachedData.set('current', el); export const setCurrentHoverElement = (el) => cachedData.set('current', el);
export const addInteractionClass = (path, d) => { export const addInteractionClass = (path, d) => {
const lineNumber = d.start_line + 1; const lineNumber = d.start_line + 1;
...@@ -10,7 +10,7 @@ export const addInteractionClass = (path, d) => { ...@@ -10,7 +10,7 @@ export const addInteractionClass = (path, d) => {
.querySelectorAll(`.blob-content #LC${lineNumber}, .line_content:not(.old) #LC${lineNumber}`); .querySelectorAll(`.blob-content #LC${lineNumber}, .line_content:not(.old) #LC${lineNumber}`);
if (!lines?.length) return; if (!lines?.length) return;
lines.forEach(line => { lines.forEach((line) => {
let charCount = 0; let charCount = 0;
const el = [...line.childNodes].find(({ textContent }) => { const el = [...line.childNodes].find(({ textContent }) => {
if (charCount === d.start_char) return true; if (charCount === d.start_char) return true;
......
...@@ -28,7 +28,7 @@ export default class ImageFile { ...@@ -28,7 +28,7 @@ export default class ImageFile {
initViewModes() { initViewModes() {
const viewMode = viewModes[0]; const viewMode = viewModes[0];
$('.view-modes', this.file).removeClass('gl-display-none'); $('.view-modes', this.file).removeClass('gl-display-none');
$('.view-modes-menu', this.file).on('click', 'li', event => { $('.view-modes-menu', this.file).on('click', 'li', (event) => {
if (!$(event.currentTarget).hasClass('active')) { if (!$(event.currentTarget).hasClass('active')) {
return this.activateViewMode(event.currentTarget.className); return this.activateViewMode(event.currentTarget.className);
} }
......
...@@ -21,7 +21,7 @@ export default () => { ...@@ -21,7 +21,7 @@ export default () => {
if (pipelineTableViewEl) { if (pipelineTableViewEl) {
// Update MR and Commits tabs // Update MR and Commits tabs
pipelineTableViewEl.addEventListener('update-pipelines-count', event => { pipelineTableViewEl.addEventListener('update-pipelines-count', (event) => {
if ( if (
event.detail.pipelines && event.detail.pipelines &&
event.detail.pipelines.count && event.detail.pipelines.count &&
......
...@@ -50,7 +50,7 @@ export function createContent(mergeRequests) { ...@@ -50,7 +50,7 @@ export function createContent(mergeRequests) {
if (mergeRequests.length === 0) { if (mergeRequests.length === 0) {
$content.text(s__('Commits|No related merge requests found')); $content.text(s__('Commits|No related merge requests found'));
} else { } else {
mergeRequests.forEach(mergeRequest => { mergeRequests.forEach((mergeRequest) => {
const $header = createHeader($content.children().length, mergeRequests.length); const $header = createHeader($content.children().length, mergeRequests.length);
const $item = createItem(mergeRequest); const $item = createItem(mergeRequest);
$content.append($header); $content.append($header);
...@@ -66,7 +66,7 @@ export function fetchCommitMergeRequests() { ...@@ -66,7 +66,7 @@ export function fetchCommitMergeRequests() {
axios axios
.get($container.data('projectCommitPath')) .get($container.data('projectCommitPath'))
.then(response => { .then((response) => {
const $content = createContent(response.data); const $content = createContent(response.data);
$container.html($content); $container.html($content);
......
...@@ -27,7 +27,7 @@ export function refreshUserMergeRequestCounts() { ...@@ -27,7 +27,7 @@ export function refreshUserMergeRequestCounts() {
updateUserMergeRequestCounts(count); updateUserMergeRequestCounts(count);
broadcastCount(count); broadcastCount(count);
}) })
.catch(ex => { .catch((ex) => {
console.error(ex); // eslint-disable-line no-console console.error(ex); // eslint-disable-line no-console
}); });
} }
...@@ -59,7 +59,7 @@ export function openUserCountsBroadcast() { ...@@ -59,7 +59,7 @@ export function openUserCountsBroadcast() {
const currentUserId = typeof gon !== 'undefined' && gon && gon.current_user_id; const currentUserId = typeof gon !== 'undefined' && gon && gon.current_user_id;
if (currentUserId) { if (currentUserId) {
channel = new BroadcastChannel(`mr_count_channel_${currentUserId}`); channel = new BroadcastChannel(`mr_count_channel_${currentUserId}`);
channel.onmessage = ev => { channel.onmessage = (ev) => {
updateUserMergeRequestCounts(ev.data); updateUserMergeRequestCounts(ev.data);
}; };
} }
......
...@@ -63,7 +63,7 @@ export default function initCompareAutocomplete(limitTo = null, clickHandler = ( ...@@ -63,7 +63,7 @@ export default function initCompareAutocomplete(limitTo = null, clickHandler = (
}, },
clicked: () => clickHandler($dropdown), clicked: () => clickHandler($dropdown),
}); });
$filterInput.on('keyup', e => { $filterInput.on('keyup', (e) => {
const keyCode = e.keyCode || e.which; const keyCode = e.keyCode || e.which;
if (keyCode !== 13) return; if (keyCode !== 13) return;
const text = $filterInput.val(); const text = $filterInput.val();
...@@ -72,7 +72,7 @@ export default function initCompareAutocomplete(limitTo = null, clickHandler = ( ...@@ -72,7 +72,7 @@ export default function initCompareAutocomplete(limitTo = null, clickHandler = (
$dropdownContainer.removeClass('open'); $dropdownContainer.removeClass('open');
}); });
$dropdownContainer.on('click', '.dropdown-content a', e => { $dropdownContainer.on('click', '.dropdown-content a', (e) => {
$dropdown.prop('title', e.target.text.replace(/_+?/g, '-')); $dropdown.prop('title', e.target.text.replace(/_+?/g, '-'));
if ($dropdown.hasClass('has-tooltip')) { if ($dropdown.hasClass('has-tooltip')) {
fixTitle($dropdown); fixTitle($dropdown);
......
...@@ -61,7 +61,7 @@ export default { ...@@ -61,7 +61,7 @@ export default {
} }
}, },
normalizeProjectData(data) { normalizeProjectData(data) {
return data.map(p => ({ return data.map((p) => ({
id: p.id, id: p.id,
name: p.name_with_namespace, name: p.name_with_namespace,
pathWithNamespace: p.path_with_namespace, pathWithNamespace: p.path_with_namespace,
...@@ -78,7 +78,7 @@ export default { ...@@ -78,7 +78,7 @@ export default {
this.projects = this.normalizeProjectData(data); this.projects = this.normalizeProjectData(data);
this.selectProject(this.projects[0]); this.selectProject(this.projects[0]);
}) })
.catch(e => { .catch((e) => {
createFlash(__('Error fetching forked projects. Please try again.')); createFlash(__('Error fetching forked projects. Please try again.'));
throw e; throw e;
}); });
......
...@@ -47,7 +47,7 @@ function getModal($btn) { ...@@ -47,7 +47,7 @@ function getModal($btn) {
} }
export default function initConfirmDangerModal() { export default function initConfirmDangerModal() {
$(document).on('click', '.js-confirm-danger', e => { $(document).on('click', '.js-confirm-danger', (e) => {
const $btn = $(e.target); const $btn = $(e.target);
const checkFieldName = $btn.data('checkFieldName'); const checkFieldName = $btn.data('checkFieldName');
const checkFieldCompareValue = $btn.data('checkCompareValue'); const checkFieldCompareValue = $btn.data('checkCompareValue');
......
import Vue from 'vue'; import Vue from 'vue';
import ConfirmModal from '~/vue_shared/components/confirm_modal.vue'; import ConfirmModal from '~/vue_shared/components/confirm_modal.vue';
const mountConfirmModal = optionalProps => const mountConfirmModal = (optionalProps) =>
new Vue({ new Vue({
render(h) { render(h) {
return h(ConfirmModal, { return h(ConfirmModal, {
......
...@@ -39,7 +39,7 @@ export default { ...@@ -39,7 +39,7 @@ export default {
...mapGetters(['showChart', 'parsedData']), ...mapGetters(['showChart', 'parsedData']),
masterChartData() { masterChartData() {
const data = {}; const data = {};
this.xAxisRange.forEach(date => { this.xAxisRange.forEach((date) => {
data[date] = this.parsedData.total[date] || 0; data[date] = this.parsedData.total[date] || 0;
}); });
return [ return [
...@@ -67,7 +67,7 @@ export default { ...@@ -67,7 +67,7 @@ export default {
const maxNumberOfIndividualContributorsCharts = 100; const maxNumberOfIndividualContributorsCharts = 100;
return Object.keys(this.parsedData.byAuthorEmail) return Object.keys(this.parsedData.byAuthorEmail)
.map(email => { .map((email) => {
const author = this.parsedData.byAuthorEmail[email]; const author = this.parsedData.byAuthorEmail[email];
return { return {
name: author.name, name: author.name,
...@@ -76,7 +76,7 @@ export default { ...@@ -76,7 +76,7 @@ export default {
dates: [ dates: [
{ {
name: __('Commits'), name: __('Commits'),
data: this.xAxisRange.map(date => [date, author.dates[date] || 0]), data: this.xAxisRange.map((date) => [date, author.dates[date] || 0]),
}, },
], ],
}; };
...@@ -101,7 +101,7 @@ export default { ...@@ -101,7 +101,7 @@ export default {
}, },
individualChartYAxisMax() { individualChartYAxisMax() {
return this.individualChartsData.reduce((acc, item) => { return this.individualChartsData.reduce((acc, item) => {
const values = item.dates[0].data.map(value => value[1]); const values = item.dates[0].data.map((value) => value[1]);
return Math.max(acc, ...values); return Math.max(acc, ...values);
}, 0); }, 0);
}, },
...@@ -150,7 +150,7 @@ export default { ...@@ -150,7 +150,7 @@ export default {
}, },
setSvg(name) { setSvg(name) {
return getSvgIconPathContent(name) return getSvgIconPathContent(name)
.then(path => { .then((path) => {
if (path) { if (path) {
this.$set(this.svgs, name, `path://${path}`); this.$set(this.svgs, name, `path://${path}`);
} }
...@@ -177,7 +177,7 @@ export default { ...@@ -177,7 +177,7 @@ export default {
this.individualCharts.push(chart); this.individualCharts.push(chart);
}, },
setIndividualChartsZoom(options) { setIndividualChartsZoom(options) {
this.charts.forEach(chart => this.charts.forEach((chart) =>
chart.setOption( chart.setOption(
{ {
dataZoom: { dataZoom: {
......
...@@ -8,8 +8,8 @@ export const fetchChartData = ({ commit }, endpoint) => { ...@@ -8,8 +8,8 @@ export const fetchChartData = ({ commit }, endpoint) => {
return service return service
.fetchChartData(endpoint) .fetchChartData(endpoint)
.then(res => res.data) .then((res) => res.data)
.then(data => { .then((data) => {
commit(types.SET_CHART_DATA, data); commit(types.SET_CHART_DATA, data);
commit(types.SET_LOADING_STATE, false); commit(types.SET_LOADING_STATE, false);
}) })
......
export const showChart = state => Boolean(!state.loading && state.chartData); export const showChart = (state) => Boolean(!state.loading && state.chartData);
export const parsedData = state => { export const parsedData = (state) => {
const byAuthorEmail = {}; const byAuthorEmail = {};
const total = {}; const total = {};
......
...@@ -9,7 +9,7 @@ import { getMonthNames } from '~/lib/utils/datetime_utility'; ...@@ -9,7 +9,7 @@ import { getMonthNames } from '~/lib/utils/datetime_utility';
* xAxisLabelFormatter('02-12-2019') will return 'Feb' * xAxisLabelFormatter('02-12-2019') will return 'Feb'
* xAxisLabelFormatter('07-12-2019') will return 'Jul' * xAxisLabelFormatter('07-12-2019') will return 'Jul'
*/ */
export const xAxisLabelFormatter = val => { export const xAxisLabelFormatter = (val) => {
const date = new Date(val); const date = new Date(val);
const month = date.getUTCMonth(); const month = date.getUTCMonth();
const year = date.getUTCFullYear(); const year = date.getUTCFullYear();
...@@ -21,7 +21,7 @@ export const xAxisLabelFormatter = val => { ...@@ -21,7 +21,7 @@ export const xAxisLabelFormatter = val => {
* @param {Date} * @param {Date}
* @returns {String} - formatted value * @returns {String} - formatted value
*/ */
export const dateFormatter = date => { export const dateFormatter = (date) => {
const year = date.getUTCFullYear(); const year = date.getUTCFullYear();
const month = date.getUTCMonth(); const month = date.getUTCMonth();
const day = date.getUTCDate(); const day = date.getUTCDate();
......
...@@ -6,9 +6,9 @@ import DropdownSearchInput from '~/vue_shared/components/dropdown/dropdown_searc ...@@ -6,9 +6,9 @@ import DropdownSearchInput from '~/vue_shared/components/dropdown/dropdown_searc
import DropdownHiddenInput from '~/vue_shared/components/dropdown/dropdown_hidden_input.vue'; import DropdownHiddenInput from '~/vue_shared/components/dropdown/dropdown_hidden_input.vue';
import DropdownButton from '~/vue_shared/components/dropdown/dropdown_button.vue'; import DropdownButton from '~/vue_shared/components/dropdown/dropdown_button.vue';
const toArray = value => (isNil(value) ? [] : [].concat(value)); const toArray = (value) => (isNil(value) ? [] : [].concat(value));
const itemsProp = (items, prop) => items.map(item => item[prop]); const itemsProp = (items, prop) => items.map((item) => item[prop]);
const defaultSearchFn = (searchQuery, labelProp) => item => const defaultSearchFn = (searchQuery, labelProp) => (item) =>
item[labelProp].toLowerCase().indexOf(searchQuery) > -1; item[labelProp].toLowerCase().indexOf(searchQuery) > -1;
export default { export default {
...@@ -135,7 +135,7 @@ export default { ...@@ -135,7 +135,7 @@ export default {
const valueList = toArray(this.value); const valueList = toArray(this.value);
const items = this.getItemsOrEmptyList(); const items = this.getItemsOrEmptyList();
return items.filter(item => valueList.some(value => item[valueProp] === value)); return items.filter((item) => valueList.some((value) => item[valueProp] === value));
}, },
selectedItemsLabels() { selectedItemsLabels() {
return itemsProp(this.selectedItems, this.labelProperty).join(', '); return itemsProp(this.selectedItems, this.labelProperty).join(', ');
......
...@@ -6,7 +6,7 @@ import createStore from './store'; ...@@ -6,7 +6,7 @@ import createStore from './store';
Vue.use(Vuex); Vue.use(Vuex);
export default el => { export default (el) => {
const { const {
gitlabManagedClusterHelpPath, gitlabManagedClusterHelpPath,
namespacePerEnvironmentHelpPath, namespacePerEnvironmentHelpPath,
......
...@@ -37,7 +37,7 @@ export const fetchVpcs = ({ region }) => { ...@@ -37,7 +37,7 @@ export const fetchVpcs = ({ region }) => {
.describeVpcs() .describeVpcs()
.promise() .promise()
.then(({ Vpcs: vpcs }) => .then(({ Vpcs: vpcs }) =>
vpcs.map(vpc => ({ vpcs.map((vpc) => ({
value: vpc.VpcId, value: vpc.VpcId,
name: lookupVpcName(vpc), name: lookupVpcName(vpc),
})), })),
......
...@@ -5,7 +5,7 @@ import axios from '~/lib/utils/axios_utils'; ...@@ -5,7 +5,7 @@ import axios from '~/lib/utils/axios_utils';
import { deprecatedCreateFlash as createFlash } from '~/flash'; import { deprecatedCreateFlash as createFlash } from '~/flash';
import { convertObjectPropsToCamelCase } from '~/lib/utils/common_utils'; import { convertObjectPropsToCamelCase } from '~/lib/utils/common_utils';
const getErrorMessage = data => { const getErrorMessage = (data) => {
const errorKey = Object.keys(data)[0]; const errorKey = Object.keys(data)[0];
return data[errorKey][0]; return data[errorKey][0];
...@@ -42,7 +42,7 @@ export const createRole = ({ dispatch, state: { createRolePath } }, payload) => ...@@ -42,7 +42,7 @@ export const createRole = ({ dispatch, state: { createRolePath } }, payload) =>
dispatch('createRoleSuccess', awsData); dispatch('createRoleSuccess', awsData);
}) })
.catch(error => { .catch((error) => {
let message = error; let message = error;
if (error?.response?.data?.message) { if (error?.response?.data?.message) {
message = error.response.data.message; message = error.response.data.message;
......
import { KUBERNETES_VERSIONS } from '../constants'; import { KUBERNETES_VERSIONS } from '../constants';
const kubernetesVersion = KUBERNETES_VERSIONS.find(version => version.default).value; const kubernetesVersion = KUBERNETES_VERSIONS.find((version) => version.default).value;
export default () => ({ export default () => ({
createRolePath: null, createRolePath: null,
......
...@@ -42,13 +42,13 @@ export default { ...@@ -42,13 +42,13 @@ export default {
return []; return [];
} }
return this.items.filter(item => item.name.toLowerCase().indexOf(this.searchQuery) > -1); return this.items.filter((item) => item.name.toLowerCase().indexOf(this.searchQuery) > -1);
}, },
}, },
methods: { methods: {
fetchSuccessHandler() { fetchSuccessHandler() {
if (this.defaultValue) { if (this.defaultValue) {
const itemToSelect = this.items.find(item => item.name === this.defaultValue); const itemToSelect = this.items.find((item) => item.name === this.defaultValue);
if (itemToSelect) { if (itemToSelect) {
this.setItem(itemToSelect.name); this.setItem(itemToSelect.name);
......
...@@ -106,7 +106,7 @@ export default { ...@@ -106,7 +106,7 @@ export default {
...mapActions({ setItem: 'setProject' }), ...mapActions({ setItem: 'setProject' }),
fetchSuccessHandler() { fetchSuccessHandler() {
if (this.defaultValue) { if (this.defaultValue) {
const projectToSelect = this.items.find(item => item.projectId === this.defaultValue); const projectToSelect = this.items.find((item) => item.projectId === this.defaultValue);
if (projectToSelect) { if (projectToSelect) {
this.setItem(projectToSelect); this.setItem(projectToSelect);
......
...@@ -22,7 +22,7 @@ const mountComponent = (entryPoint, component, componentName, extraProps = {}) = ...@@ -22,7 +22,7 @@ const mountComponent = (entryPoint, component, componentName, extraProps = {}) =
components: { components: {
[componentName]: component, [componentName]: component,
}, },
render: createElement => render: (createElement) =>
createElement(componentName, { createElement(componentName, {
props: { props: {
fieldName: hiddenInput.getAttribute('name'), fieldName: hiddenInput.getAttribute('name'),
......
...@@ -6,14 +6,14 @@ const gapiResourceListRequest = ({ resource, params, commit, mutation, payloadKe ...@@ -6,14 +6,14 @@ const gapiResourceListRequest = ({ resource, params, commit, mutation, payloadKe
const request = resource.list(params); const request = resource.list(params);
return request.then( return request.then(
resp => { (resp) => {
const { result } = resp; const { result } = resp;
commit(mutation, result[payloadKey]); commit(mutation, result[payloadKey]);
resolve(); resolve();
}, },
resp => { (resp) => {
reject(resp); reject(resp);
}, },
); );
...@@ -54,14 +54,14 @@ export const validateProjectBilling = ({ dispatch, commit, state }) => ...@@ -54,14 +54,14 @@ export const validateProjectBilling = ({ dispatch, commit, state }) =>
commit(types.SET_MACHINE_TYPE, ''); commit(types.SET_MACHINE_TYPE, '');
return request.then( return request.then(
resp => { (resp) => {
const { billingEnabled } = resp.result; const { billingEnabled } = resp.result;
commit(types.SET_PROJECT_BILLING_STATUS, Boolean(billingEnabled)); commit(types.SET_PROJECT_BILLING_STATUS, Boolean(billingEnabled));
dispatch('setIsValidatingProjectBilling', false); dispatch('setIsValidatingProjectBilling', false);
resolve(); resolve();
}, },
resp => { (resp) => {
dispatch('setIsValidatingProjectBilling', false); dispatch('setIsValidatingProjectBilling', false);
reject(resp); reject(resp);
}, },
......
export const hasProject = state => Boolean(state.selectedProject.projectId); export const hasProject = (state) => Boolean(state.selectedProject.projectId);
export const hasZone = state => Boolean(state.selectedZone); export const hasZone = (state) => Boolean(state.selectedZone);
export const hasMachineType = state => Boolean(state.selectedMachineType); export const hasMachineType = (state) => Boolean(state.selectedMachineType);
export const hasValidData = (state, getters) => export const hasValidData = (state, getters) =>
Boolean(state.projectHasBillingEnabled) && getters.hasZone && getters.hasMachineType; Boolean(state.projectHasBillingEnabled) && getters.hasZone && getters.hasMachineType;
...@@ -12,7 +12,7 @@ const setDisabled = (el, isDisabled) => { ...@@ -12,7 +12,7 @@ const setDisabled = (el, isDisabled) => {
} }
}; };
const setState = glManagedCheckbox => { const setState = (glManagedCheckbox) => {
const glManaged = document.querySelector('.js-namespace-prefixed'); const glManaged = document.querySelector('.js-namespace-prefixed');
const selfManaged = document.querySelector('.js-namespace'); const selfManaged = document.querySelector('.js-namespace');
......
...@@ -4,11 +4,11 @@ import PersistentUserCallout from '~/persistent_user_callout'; ...@@ -4,11 +4,11 @@ import PersistentUserCallout from '~/persistent_user_callout';
const newClusterViews = [':clusters:new', ':clusters:create_gcp', ':clusters:create_user']; const newClusterViews = [':clusters:new', ':clusters:create_gcp', ':clusters:create_user'];
const isProjectLevelCluster = page => page.startsWith('project:clusters'); const isProjectLevelCluster = (page) => page.startsWith('project:clusters');
export default document => { export default (document) => {
const { page } = document.body.dataset; const { page } = document.body.dataset;
const isNewClusterView = newClusterViews.some(view => page.endsWith(view)); const isNewClusterView = newClusterViews.some((view) => page.endsWith(view));
if (!isNewClusterView) { if (!isNewClusterView) {
return; return;
......
import * as types from './mutation_types'; import * as types from './mutation_types';
export default fetchItems => ({ export default (fetchItems) => ({
requestItems: ({ commit }) => commit(types.REQUEST_ITEMS), requestItems: ({ commit }) => commit(types.REQUEST_ITEMS),
receiveItemsSuccess: ({ commit }, payload) => commit(types.RECEIVE_ITEMS_SUCCESS, payload), receiveItemsSuccess: ({ commit }, payload) => commit(types.RECEIVE_ITEMS_SUCCESS, payload),
receiveItemsError: ({ commit }, payload) => commit(types.RECEIVE_ITEMS_ERROR, payload), receiveItemsError: ({ commit }, payload) => commit(types.RECEIVE_ITEMS_ERROR, payload),
...@@ -8,7 +8,7 @@ export default fetchItems => ({ ...@@ -8,7 +8,7 @@ export default fetchItems => ({
dispatch('requestItems'); dispatch('requestItems');
return fetchItems(payload) return fetchItems(payload)
.then(items => dispatch('receiveItemsSuccess', { items })) .then((items) => dispatch('receiveItemsSuccess', { items }))
.catch(error => dispatch('receiveItemsError', { error })); .catch((error) => dispatch('receiveItemsError', { error }));
}, },
}); });
...@@ -47,7 +47,7 @@ export default class CreateItemDropdown { ...@@ -47,7 +47,7 @@ export default class CreateItemDropdown {
return escape(item.id); return escape(item.id);
}, },
onFilter: this.toggleCreateNewButton.bind(this), onFilter: this.toggleCreateNewButton.bind(this),
clicked: options => { clicked: (options) => {
options.e.preventDefault(); options.e.preventDefault();
this.onSelect(); this.onSelect();
}, },
...@@ -79,7 +79,7 @@ export default class CreateItemDropdown { ...@@ -79,7 +79,7 @@ export default class CreateItemDropdown {
this.getDataOption(term, (data = []) => { this.getDataOption(term, (data = []) => {
// Ensure the selected item isn't already in the data to avoid duplicates // Ensure the selected item isn't already in the data to avoid duplicates
const alreadyHasSelectedItem = const alreadyHasSelectedItem =
this.selectedItem && data.some(item => item.id === this.selectedItem.id); this.selectedItem && data.some((item) => item.id === this.selectedItem.id);
let uniqueData = data; let uniqueData = data;
if (!alreadyHasSelectedItem) { if (!alreadyHasSelectedItem) {
......
...@@ -56,7 +56,7 @@ export default class CreateLabelDropdown { ...@@ -56,7 +56,7 @@ export default class CreateLabelDropdown {
this.$dropdownBack.on('click', this.resetForm.bind(this)); this.$dropdownBack.on('click', this.resetForm.bind(this));
this.$cancelButton.on('click', e => { this.$cancelButton.on('click', (e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
...@@ -105,7 +105,7 @@ export default class CreateLabelDropdown { ...@@ -105,7 +105,7 @@ export default class CreateLabelDropdown {
title: this.$newLabelField.val(), title: this.$newLabelField.val(),
color: this.$newColorField.val(), color: this.$newColorField.val(),
}, },
label => { (label) => {
this.$newLabelCreateButton.enable(); this.$newLabelCreateButton.enable();
if (label.message) { if (label.message) {
...@@ -115,7 +115,7 @@ export default class CreateLabelDropdown { ...@@ -115,7 +115,7 @@ export default class CreateLabelDropdown {
errors = label.message; errors = label.message;
} else { } else {
errors = Object.keys(label.message) errors = Object.keys(label.message)
.map(key => `${humanize(key)} ${label.message[key].join(', ')}`) .map((key) => `${humanize(key)} ${label.message[key].join(', ')}`)
.join('<br/>'); .join('<br/>');
} }
......
...@@ -191,7 +191,7 @@ export default class CreateMergeRequestDropdown { ...@@ -191,7 +191,7 @@ export default class CreateMergeRequestDropdown {
static findByValue(objects, ref, returnFirstMatch = false) { static findByValue(objects, ref, returnFirstMatch = false) {
if (!objects || !objects.length) return false; if (!objects || !objects.length) return false;
if (objects.indexOf(ref) > -1) return ref; if (objects.indexOf(ref) > -1) return ref;
if (returnFirstMatch) return objects.find(item => new RegExp(`^${ref}`).test(item)); if (returnFirstMatch) return objects.find((item) => new RegExp(`^${ref}`).test(item));
return false; return false;
} }
...@@ -356,7 +356,7 @@ export default class CreateMergeRequestDropdown { ...@@ -356,7 +356,7 @@ export default class CreateMergeRequestDropdown {
event.preventDefault(); event.preventDefault();
if (isConfidentialIssue() && !event.target.classList.contains('js-create-target')) { if (isConfidentialIssue() && !event.target.classList.contains('js-create-target')) {
this.droplab.hooks.forEach(hook => hook.list.toggle()); this.droplab.hooks.forEach((hook) => hook.list.toggle());
return; return;
} }
...@@ -404,8 +404,8 @@ export default class CreateMergeRequestDropdown { ...@@ -404,8 +404,8 @@ export default class CreateMergeRequestDropdown {
const inputClasses = ['gl-field-error-outline', 'gl-field-success-outline']; const inputClasses = ['gl-field-error-outline', 'gl-field-success-outline'];
const messageClasses = ['text-muted', 'text-danger', 'text-success']; const messageClasses = ['text-muted', 'text-danger', 'text-success'];
inputClasses.forEach(cssClass => input.classList.remove(cssClass)); inputClasses.forEach((cssClass) => input.classList.remove(cssClass));
messageClasses.forEach(cssClass => message.classList.remove(cssClass)); messageClasses.forEach((cssClass) => message.classList.remove(cssClass));
message.style.display = 'none'; message.style.display = 'none';
} }
......
...@@ -22,7 +22,7 @@ let cancelTokenSource; ...@@ -22,7 +22,7 @@ let cancelTokenSource;
function backOffRequest(makeRequestCallback) { function backOffRequest(makeRequestCallback) {
return backOff((next, stop) => { return backOff((next, stop) => {
makeRequestCallback() makeRequestCallback()
.then(resp => { .then((resp) => {
if (resp.status === statusCodes.OK) { if (resp.status === statusCodes.OK) {
stop(resp); stop(resp);
} else { } else {
...@@ -32,7 +32,7 @@ function backOffRequest(makeRequestCallback) { ...@@ -32,7 +32,7 @@ function backOffRequest(makeRequestCallback) {
// If the request is cancelled by axios // If the request is cancelled by axios
// then consider it as noop so that its not // then consider it as noop so that its not
// caught by subsequent catches // caught by subsequent catches
.catch(thrown => (axios.isCancel(thrown) ? undefined : stop(thrown))); .catch((thrown) => (axios.isCancel(thrown) ? undefined : stop(thrown)));
}, VALIDATION_REQUEST_TIMEOUT); }, VALIDATION_REQUEST_TIMEOUT);
} }
...@@ -144,7 +144,7 @@ export default { ...@@ -144,7 +144,7 @@ export default {
// as well. // as well.
cancelTokenSource = axiosCancelToken.source(); cancelTokenSource = axiosCancelToken.source();
this.requestValidation(this.query, cancelTokenSource.token) this.requestValidation(this.query, cancelTokenSource.token)
.then(res => { .then((res) => {
const response = res.data; const response = res.data;
const { valid, error } = response.query; const { valid, error } = response.query;
if (response.success) { if (response.success) {
......
...@@ -4,9 +4,9 @@ export const queryTypes = { ...@@ -4,9 +4,9 @@ export const queryTypes = {
system: 'system', system: 'system',
}; };
export const formDataValidator = val => { export const formDataValidator = (val) => {
const fieldNames = Object.keys(val); const fieldNames = Object.keys(val);
const requiredFields = ['title', 'query', 'yLabel', 'unit', 'group', 'legend']; const requiredFields = ['title', 'query', 'yLabel', 'unit', 'group', 'legend'];
return requiredFields.every(name => fieldNames.includes(name)); return requiredFields.every((name) => fieldNames.includes(name));
}; };
...@@ -78,7 +78,7 @@ export default () => { ...@@ -78,7 +78,7 @@ export default () => {
$dropdown $dropdown
.find('li a') .find('li a')
.off('click') .off('click')
.on('click', e => { .on('click', (e) => {
e.preventDefault(); e.preventDefault();
const $target = $(e.currentTarget); const $target = $(e.currentTarget);
this.startDate = $target.data('value'); this.startDate = $target.data('value');
...@@ -94,7 +94,7 @@ export default () => { ...@@ -94,7 +94,7 @@ export default () => {
this.service this.service
.fetchCycleAnalyticsData(fetchOptions) .fetchCycleAnalyticsData(fetchOptions)
.then(response => { .then((response) => {
this.store.setCycleAnalyticsData(response); this.store.setCycleAnalyticsData(response);
this.selectDefaultStage(); this.selectDefaultStage();
this.initDropdown(); this.initDropdown();
...@@ -128,7 +128,7 @@ export default () => { ...@@ -128,7 +128,7 @@ export default () => {
startDate: this.startDate, startDate: this.startDate,
projectIds: this.selectedProjectIds, projectIds: this.selectedProjectIds,
}) })
.then(response => { .then((response) => {
this.isEmptyStage = !response.events.length; this.isEmptyStage = !response.events.length;
this.store.setStageEvents(response.events, stage); this.store.setStageEvents(response.events, stage);
this.isLoadingStage = false; this.isLoadingStage = false;
......
...@@ -17,7 +17,7 @@ export default class CycleAnalyticsService { ...@@ -17,7 +17,7 @@ export default class CycleAnalyticsService {
'cycle_analytics[project_ids]': projectIds, 'cycle_analytics[project_ids]': projectIds,
}, },
}) })
.then(x => x.data); .then((x) => x.data);
} }
fetchStageData(options) { fetchStageData(options) {
...@@ -30,6 +30,6 @@ export default class CycleAnalyticsService { ...@@ -30,6 +30,6 @@ export default class CycleAnalyticsService {
'cycle_analytics[project_ids]': projectIds, 'cycle_analytics[project_ids]': projectIds,
}, },
}) })
.then(x => x.data); .then((x) => x.data);
} }
} }
...@@ -42,11 +42,11 @@ export default { ...@@ -42,11 +42,11 @@ export default {
newData.stages = data.stats || []; newData.stages = data.stats || [];
newData.summary = data.summary || []; newData.summary = data.summary || [];
newData.summary.forEach(item => { newData.summary.forEach((item) => {
item.value = item.value || '-'; item.value = item.value || '-';
}); });
newData.stages.forEach(item => { newData.stages.forEach((item) => {
const stageSlug = dasherize(item.name.toLowerCase()); const stageSlug = dasherize(item.name.toLowerCase());
item.active = false; item.active = false;
item.isUserAllowed = data.permissions[stageSlug]; item.isUserAllowed = data.permissions[stageSlug];
...@@ -64,7 +64,7 @@ export default { ...@@ -64,7 +64,7 @@ export default {
this.state.hasError = state; this.state.hasError = state;
}, },
deactivateAllStages() { deactivateAllStages() {
this.state.stages.forEach(stage => { this.state.stages.forEach((stage) => {
stage.active = false; stage.active = false;
}); });
}, },
...@@ -78,7 +78,7 @@ export default { ...@@ -78,7 +78,7 @@ export default {
decorateEvents(events, stage) { decorateEvents(events, stage) {
const newEvents = []; const newEvents = [];
events.forEach(item => { events.forEach((item) => {
if (!item) return; if (!item) return;
const eventItem = { ...DEFAULT_EVENT_OBJECTS[stage.slug], ...item }; const eventItem = { ...DEFAULT_EVENT_OBJECTS[stage.slug], ...item };
...@@ -107,6 +107,6 @@ export default { ...@@ -107,6 +107,6 @@ export default {
return newEvents; return newEvents;
}, },
currentActiveStage() { currentActiveStage() {
return this.state.stages.find(stage => stage.active); return this.state.stages.find((stage) => stage.active);
}, },
}; };
...@@ -28,7 +28,7 @@ export const addFreezePeriod = ({ state, dispatch, commit }) => { ...@@ -28,7 +28,7 @@ export const addFreezePeriod = ({ state, dispatch, commit }) => {
commit(types.RESET_MODAL); commit(types.RESET_MODAL);
dispatch('fetchFreezePeriods'); dispatch('fetchFreezePeriods');
}) })
.catch(error => { .catch((error) => {
createFlash(__('Error: Unable to create deploy freeze')); createFlash(__('Error: Unable to create deploy freeze'));
dispatch('receiveAddFreezePeriodError', error); dispatch('receiveAddFreezePeriodError', error);
}); });
......
...@@ -6,7 +6,7 @@ import createState from './state'; ...@@ -6,7 +6,7 @@ import createState from './state';
Vue.use(Vuex); Vue.use(Vuex);
export default initialState => export default (initialState) =>
new Vuex.Store({ new Vuex.Store({
actions, actions,
mutations, mutations,
......
...@@ -4,7 +4,7 @@ import * as types from './mutation_types'; ...@@ -4,7 +4,7 @@ import * as types from './mutation_types';
const formatTimezoneName = (freezePeriod, timezoneList) => const formatTimezoneName = (freezePeriod, timezoneList) =>
convertObjectPropsToCamelCase({ convertObjectPropsToCamelCase({
...freezePeriod, ...freezePeriod,
cron_timezone: timezoneList.find(tz => tz.identifier === freezePeriod.cron_timezone)?.name, cron_timezone: timezoneList.find((tz) => tz.identifier === freezePeriod.cron_timezone)?.name,
}); });
export default { export default {
...@@ -14,7 +14,7 @@ export default { ...@@ -14,7 +14,7 @@ export default {
[types.RECEIVE_FREEZE_PERIODS_SUCCESS](state, freezePeriods) { [types.RECEIVE_FREEZE_PERIODS_SUCCESS](state, freezePeriods) {
state.isLoading = false; state.isLoading = false;
state.freezePeriods = freezePeriods.map(freezePeriod => state.freezePeriods = freezePeriods.map((freezePeriod) =>
formatTimezoneName(freezePeriod, state.timezoneData), formatTimezoneName(freezePeriod, state.timezoneData),
); );
}, },
......
...@@ -39,7 +39,7 @@ export default { ...@@ -39,7 +39,7 @@ export default {
}, },
computed: { computed: {
tabs() { tabs() {
return Object.keys(this.$options.scopes).map(scope => { return Object.keys(this.$options.scopes).map((scope) => {
const count = Array.isArray(this.keys[scope]) ? this.keys[scope].length : null; const count = Array.isArray(this.keys[scope]) ? this.keys[scope].length : null;
return { return {
...@@ -81,7 +81,7 @@ export default { ...@@ -81,7 +81,7 @@ export default {
return this.service return this.service
.getKeys() .getKeys()
.then(data => { .then((data) => {
this.isLoading = false; this.isLoading = false;
this.store.keys = data; this.store.keys = data;
}) })
......
...@@ -48,7 +48,7 @@ export default { ...@@ -48,7 +48,7 @@ export default {
if (this.projectId !== null) { if (this.projectId !== null) {
const indexOfCurrentProject = projects.findIndex( const indexOfCurrentProject = projects.findIndex(
project => (project) =>
project && project &&
project.project && project.project &&
project.project.id && project.project.id &&
......
...@@ -6,14 +6,14 @@ export default class DeployKeysService { ...@@ -6,14 +6,14 @@ export default class DeployKeysService {
} }
getKeys() { getKeys() {
return axios.get(this.endpoint).then(response => response.data); return axios.get(this.endpoint).then((response) => response.data);
} }
enableKey(id) { enableKey(id) {
return axios.put(`${this.endpoint}/${id}/enable`).then(response => response.data); return axios.put(`${this.endpoint}/${id}/enable`).then((response) => response.data);
} }
disableKey(id) { disableKey(id) {
return axios.put(`${this.endpoint}/${id}/disable`).then(response => response.data); return axios.put(`${this.endpoint}/${id}/disable`).then((response) => response.data);
} }
} }
...@@ -4,6 +4,6 @@ export default class DeployKeysStore { ...@@ -4,6 +4,6 @@ export default class DeployKeysStore {
} }
isEnabled(id) { isEnabled(id) {
return this.keys.enabled_keys.some(key => key.id === id); return this.keys.enabled_keys.some((key) => key.id === id);
} }
} }
...@@ -68,7 +68,7 @@ export class GitLabDropdown { ...@@ -68,7 +68,7 @@ export class GitLabDropdown {
this.remote = new GitLabDropdownRemote(this.options.data, { this.remote = new GitLabDropdownRemote(this.options.data, {
dataType: this.options.dataType, dataType: this.options.dataType,
beforeSend: this.toggleLoading.bind(this), beforeSend: this.toggleLoading.bind(this),
success: data => { success: (data) => {
this.fullData = data; this.fullData = data;
this.parseData(this.fullData); this.parseData(this.fullData);
this.focusTextInput(); this.focusTextInput();
...@@ -113,7 +113,7 @@ export class GitLabDropdown { ...@@ -113,7 +113,7 @@ export class GitLabDropdown {
return $(selector, this.dropdown); return $(selector, this.dropdown);
}, },
data: () => this.fullData, data: () => this.fullData,
callback: data => { callback: (data) => {
this.parseData(data); this.parseData(data);
if (this.filterInput.val() !== '') { if (this.filterInput.val() !== '') {
selector = SELECTABLE_CLASSES; selector = SELECTABLE_CLASSES;
...@@ -135,13 +135,13 @@ export class GitLabDropdown { ...@@ -135,13 +135,13 @@ export class GitLabDropdown {
this.dropdown.on('hidden.bs.dropdown', this.hidden); this.dropdown.on('hidden.bs.dropdown', this.hidden);
$(this.el).on('update.label', this.updateLabel); $(this.el).on('update.label', this.updateLabel);
this.dropdown.on('click', '.dropdown-menu, .dropdown-menu-close', this.shouldPropagate); this.dropdown.on('click', '.dropdown-menu, .dropdown-menu-close', this.shouldPropagate);
this.dropdown.on('keyup', e => { this.dropdown.on('keyup', (e) => {
// Escape key // Escape key
if (e.which === 27) { if (e.which === 27) {
return $('.dropdown-menu-close', this.dropdown).trigger('click'); return $('.dropdown-menu-close', this.dropdown).trigger('click');
} }
}); });
this.dropdown.on('blur', 'a', e => { this.dropdown.on('blur', 'a', (e) => {
let $dropdownMenu; let $dropdownMenu;
let $relatedTarget; let $relatedTarget;
if (e.relatedTarget != null) { if (e.relatedTarget != null) {
...@@ -153,7 +153,7 @@ export class GitLabDropdown { ...@@ -153,7 +153,7 @@ export class GitLabDropdown {
} }
}); });
if (this.dropdown.find('.dropdown-toggle-page').length) { if (this.dropdown.find('.dropdown-toggle-page').length) {
this.dropdown.find('.dropdown-toggle-page, .dropdown-menu-back').on('click', e => { this.dropdown.find('.dropdown-toggle-page, .dropdown-menu-back').on('click', (e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
return this.togglePage(); return this.togglePage();
...@@ -164,7 +164,7 @@ export class GitLabDropdown { ...@@ -164,7 +164,7 @@ export class GitLabDropdown {
if (this.dropdown.find('.dropdown-toggle-page').length) { if (this.dropdown.find('.dropdown-toggle-page').length) {
selector = '.dropdown-page-one .dropdown-content a'; selector = '.dropdown-page-one .dropdown-content a';
} }
this.dropdown.on('click', selector, e => { this.dropdown.on('click', selector, (e) => {
const $el = $(e.currentTarget); const $el = $(e.currentTarget);
const selected = self.rowClicked($el); const selected = self.rowClicked($el);
const selectedObj = selected ? selected[0] : null; const selectedObj = selected ? selected[0] : null;
...@@ -221,7 +221,7 @@ export class GitLabDropdown { ...@@ -221,7 +221,7 @@ export class GitLabDropdown {
else if (isObject(data)) { else if (isObject(data)) {
html = []; html = [];
Object.keys(data).forEach(name => { Object.keys(data).forEach((name) => {
groupData = data[name]; groupData = data[name];
html.push( html.push(
this.renderItem( this.renderItem(
...@@ -232,7 +232,7 @@ export class GitLabDropdown { ...@@ -232,7 +232,7 @@ export class GitLabDropdown {
name, name,
), ),
); );
this.renderData(groupData, name).map(item => html.push(item)); this.renderData(groupData, name).map((item) => html.push(item));
}); });
} else { } else {
// Render each row // Render each row
...@@ -271,7 +271,7 @@ export class GitLabDropdown { ...@@ -271,7 +271,7 @@ export class GitLabDropdown {
filteredFullData() { filteredFullData() {
return this.fullData.filter( return this.fullData.filter(
r => (r) =>
typeof r === 'object' && typeof r === 'object' &&
!Object.prototype.hasOwnProperty.call(r, 'beforeDivider') && !Object.prototype.hasOwnProperty.call(r, 'beforeDivider') &&
!Object.prototype.hasOwnProperty.call(r, 'header'), !Object.prototype.hasOwnProperty.call(r, 'header'),
...@@ -389,7 +389,7 @@ export class GitLabDropdown { ...@@ -389,7 +389,7 @@ export class GitLabDropdown {
...this.options, ...this.options,
icon: this.icon, icon: this.icon,
highlight: this.highlight, highlight: this.highlight,
highlightText: text => this.highlightTextMatches(text, this.filterInput.val()), highlightText: (text) => this.highlightTextMatches(text, this.filterInput.val()),
highlightTemplate: this.highlightTemplate.bind(this), highlightTemplate: this.highlightTemplate.bind(this),
parent, parent,
}, },
...@@ -536,7 +536,7 @@ export class GitLabDropdown { ...@@ -536,7 +536,7 @@ export class GitLabDropdown {
} }
if (this.options.multiSelect) { if (this.options.multiSelect) {
Object.keys(selectedObject).forEach(attribute => { Object.keys(selectedObject).forEach((attribute) => {
$input.attr(`data-${attribute}`, selectedObject[attribute]); $input.attr(`data-${attribute}`, selectedObject[attribute]);
}); });
} }
...@@ -577,7 +577,7 @@ export class GitLabDropdown { ...@@ -577,7 +577,7 @@ export class GitLabDropdown {
if (this.dropdown.find('.dropdown-toggle-page').length) { if (this.dropdown.find('.dropdown-toggle-page').length) {
selector = `.dropdown-page-one ${selector}`; selector = `.dropdown-page-one ${selector}`;
} }
return $('body').on('keydown', e => { return $('body').on('keydown', (e) => {
let $listItems; let $listItems;
let PREV_INDEX; let PREV_INDEX;
const currentKeyCode = e.which; const currentKeyCode = e.which;
......
...@@ -18,7 +18,7 @@ export class GitLabDropdownFilter { ...@@ -18,7 +18,7 @@ export class GitLabDropdownFilter {
this.filterInputBlur = (ref = this.options.filterInputBlur) != null ? ref : true; this.filterInputBlur = (ref = this.options.filterInputBlur) != null ? ref : true;
const $inputContainer = this.input.parent(); const $inputContainer = this.input.parent();
const $clearButton = $inputContainer.find('.js-dropdown-input-clear'); const $clearButton = $inputContainer.find('.js-dropdown-input-clear');
$clearButton.on('click', e => { $clearButton.on('click', (e) => {
// Clear click // Clear click
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
...@@ -27,7 +27,7 @@ export class GitLabDropdownFilter { ...@@ -27,7 +27,7 @@ export class GitLabDropdownFilter {
// Key events // Key events
timeout = ''; timeout = '';
this.input this.input
.on('keydown', e => { .on('keydown', (e) => {
const keyCode = e.which; const keyCode = e.which;
if (keyCode === 13 && !options.elIsInput) { if (keyCode === 13 && !options.elIsInput) {
e.preventDefault(); e.preventDefault();
...@@ -46,7 +46,7 @@ export class GitLabDropdownFilter { ...@@ -46,7 +46,7 @@ export class GitLabDropdownFilter {
return (timeout = setTimeout(() => { return (timeout = setTimeout(() => {
$inputContainer.parent().addClass('is-loading'); $inputContainer.parent().addClass('is-loading');
return this.options.query(this.input.val(), data => { return this.options.query(this.input.val(), (data) => {
$inputContainer.parent().removeClass('is-loading'); $inputContainer.parent().removeClass('is-loading');
return this.options.callback(data); return this.options.callback(data);
}); });
...@@ -94,13 +94,13 @@ export class GitLabDropdownFilter { ...@@ -94,13 +94,13 @@ export class GitLabDropdownFilter {
// } // }
else if (isObject(data)) { else if (isObject(data)) {
results = {}; results = {};
Object.keys(data).forEach(key => { Object.keys(data).forEach((key) => {
group = data[key]; group = data[key];
tmp = fuzzaldrinPlus.filter(group, searchText, { tmp = fuzzaldrinPlus.filter(group, searchText, {
key: this.options.keys, key: this.options.keys,
}); });
if (tmp.length) { if (tmp.length) {
results[key] = tmp.map(item => item); results[key] = tmp.map((item) => item);
} }
}); });
} }
......
...@@ -5,7 +5,7 @@ export class GitLabDropdownInput { ...@@ -5,7 +5,7 @@ export class GitLabDropdownInput {
this.fieldName = this.options.fieldName || 'field-name'; this.fieldName = this.options.fieldName || 'field-name';
const $inputContainer = this.input.parent(); const $inputContainer = this.input.parent();
const $clearButton = $inputContainer.find('.js-dropdown-input-clear'); const $clearButton = $inputContainer.find('.js-dropdown-input-clear');
$clearButton.on('click', e => { $clearButton.on('click', (e) => {
// Clear click // Clear click
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
...@@ -13,13 +13,13 @@ export class GitLabDropdownInput { ...@@ -13,13 +13,13 @@ export class GitLabDropdownInput {
}); });
this.input this.input
.on('keydown', e => { .on('keydown', (e) => {
const keyCode = e.which; const keyCode = e.which;
if (keyCode === 13 && !options.elIsInput) { if (keyCode === 13 && !options.elIsInput) {
e.preventDefault(); e.preventDefault();
} }
}) })
.on('input', e => { .on('input', (e) => {
let val = e.currentTarget.value || this.options.inputFieldName; let val = e.currentTarget.value || this.options.inputFieldName;
val = val val = val
.split(' ') .split(' ')
......
...@@ -15,7 +15,7 @@ export class GitLabDropdownRemote { ...@@ -15,7 +15,7 @@ export class GitLabDropdownRemote {
if (this.options.beforeSend) { if (this.options.beforeSend) {
this.options.beforeSend(); this.options.beforeSend();
} }
return this.dataEndpoint('', data => { return this.dataEndpoint('', (data) => {
// Fetch the data by calling the data function // Fetch the data by calling the data function
if (this.options.success) { if (this.options.success) {
this.options.success(data); this.options.success(data);
......
...@@ -171,7 +171,7 @@ export default { ...@@ -171,7 +171,7 @@ export default {
this.$emit('resolve-discussion-error', data.errors[0]); this.$emit('resolve-discussion-error', data.errors[0]);
} }
}) })
.catch(err => { .catch((err) => {
this.$emit('resolve-discussion-error', err); this.$emit('resolve-discussion-error', err);
}) })
.finally(() => { .finally(() => {
......
...@@ -58,7 +58,7 @@ export default { ...@@ -58,7 +58,7 @@ export default {
}, },
computed: { computed: {
discussionStartingNotes() { discussionStartingNotes() {
return this.discussions.map(discussion => ({ return this.discussions.map((discussion) => ({
...discussion.notes[0], ...discussion.notes[0],
index: discussion.index, index: discussion.index,
})); }));
......
...@@ -63,10 +63,10 @@ export default { ...@@ -63,10 +63,10 @@ export default {
return extractParticipants(this.issue.participants.nodes); return extractParticipants(this.issue.participants.nodes);
}, },
resolvedDiscussions() { resolvedDiscussions() {
return this.discussions.filter(discussion => discussion.resolved); return this.discussions.filter((discussion) => discussion.resolved);
}, },
unresolvedDiscussions() { unresolvedDiscussions() {
return this.discussions.filter(discussion => !discussion.resolved); return this.discussions.filter((discussion) => !discussion.resolved);
}, },
resolvedCommentsToggleIcon() { resolvedCommentsToggleIcon() {
return this.resolvedDiscussionsExpanded ? 'chevron-down' : 'chevron-right'; return this.resolvedDiscussionsExpanded ? 'chevron-down' : 'chevron-right';
......
...@@ -95,7 +95,7 @@ export default { ...@@ -95,7 +95,7 @@ export default {
.then(() => { .then(() => {
this.incrementGlobalTodoCount(); this.incrementGlobalTodoCount();
}) })
.catch(err => { .catch((err) => {
this.$emit('error', Error(CREATE_DESIGN_TODO_ERROR)); this.$emit('error', Error(CREATE_DESIGN_TODO_ERROR));
throw err; throw err;
}) })
...@@ -133,7 +133,7 @@ export default { ...@@ -133,7 +133,7 @@ export default {
.then(() => { .then(() => {
this.decrementGlobalTodoCount(); this.decrementGlobalTodoCount();
}) })
.catch(err => { .catch((err) => {
this.$emit('error', Error(DELETE_DESIGN_TODO_ERROR)); this.$emit('error', Error(DELETE_DESIGN_TODO_ERROR));
throw err; throw err;
}) })
......
...@@ -26,7 +26,7 @@ export default { ...@@ -26,7 +26,7 @@ export default {
return this.designs.length; return this.designs.length;
}, },
currentIndex() { currentIndex() {
return this.designs.findIndex(design => design.filename === this.id); return this.designs.findIndex((design) => design.filename === this.id);
}, },
paginationText() { paginationText() {
return sprintf(s__('DesignManagement|%{current_design} of %{designs_count}'), { return sprintf(s__('DesignManagement|%{current_design} of %{designs_count}'), {
......
...@@ -75,7 +75,7 @@ export default { ...@@ -75,7 +75,7 @@ export default {
iid: this.issueIid, iid: this.issueIid,
}; };
}, },
update: data => data.project.issue.userPermissions, update: (data) => data.project.issue.userPermissions,
}, },
}, },
computed: { computed: {
......
...@@ -19,7 +19,7 @@ export default { ...@@ -19,7 +19,7 @@ export default {
if (!this.queryVersion) return 0; if (!this.queryVersion) return 0;
const idx = this.allVersions.findIndex( const idx = this.allVersions.findIndex(
version => this.findVersionId(version.id) === this.queryVersion, (version) => this.findVersionId(version.id) === this.queryVersion,
); );
// if the currentVersionId isn't a valid version (i.e. not in allVersions) // if the currentVersionId isn't a valid version (i.e. not in allVersions)
......
...@@ -19,7 +19,7 @@ const resolvers = { ...@@ -19,7 +19,7 @@ const resolvers = {
updateActiveDiscussion: (_, { id = null, source }, { cache }) => { updateActiveDiscussion: (_, { id = null, source }, { cache }) => {
const sourceData = cache.readQuery({ query: activeDiscussionQuery }); const sourceData = cache.readQuery({ query: activeDiscussionQuery });
const data = produce(sourceData, draftData => { const data = produce(sourceData, (draftData) => {
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
draftData.activeDiscussion = { draftData.activeDiscussion = {
__typename: 'ActiveDiscussion', __typename: 'ActiveDiscussion',
...@@ -74,7 +74,7 @@ const defaultClient = createDefaultClient( ...@@ -74,7 +74,7 @@ const defaultClient = createDefaultClient(
// Should be removed as soon as https://gitlab.com/gitlab-org/gitlab/issues/13495 is resolved // Should be removed as soon as https://gitlab.com/gitlab-org/gitlab/issues/13495 is resolved
{ {
cacheConfig: { cacheConfig: {
dataIdFromObject: object => { dataIdFromObject: (object) => {
// eslint-disable-next-line no-underscore-dangle, @gitlab/require-i18n-strings // eslint-disable-next-line no-underscore-dangle, @gitlab/require-i18n-strings
if (object.__typename === 'Design') { if (object.__typename === 'Design') {
return object.id && object.image ? `${object.id}-${object.image}` : uniqueId(); return object.id && object.image ? `${object.id}-${object.image}` : uniqueId();
......
...@@ -17,7 +17,7 @@ export default { ...@@ -17,7 +17,7 @@ export default {
atVersion: this.designsVersion, atVersion: this.designsVersion,
}; };
}, },
update: data => { update: (data) => {
const designNodes = propertyOf(data)([ const designNodes = propertyOf(data)([
'project', 'project',
'issue', 'issue',
......
...@@ -12,7 +12,7 @@ export default { ...@@ -12,7 +12,7 @@ export default {
atVersion: null, atVersion: null,
}; };
}, },
update: data => data.project.issue.designCollection.versions.nodes, update: (data) => data.project.issue.designCollection.versions.nodes,
}, },
}, },
inject: { inject: {
...@@ -28,7 +28,7 @@ export default { ...@@ -28,7 +28,7 @@ export default {
return ( return (
this.$route.query.version && this.$route.query.version &&
this.allVersions && this.allVersions &&
this.allVersions.some(version => version.id.endsWith(this.$route.query.version)) this.allVersions.some((version) => version.id.endsWith(this.$route.query.version))
); );
}, },
designsVersion() { designsVersion() {
......
...@@ -81,7 +81,7 @@ export default { ...@@ -81,7 +81,7 @@ export default {
variables() { variables() {
return this.designVariables; return this.designVariables;
}, },
update: data => extractDesign(data), update: (data) => extractDesign(data),
result(res) { result(res) {
this.onDesignQueryResult(res); this.onDesignQueryResult(res);
}, },
...@@ -139,7 +139,7 @@ export default { ...@@ -139,7 +139,7 @@ export default {
return Boolean(this.annotationCoordinates); return Boolean(this.annotationCoordinates);
}, },
resolvedDiscussions() { resolvedDiscussions() {
return this.discussions.filter(discussion => discussion.resolved); return this.discussions.filter((discussion) => discussion.resolved);
}, },
}, },
watch: { watch: {
...@@ -203,7 +203,7 @@ export default { ...@@ -203,7 +203,7 @@ export default {
update: this.updateImageDiffNoteInStore, update: this.updateImageDiffNoteInStore,
}; };
return this.$apollo.mutate(mutationPayload).catch(e => this.onUpdateImageDiffNoteError(e)); return this.$apollo.mutate(mutationPayload).catch((e) => this.onUpdateImageDiffNoteError(e));
}, },
onDesignQueryResult({ data, loading }) { onDesignQueryResult({ data, loading }) {
// On the initial load with cache-and-network policy data is undefined while loading is true // On the initial load with cache-and-network policy data is undefined while loading is true
......
...@@ -69,7 +69,7 @@ export default { ...@@ -69,7 +69,7 @@ export default {
iid: this.issueIid, iid: this.issueIid,
}; };
}, },
update: data => data.project.issue.userPermissions, update: (data) => data.project.issue.userPermissions,
}, },
}, },
data() { data() {
...@@ -184,7 +184,7 @@ export default { ...@@ -184,7 +184,7 @@ export default {
return this.$apollo return this.$apollo
.mutate(mutationPayload) .mutate(mutationPayload)
.then(res => this.onUploadDesignDone(res)) .then((res) => this.onUploadDesignDone(res))
.catch(() => this.onUploadDesignError()); .catch(() => this.onUploadDesignError());
}, },
afterUploadDesign(store, { data: { designManagementUpload } }) { afterUploadDesign(store, { data: { designManagementUpload } }) {
...@@ -208,7 +208,7 @@ export default { ...@@ -208,7 +208,7 @@ export default {
this.trackUploadDesign(res); this.trackUploadDesign(res);
}, },
trackUploadDesign(res) { trackUploadDesign(res) {
(res?.data?.designManagementUpload?.designs || []).forEach(design => { (res?.data?.designManagementUpload?.designs || []).forEach((design) => {
if (design.event === 'CREATION') { if (design.event === 'CREATION') {
trackDesignCreate(); trackDesignCreate();
} else if (design.event === 'MODIFICATION') { } else if (design.event === 'MODIFICATION') {
...@@ -222,7 +222,7 @@ export default { ...@@ -222,7 +222,7 @@ export default {
}, },
changeSelectedDesigns(filename) { changeSelectedDesigns(filename) {
if (this.isDesignSelected(filename)) { if (this.isDesignSelected(filename)) {
this.selectedDesigns = this.selectedDesigns.filter(design => design !== filename); this.selectedDesigns = this.selectedDesigns.filter((design) => design !== filename);
} else { } else {
this.selectedDesigns.push(filename); this.selectedDesigns.push(filename);
} }
...@@ -231,14 +231,14 @@ export default { ...@@ -231,14 +231,14 @@ export default {
if (this.hasSelectedDesigns) { if (this.hasSelectedDesigns) {
this.selectedDesigns = []; this.selectedDesigns = [];
} else { } else {
this.selectedDesigns = this.designs.map(design => design.filename); this.selectedDesigns = this.designs.map((design) => design.filename);
} }
}, },
isDesignSelected(filename) { isDesignSelected(filename) {
return this.selectedDesigns.includes(filename); return this.selectedDesigns.includes(filename);
}, },
isDesignToBeSaved(filename) { isDesignToBeSaved(filename) {
return this.filesToBeSaved.some(file => file.name === filename); return this.filesToBeSaved.some((file) => file.name === filename);
}, },
canSelectDesign(filename) { canSelectDesign(filename) {
return this.isLatestVersion && this.canCreateDesign && !this.isDesignToBeSaved(filename); return this.isLatestVersion && this.canCreateDesign && !this.isDesignToBeSaved(filename);
......
...@@ -11,14 +11,14 @@ import { ...@@ -11,14 +11,14 @@ import {
designDeletionError, designDeletionError,
} from './error_messages'; } from './error_messages';
const designsOf = data => data.project.issue.designCollection.designs; const designsOf = (data) => data.project.issue.designCollection.designs;
const deleteDesignsFromStore = (store, query, selectedDesigns) => { const deleteDesignsFromStore = (store, query, selectedDesigns) => {
const sourceData = store.readQuery(query); const sourceData = store.readQuery(query);
const data = produce(sourceData, draftData => { const data = produce(sourceData, (draftData) => {
const changedDesigns = designsOf(sourceData).nodes.filter( const changedDesigns = designsOf(sourceData).nodes.filter(
design => !selectedDesigns.includes(design.filename), (design) => !selectedDesigns.includes(design.filename),
); );
designsOf(draftData).nodes = [...changedDesigns]; designsOf(draftData).nodes = [...changedDesigns];
}); });
...@@ -40,7 +40,7 @@ const addNewVersionToStore = (store, query, version) => { ...@@ -40,7 +40,7 @@ const addNewVersionToStore = (store, query, version) => {
if (!version) return; if (!version) return;
const sourceData = store.readQuery(query); const sourceData = store.readQuery(query);
const data = produce(sourceData, draftData => { const data = produce(sourceData, (draftData) => {
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
draftData.project.issue.designCollection.versions.nodes = [ draftData.project.issue.designCollection.versions.nodes = [
version, version,
...@@ -74,14 +74,14 @@ const addImageDiffNoteToStore = (store, createImageDiffNote, query, variables) = ...@@ -74,14 +74,14 @@ const addImageDiffNoteToStore = (store, createImageDiffNote, query, variables) =
}, },
}; };
const data = produce(sourceData, draftData => { const data = produce(sourceData, (draftData) => {
const design = extractDesign(draftData); const design = extractDesign(draftData);
design.notesCount += 1; design.notesCount += 1;
design.discussions.nodes = [...design.discussions.nodes, newDiscussion]; design.discussions.nodes = [...design.discussions.nodes, newDiscussion];
if ( if (
!design.issue.participants.nodes.some( !design.issue.participants.nodes.some(
participant => participant.username === createImageDiffNote.note.author.username, (participant) => participant.username === createImageDiffNote.note.author.username,
) )
) { ) {
design.issue.participants.nodes = [ design.issue.participants.nodes = [
...@@ -107,7 +107,7 @@ const updateImageDiffNoteInStore = (store, repositionImageDiffNote, query, varia ...@@ -107,7 +107,7 @@ const updateImageDiffNoteInStore = (store, repositionImageDiffNote, query, varia
variables, variables,
}); });
const data = produce(sourceData, draftData => { const data = produce(sourceData, (draftData) => {
const design = extractDesign(draftData); const design = extractDesign(draftData);
const discussion = extractCurrentDiscussion( const discussion = extractCurrentDiscussion(
design.discussions, design.discussions,
...@@ -130,18 +130,18 @@ const updateImageDiffNoteInStore = (store, repositionImageDiffNote, query, varia ...@@ -130,18 +130,18 @@ const updateImageDiffNoteInStore = (store, repositionImageDiffNote, query, varia
const addNewDesignToStore = (store, designManagementUpload, query) => { const addNewDesignToStore = (store, designManagementUpload, query) => {
const sourceData = store.readQuery(query); const sourceData = store.readQuery(query);
const data = produce(sourceData, draftData => { const data = produce(sourceData, (draftData) => {
const currentDesigns = extractDesigns(draftData); const currentDesigns = extractDesigns(draftData);
const difference = differenceBy(designManagementUpload.designs, currentDesigns, 'filename'); const difference = differenceBy(designManagementUpload.designs, currentDesigns, 'filename');
const newDesigns = currentDesigns const newDesigns = currentDesigns
.map(design => { .map((design) => {
return designManagementUpload.designs.find(d => d.filename === design.filename) || design; return designManagementUpload.designs.find((d) => d.filename === design.filename) || design;
}) })
.concat(difference); .concat(difference);
let newVersionNode; let newVersionNode;
const findNewVersions = designManagementUpload.designs.find(design => design.versions); const findNewVersions = designManagementUpload.designs.find((design) => design.versions);
if (findNewVersions) { if (findNewVersions) {
const findNewVersionsNodes = findNewVersions.versions.nodes; const findNewVersionsNodes = findNewVersions.versions.nodes;
...@@ -181,7 +181,7 @@ const addNewDesignToStore = (store, designManagementUpload, query) => { ...@@ -181,7 +181,7 @@ const addNewDesignToStore = (store, designManagementUpload, query) => {
const moveDesignInStore = (store, designManagementMove, query) => { const moveDesignInStore = (store, designManagementMove, query) => {
const sourceData = store.readQuery(query); const sourceData = store.readQuery(query);
const data = produce(sourceData, draftData => { const data = produce(sourceData, (draftData) => {
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
draftData.project.issue.designCollection.designs = draftData.project.issue.designCollection.designs =
designManagementMove.designCollection.designs; designManagementMove.designCollection.designs;
...@@ -199,7 +199,7 @@ export const addPendingTodoToStore = (store, pendingTodo, query, queryVariables) ...@@ -199,7 +199,7 @@ export const addPendingTodoToStore = (store, pendingTodo, query, queryVariables)
variables: queryVariables, variables: queryVariables,
}); });
const data = produce(sourceData, draftData => { const data = produce(sourceData, (draftData) => {
const design = extractDesign(draftData); const design = extractDesign(draftData);
const existingTodos = design.currentUserTodos?.nodes || []; const existingTodos = design.currentUserTodos?.nodes || [];
const newTodoNodes = [...existingTodos, { ...pendingTodo, __typename: 'Todo' }]; const newTodoNodes = [...existingTodos, { ...pendingTodo, __typename: 'Todo' }];
...@@ -226,7 +226,7 @@ export const deletePendingTodoFromStore = (store, todoMarkDone, query, queryVari ...@@ -226,7 +226,7 @@ export const deletePendingTodoFromStore = (store, todoMarkDone, query, queryVari
const { const {
todo: { id: todoId }, todo: { id: todoId },
} = todoMarkDone; } = todoMarkDone;
const data = produce(sourceData, draftData => { const data = produce(sourceData, (draftData) => {
const design = extractDesign(draftData); const design = extractDesign(draftData);
const existingTodos = design.currentUserTodos?.nodes || []; const existingTodos = design.currentUserTodos?.nodes || [];
......
...@@ -10,7 +10,7 @@ export const isValidDesignFile = ({ type }) => ...@@ -10,7 +10,7 @@ export const isValidDesignFile = ({ type }) =>
* @param {Array} discussions * @param {Array} discussions
*/ */
export const extractDiscussions = discussions => export const extractDiscussions = (discussions) =>
discussions.nodes.map((discussion, index) => ({ discussions.nodes.map((discussion, index) => ({
...discussion, ...discussion,
index: index + 1, index: index + 1,
...@@ -24,27 +24,27 @@ export const extractDiscussions = discussions => ...@@ -24,27 +24,27 @@ export const extractDiscussions = discussions =>
*/ */
export const extractCurrentDiscussion = (discussions, id) => export const extractCurrentDiscussion = (discussions, id) =>
discussions.nodes.find(discussion => discussion.id === id); discussions.nodes.find((discussion) => discussion.id === id);
export const findVersionId = id => (id.match('::Version/(.+$)') || [])[1]; export const findVersionId = (id) => (id.match('::Version/(.+$)') || [])[1];
export const findNoteId = id => (id.match('DiffNote/(.+$)') || [])[1]; export const findNoteId = (id) => (id.match('DiffNote/(.+$)') || [])[1];
export const findIssueId = id => (id.match('Issue/(.+$)') || [])[1]; export const findIssueId = (id) => (id.match('Issue/(.+$)') || [])[1];
export const findDesignId = id => (id.match('Design/(.+$)') || [])[1]; export const findDesignId = (id) => (id.match('Design/(.+$)') || [])[1];
export const extractDesigns = data => data.project.issue.designCollection.designs.nodes; export const extractDesigns = (data) => data.project.issue.designCollection.designs.nodes;
export const extractDesign = data => (extractDesigns(data) || [])[0]; export const extractDesign = (data) => (extractDesigns(data) || [])[0];
export const toDiffNoteGid = noteId => `gid://gitlab/DiffNote/${noteId}`; export const toDiffNoteGid = (noteId) => `gid://gitlab/DiffNote/${noteId}`;
/** /**
* Return the note ID from a URL hash parameter * Return the note ID from a URL hash parameter
* @param {String} urlHash URL hash, including `#` prefix * @param {String} urlHash URL hash, including `#` prefix
*/ */
export const extractDesignNoteId = urlHash => { export const extractDesignNoteId = (urlHash) => {
const [, noteId] = urlHash.match('#note_([0-9]+$)') || []; const [, noteId] = urlHash.match('#note_([0-9]+$)') || [];
return noteId || null; return noteId || null;
}; };
...@@ -53,8 +53,8 @@ export const extractDesignNoteId = urlHash => { ...@@ -53,8 +53,8 @@ export const extractDesignNoteId = urlHash => {
* Generates optimistic response for a design upload mutation * Generates optimistic response for a design upload mutation
* @param {Array<File>} files * @param {Array<File>} files
*/ */
export const designUploadOptimisticResponse = files => { export const designUploadOptimisticResponse = (files) => {
const designs = files.map(file => ({ const designs = files.map((file) => ({
// False positive i18n lint: https://gitlab.com/gitlab-org/frontend/eslint-plugin-i18n/issues/26 // False positive i18n lint: https://gitlab.com/gitlab-org/frontend/eslint-plugin-i18n/issues/26
// eslint-disable-next-line @gitlab/require-i18n-strings // eslint-disable-next-line @gitlab/require-i18n-strings
__typename: 'Design', __typename: 'Design',
...@@ -128,7 +128,7 @@ export const repositionImageDiffNoteOptimisticResponse = (note, { position }) => ...@@ -128,7 +128,7 @@ export const repositionImageDiffNoteOptimisticResponse = (note, { position }) =>
* Generates optimistic response for a design upload mutation * Generates optimistic response for a design upload mutation
* @param {Array} designs * @param {Array} designs
*/ */
export const moveDesignOptimisticResponse = designs => ({ export const moveDesignOptimisticResponse = (designs) => ({
// False positive i18n lint: https://gitlab.com/gitlab-org/frontend/eslint-plugin-i18n/issues/26 // False positive i18n lint: https://gitlab.com/gitlab-org/frontend/eslint-plugin-i18n/issues/26
// eslint-disable-next-line @gitlab/require-i18n-strings // eslint-disable-next-line @gitlab/require-i18n-strings
__typename: 'Mutation', __typename: 'Mutation',
...@@ -145,13 +145,13 @@ export const moveDesignOptimisticResponse = designs => ({ ...@@ -145,13 +145,13 @@ export const moveDesignOptimisticResponse = designs => ({
}, },
}); });
const normalizeAuthor = author => ({ const normalizeAuthor = (author) => ({
...author, ...author,
web_url: author.webUrl, web_url: author.webUrl,
avatar_url: author.avatarUrl, avatar_url: author.avatarUrl,
}); });
export const extractParticipants = users => users.map(node => normalizeAuthor(node)); export const extractParticipants = (users) => users.map((node) => normalizeAuthor(node));
export const getPageLayoutElement = () => document.querySelector('.layout-page'); export const getPageLayoutElement = () => document.querySelector('.layout-page');
...@@ -160,14 +160,14 @@ export const getPageLayoutElement = () => document.querySelector('.layout-page') ...@@ -160,14 +160,14 @@ export const getPageLayoutElement = () => document.querySelector('.layout-page')
* Example of todoDeletePath: /delete/1234 * Example of todoDeletePath: /delete/1234
* @param {String} todoDeletePath delete_path from REST API response * @param {String} todoDeletePath delete_path from REST API response
*/ */
export const extractTodoIdFromDeletePath = todoDeletePath => export const extractTodoIdFromDeletePath = (todoDeletePath) =>
(todoDeletePath.match('todos/([0-9]+$)') || [])[1]; (todoDeletePath.match('todos/([0-9]+$)') || [])[1];
const createTodoGid = todoId => { const createTodoGid = (todoId) => {
return `gid://gitlab/Todo/${todoId}`; return `gid://gitlab/Todo/${todoId}`;
}; };
export const createPendingTodo = todoId => { export const createPendingTodo = (todoId) => {
return { return {
__typename: 'Todo', // eslint-disable-line @gitlab/require-i18n-strings __typename: 'Todo', // eslint-disable-line @gitlab/require-i18n-strings
id: createTodoGid(todoId), id: createTodoGid(todoId),
......
...@@ -54,7 +54,7 @@ export const TOGGLE_TODO_ERROR = __('Failed to toggle To-Do for the design.'); ...@@ -54,7 +54,7 @@ export const TOGGLE_TODO_ERROR = __('Failed to toggle To-Do for the design.');
const MAX_SKIPPED_FILES_LISTINGS = 5; const MAX_SKIPPED_FILES_LISTINGS = 5;
const oneDesignSkippedMessage = filename => const oneDesignSkippedMessage = (filename) =>
`${DESIGN_UPLOAD_SKIPPED_MESSAGE} ${sprintf(s__('DesignManagement|%{filename} did not change.'), { `${DESIGN_UPLOAD_SKIPPED_MESSAGE} ${sprintf(s__('DesignManagement|%{filename} did not change.'), {
filename, filename,
})}`; })}`;
...@@ -64,7 +64,7 @@ const oneDesignSkippedMessage = filename => ...@@ -64,7 +64,7 @@ const oneDesignSkippedMessage = filename =>
* files were skipped. * files were skipped.
* @param {Array<{ filename }>} skippedFiles * @param {Array<{ filename }>} skippedFiles
*/ */
const someDesignsSkippedMessage = skippedFiles => { const someDesignsSkippedMessage = (skippedFiles) => {
const designsSkippedMessage = `${DESIGN_UPLOAD_SKIPPED_MESSAGE} ${s__( const designsSkippedMessage = `${DESIGN_UPLOAD_SKIPPED_MESSAGE} ${s__(
'Some of the designs you tried uploading did not change:', 'Some of the designs you tried uploading did not change:',
)}`; )}`;
......
...@@ -117,7 +117,7 @@ export default class Diff { ...@@ -117,7 +117,7 @@ export default class Diff {
table.removeClass('left-side-selected right-side-selected'); table.removeClass('left-side-selected right-side-selected');
const lineClass = ['left-side', 'right-side'].filter(name => line.hasClass(name))[0]; const lineClass = ['left-side', 'right-side'].filter((name) => line.hasClass(name))[0];
if (lineClass) { if (lineClass) {
table.addClass(`${lineClass}-selected`); table.addClass(`${lineClass}-selected`);
} }
...@@ -132,7 +132,7 @@ export default class Diff { ...@@ -132,7 +132,7 @@ export default class Diff {
if (children.length !== 2) { if (children.length !== 2) {
return [0, 0]; return [0, 0];
} }
return children.map(elm => parseInt($(elm).data('linenumber'), 10) || 0); return children.map((elm) => parseInt($(elm).data('linenumber'), 10) || 0);
} }
// eslint-disable-next-line class-methods-use-this // eslint-disable-next-line class-methods-use-this
highlightSelectedLine() { highlightSelectedLine() {
......
...@@ -141,19 +141,19 @@ export default { ...@@ -141,19 +141,19 @@ export default {
}, },
computed: { computed: {
...mapState({ ...mapState({
isLoading: state => state.diffs.isLoading, isLoading: (state) => state.diffs.isLoading,
isBatchLoading: state => state.diffs.isBatchLoading, isBatchLoading: (state) => state.diffs.isBatchLoading,
diffFiles: state => state.diffs.diffFiles, diffFiles: (state) => state.diffs.diffFiles,
diffViewType: state => state.diffs.diffViewType, diffViewType: (state) => state.diffs.diffViewType,
mergeRequestDiffs: state => state.diffs.mergeRequestDiffs, mergeRequestDiffs: (state) => state.diffs.mergeRequestDiffs,
mergeRequestDiff: state => state.diffs.mergeRequestDiff, mergeRequestDiff: (state) => state.diffs.mergeRequestDiff,
commit: state => state.diffs.commit, commit: (state) => state.diffs.commit,
renderOverflowWarning: state => state.diffs.renderOverflowWarning, renderOverflowWarning: (state) => state.diffs.renderOverflowWarning,
numTotalFiles: state => state.diffs.realSize, numTotalFiles: (state) => state.diffs.realSize,
numVisibleFiles: state => state.diffs.size, numVisibleFiles: (state) => state.diffs.size,
plainDiffPath: state => state.diffs.plainDiffPath, plainDiffPath: (state) => state.diffs.plainDiffPath,
emailPatchPath: state => state.diffs.emailPatchPath, emailPatchPath: (state) => state.diffs.emailPatchPath,
retrievingBatches: state => state.diffs.retrievingBatches, retrievingBatches: (state) => state.diffs.retrievingBatches,
}), }),
...mapState('diffs', [ ...mapState('diffs', [
'showTreeList', 'showTreeList',
......
...@@ -16,7 +16,7 @@ export default { ...@@ -16,7 +16,7 @@ export default {
}, },
computed: { computed: {
selectedVersionName() { selectedVersionName() {
return this.versions.find(x => x.selected)?.versionName || ''; return this.versions.find((x) => x.selected)?.versionName || '';
}, },
}, },
}; };
......
...@@ -50,7 +50,7 @@ export default { ...@@ -50,7 +50,7 @@ export default {
}, },
computed: { computed: {
...mapState({ ...mapState({
projectPath: state => state.diffs.projectPath, projectPath: (state) => state.diffs.projectPath,
}), }),
...mapGetters('diffs', [ ...mapGetters('diffs', [
'isInlineView', 'isInlineView',
......
...@@ -13,7 +13,7 @@ const EXPAND_DOWN = 2; ...@@ -13,7 +13,7 @@ const EXPAND_DOWN = 2;
const lineNumberByViewType = (viewType, diffLine) => { const lineNumberByViewType = (viewType, diffLine) => {
const numberGetters = { const numberGetters = {
[INLINE_DIFF_VIEW_TYPE]: line => line?.new_line, [INLINE_DIFF_VIEW_TYPE]: (line) => line?.new_line,
}; };
const numberGetter = numberGetters[viewType]; const numberGetter = numberGetters[viewType];
return numberGetter && numberGetter(diffLine); return numberGetter && numberGetter(diffLine);
...@@ -56,7 +56,7 @@ export default { ...@@ -56,7 +56,7 @@ export default {
}, },
computed: { computed: {
...mapState({ ...mapState({
diffFiles: state => state.diffs.diffFiles, diffFiles: (state) => state.diffs.diffFiles,
}), }),
canExpandUp() { canExpandUp() {
return !this.isBottom; return !this.isBottom;
......
...@@ -210,7 +210,7 @@ export default { ...@@ -210,7 +210,7 @@ export default {
await this.$nextTick(); await this.$nextTick();
eventsForThisFile.forEach(event => { eventsForThisFile.forEach((event) => {
eventHub.$emit(event); eventHub.$emit(event);
}); });
}, },
......
...@@ -29,7 +29,7 @@ export default { ...@@ -29,7 +29,7 @@ export default {
return this.discussions.reduce((acc, note) => acc.concat(note.notes), []); return this.discussions.reduce((acc, note) => acc.concat(note.notes), []);
}, },
notesInGutter() { notesInGutter() {
return this.allDiscussions.slice(0, COUNT_OF_AVATARS_IN_GUTTER).map(n => ({ return this.allDiscussions.slice(0, COUNT_OF_AVATARS_IN_GUTTER).map((n) => ({
note: n.note, note: n.note,
author: n.author, author: n.author,
})); }));
......
...@@ -56,8 +56,8 @@ export default { ...@@ -56,8 +56,8 @@ export default {
}, },
computed: { computed: {
...mapState({ ...mapState({
noteableData: state => state.notes.noteableData, noteableData: (state) => state.notes.noteableData,
diffViewType: state => state.diffs.diffViewType, diffViewType: (state) => state.diffs.diffViewType,
}), }),
...mapState('diffs', ['showSuggestPopover']), ...mapState('diffs', ['showSuggestPopover']),
...mapGetters('diffs', ['getDiffFileByHash', 'diffLines']), ...mapGetters('diffs', ['getDiffFileByHash', 'diffLines']),
......
...@@ -15,22 +15,22 @@ export const isHighlighted = (state, line, isCommented) => { ...@@ -15,22 +15,22 @@ export const isHighlighted = (state, line, isCommented) => {
return lineCode ? lineCode === state.diffs.highlightedRow : false; return lineCode ? lineCode === state.diffs.highlightedRow : false;
}; };
export const isContextLine = type => type === CONTEXT_LINE_TYPE; export const isContextLine = (type) => type === CONTEXT_LINE_TYPE;
export const isMatchLine = type => type === MATCH_LINE_TYPE; export const isMatchLine = (type) => type === MATCH_LINE_TYPE;
export const isMetaLine = type => export const isMetaLine = (type) =>
[OLD_NO_NEW_LINE_TYPE, NEW_NO_NEW_LINE_TYPE, EMPTY_CELL_TYPE].includes(type); [OLD_NO_NEW_LINE_TYPE, NEW_NO_NEW_LINE_TYPE, EMPTY_CELL_TYPE].includes(type);
export const shouldRenderCommentButton = (isLoggedIn, isCommentButtonRendered) => { export const shouldRenderCommentButton = (isLoggedIn, isCommentButtonRendered) => {
return isCommentButtonRendered && isLoggedIn; return isCommentButtonRendered && isLoggedIn;
}; };
export const hasDiscussions = line => line?.discussions?.length > 0; export const hasDiscussions = (line) => line?.discussions?.length > 0;
export const lineHref = line => `#${line?.line_code || ''}`; export const lineHref = (line) => `#${line?.line_code || ''}`;
export const lineCode = line => { export const lineCode = (line) => {
if (!line) return undefined; if (!line) return undefined;
return line.line_code || line.left?.line_code || line.right?.line_code; return line.line_code || line.left?.line_code || line.right?.line_code;
}; };
...@@ -48,7 +48,7 @@ export const classNameMapCell = (line, hll, isLoggedIn, isHover) => { ...@@ -48,7 +48,7 @@ export const classNameMapCell = (line, hll, isLoggedIn, isHover) => {
]; ];
}; };
export const addCommentTooltip = line => { export const addCommentTooltip = (line) => {
let tooltip; let tooltip;
if (!line) return tooltip; if (!line) return tooltip;
...@@ -84,7 +84,7 @@ export const shouldShowCommentButton = (hover, context, meta, discussions) => { ...@@ -84,7 +84,7 @@ export const shouldShowCommentButton = (hover, context, meta, discussions) => {
return hover && !context && !meta && !discussions; return hover && !context && !meta && !discussions;
}; };
export const mapParallel = content => line => { export const mapParallel = (content) => (line) => {
let { left, right } = line; let { left, right } = line;
// Dicussions/Comments // Dicussions/Comments
...@@ -137,7 +137,7 @@ export const mapParallel = content => line => { ...@@ -137,7 +137,7 @@ export const mapParallel = content => line => {
}; };
// TODO: Delete this function when unifiedDiffComponents FF is removed // TODO: Delete this function when unifiedDiffComponents FF is removed
export const mapInline = content => line => { export const mapInline = (content) => (line) => {
// Discussions/Comments // Discussions/Comments
const renderCommentRow = line.hasForm || (line.discussions?.length && line.discussionsExpanded); const renderCommentRow = line.hasForm || (line.discussions?.length && line.discussionsExpanded);
......
...@@ -112,8 +112,8 @@ export default { ...@@ -112,8 +112,8 @@ export default {
mounted() { mounted() {
this.scrollToLineIfNeededParallel(this.line); this.scrollToLineIfNeededParallel(this.line);
this.unwatchShouldShowCommentButton = this.$watch( this.unwatchShouldShowCommentButton = this.$watch(
vm => [vm.shouldShowCommentButtonLeft, vm.shouldShowCommentButtonRight].join(), (vm) => [vm.shouldShowCommentButtonLeft, vm.shouldShowCommentButtonRight].join(),
newVal => { (newVal) => {
if (newVal) { if (newVal) {
this.isCommentButtonRendered = true; this.isCommentButtonRendered = true;
this.unwatchShouldShowCommentButton(); this.unwatchShouldShowCommentButton();
...@@ -150,7 +150,7 @@ export default { ...@@ -150,7 +150,7 @@ export default {
const table = line.closest('table'); const table = line.closest('table');
table.removeClass('left-side-selected right-side-selected'); table.removeClass('left-side-selected right-side-selected');
const [lineClass] = ['left-side', 'right-side'].filter(name => line.hasClass(name)); const [lineClass] = ['left-side', 'right-side'].filter((name) => line.hasClass(name));
if (lineClass) { if (lineClass) {
table.addClass(`${lineClass}-selected`); table.addClass(`${lineClass}-selected`);
......
...@@ -35,7 +35,7 @@ export default { ...@@ -35,7 +35,7 @@ export default {
} }
return this.allBlobs.reduce((acc, folder) => { return this.allBlobs.reduce((acc, folder) => {
const tree = folder.tree.filter(f => f.path.toLowerCase().indexOf(search) >= 0); const tree = folder.tree.filter((f) => f.path.toLowerCase().indexOf(search) >= 0);
if (tree.length) { if (tree.length) {
return acc.concat({ return acc.concat({
......
...@@ -87,7 +87,7 @@ export default function initDiffsApp(store) { ...@@ -87,7 +87,7 @@ export default function initDiffsApp(store) {
}, },
computed: { computed: {
...mapState({ ...mapState({
activeTab: state => state.page.activeTab, activeTab: (state) => state.page.activeTab,
}), }),
}, },
created() { created() {
......
...@@ -127,7 +127,7 @@ export const fetchDiffFilesBatch = ({ commit, state, dispatch }) => { ...@@ -127,7 +127,7 @@ export const fetchDiffFilesBatch = ({ commit, state, dispatch }) => {
// We need to check that the currentDiffFileId points to a file that exists // We need to check that the currentDiffFileId points to a file that exists
if ( if (
state.currentDiffFileId && state.currentDiffFileId &&
!state.diffFiles.some(f => f.file_hash === state.currentDiffFileId) && !state.diffFiles.some((f) => f.file_hash === state.currentDiffFileId) &&
!isNoteLink !isNoteLink
) { ) {
commit(types.VIEW_DIFF_FILE, state.diffFiles[0].file_hash); commit(types.VIEW_DIFF_FILE, state.diffFiles[0].file_hash);
...@@ -135,11 +135,11 @@ export const fetchDiffFilesBatch = ({ commit, state, dispatch }) => { ...@@ -135,11 +135,11 @@ export const fetchDiffFilesBatch = ({ commit, state, dispatch }) => {
if (state.diffFiles?.length) { if (state.diffFiles?.length) {
// eslint-disable-next-line promise/catch-or-return,promise/no-nesting // eslint-disable-next-line promise/catch-or-return,promise/no-nesting
import('~/code_navigation').then(m => import('~/code_navigation').then((m) =>
m.default({ m.default({
blobs: state.diffFiles blobs: state.diffFiles
.filter(f => f.code_navigation_path) .filter((f) => f.code_navigation_path)
.map(f => ({ .map((f) => ({
path: f.new_path, path: f.new_path,
codeNavigationPath: f.code_navigation_path, codeNavigationPath: f.code_navigation_path,
})), })),
...@@ -161,7 +161,7 @@ export const fetchDiffFilesBatch = ({ commit, state, dispatch }) => { ...@@ -161,7 +161,7 @@ export const fetchDiffFilesBatch = ({ commit, state, dispatch }) => {
return pagination.next_page; return pagination.next_page;
}) })
.then(nextPage => nextPage && getBatch(nextPage)) .then((nextPage) => nextPage && getBatch(nextPage))
.catch(() => commit(types.SET_RETRIEVING_BATCHES, false)); .catch(() => commit(types.SET_RETRIEVING_BATCHES, false));
return getBatch() return getBatch()
...@@ -211,7 +211,7 @@ export const fetchDiffFilesMeta = ({ commit, state }) => { ...@@ -211,7 +211,7 @@ export const fetchDiffFilesMeta = ({ commit, state }) => {
export const fetchCoverageFiles = ({ commit, state }) => { export const fetchCoverageFiles = ({ commit, state }) => {
const coveragePoll = new Poll({ const coveragePoll = new Poll({
resource: { resource: {
getCoverageReports: endpoint => axios.get(endpoint), getCoverageReports: (endpoint) => axios.get(endpoint),
}, },
data: state.endpointCoverage, data: state.endpointCoverage,
method: 'getCoverageReports', method: 'getCoverageReports',
...@@ -246,8 +246,8 @@ export const assignDiscussionsToDiff = ( ...@@ -246,8 +246,8 @@ export const assignDiscussionsToDiff = (
const hash = getLocationHash(); const hash = getLocationHash();
discussions discussions
.filter(discussion => discussion.diff_discussion) .filter((discussion) => discussion.diff_discussion)
.forEach(discussion => { .forEach((discussion) => {
commit(types.SET_LINE_DISCUSSIONS_FOR_FILE, { commit(types.SET_LINE_DISCUSSIONS_FOR_FILE, {
discussion, discussion,
diffPositionByLineCode, diffPositionByLineCode,
...@@ -274,10 +274,10 @@ export const toggleLineDiscussions = ({ commit }, options) => { ...@@ -274,10 +274,10 @@ export const toggleLineDiscussions = ({ commit }, options) => {
}; };
export const renderFileForDiscussionId = ({ commit, rootState, state }, discussionId) => { export const renderFileForDiscussionId = ({ commit, rootState, state }, discussionId) => {
const discussion = rootState.notes.discussions.find(d => d.id === discussionId); const discussion = rootState.notes.discussions.find((d) => d.id === discussionId);
if (discussion && discussion.diff_file) { if (discussion && discussion.diff_file) {
const file = state.diffFiles.find(f => f.file_hash === discussion.diff_file.file_hash); const file = state.diffFiles.find((f) => f.file_hash === discussion.diff_file.file_hash);
if (file) { if (file) {
if (!file.renderIt) { if (!file.renderIt) {
...@@ -303,9 +303,9 @@ export const renderFileForDiscussionId = ({ commit, rootState, state }, discussi ...@@ -303,9 +303,9 @@ export const renderFileForDiscussionId = ({ commit, rootState, state }, discussi
export const startRenderDiffsQueue = ({ state, commit }) => { export const startRenderDiffsQueue = ({ state, commit }) => {
const checkItem = () => const checkItem = () =>
new Promise(resolve => { new Promise((resolve) => {
const nextFile = state.diffFiles.find( const nextFile = state.diffFiles.find(
file => (file) =>
!file.renderIt && !file.renderIt &&
file.viewer && file.viewer &&
(!isCollapsed(file) || file.viewer.name !== diffViewerModes.text), (!isCollapsed(file) || file.viewer.name !== diffViewerModes.text),
...@@ -362,7 +362,7 @@ export const loadMoreLines = ({ commit }, options) => { ...@@ -362,7 +362,7 @@ export const loadMoreLines = ({ commit }, options) => {
params.from_merge_request = true; params.from_merge_request = true;
return axios.get(endpoint, { params }).then(res => { return axios.get(endpoint, { params }).then((res) => {
const contextLines = res.data || []; const contextLines = res.data || [];
commit(types.ADD_CONTEXT_LINES, { commit(types.ADD_CONTEXT_LINES, {
...@@ -403,7 +403,7 @@ export const loadCollapsedDiff = ({ commit, getters, state }, file) => ...@@ -403,7 +403,7 @@ export const loadCollapsedDiff = ({ commit, getters, state }, file) =>
w: state.showWhitespace ? '0' : '1', w: state.showWhitespace ? '0' : '1',
}, },
}) })
.then(res => { .then((res) => {
commit(types.ADD_COLLAPSED_DIFFS, { commit(types.ADD_COLLAPSED_DIFFS, {
file, file,
data: res.data, data: res.data,
...@@ -426,7 +426,7 @@ export const toggleFileDiscussions = ({ getters, dispatch }, diff) => { ...@@ -426,7 +426,7 @@ export const toggleFileDiscussions = ({ getters, dispatch }, diff) => {
const shouldCloseAll = getters.diffHasAllExpandedDiscussions(diff); const shouldCloseAll = getters.diffHasAllExpandedDiscussions(diff);
const shouldExpandAll = getters.diffHasAllCollapsedDiscussions(diff); const shouldExpandAll = getters.diffHasAllCollapsedDiscussions(diff);
discussions.forEach(discussion => { discussions.forEach((discussion) => {
const data = { discussionId: discussion.id }; const data = { discussionId: discussion.id };
if (shouldCloseAll) { if (shouldCloseAll) {
...@@ -440,13 +440,13 @@ export const toggleFileDiscussions = ({ getters, dispatch }, diff) => { ...@@ -440,13 +440,13 @@ export const toggleFileDiscussions = ({ getters, dispatch }, diff) => {
export const toggleFileDiscussionWrappers = ({ commit }, diff) => { export const toggleFileDiscussionWrappers = ({ commit }, diff) => {
const discussionWrappersExpanded = allDiscussionWrappersExpanded(diff); const discussionWrappersExpanded = allDiscussionWrappersExpanded(diff);
const lineCodesWithDiscussions = new Set(); const lineCodesWithDiscussions = new Set();
const lineHasDiscussion = line => Boolean(line?.discussions.length); const lineHasDiscussion = (line) => Boolean(line?.discussions.length);
const registerDiscussionLine = line => lineCodesWithDiscussions.add(line.line_code); const registerDiscussionLine = (line) => lineCodesWithDiscussions.add(line.line_code);
diff[INLINE_DIFF_LINES_KEY].filter(lineHasDiscussion).forEach(registerDiscussionLine); diff[INLINE_DIFF_LINES_KEY].filter(lineHasDiscussion).forEach(registerDiscussionLine);
if (lineCodesWithDiscussions.size) { if (lineCodesWithDiscussions.size) {
Array.from(lineCodesWithDiscussions).forEach(lineCode => { Array.from(lineCodesWithDiscussions).forEach((lineCode) => {
commit(types.TOGGLE_LINE_DISCUSSIONS, { commit(types.TOGGLE_LINE_DISCUSSIONS, {
fileHash: diff.file_hash, fileHash: diff.file_hash,
expanded: !discussionWrappersExpanded, expanded: !discussionWrappersExpanded,
...@@ -464,8 +464,8 @@ export const saveDiffDiscussion = ({ state, dispatch }, { note, formData }) => { ...@@ -464,8 +464,8 @@ export const saveDiffDiscussion = ({ state, dispatch }, { note, formData }) => {
}); });
return dispatch('saveNote', postData, { root: true }) return dispatch('saveNote', postData, { root: true })
.then(result => dispatch('updateDiscussion', result.discussion, { root: true })) .then((result) => dispatch('updateDiscussion', result.discussion, { root: true }))
.then(discussion => dispatch('assignDiscussionsToDiff', [discussion])) .then((discussion) => dispatch('assignDiscussionsToDiff', [discussion]))
.then(() => dispatch('updateResolvableDiscussionsCounts', null, { root: true })) .then(() => dispatch('updateResolvableDiscussionsCounts', null, { root: true }))
.then(() => dispatch('closeDiffFileCommentForm', formData.diffFile.file_hash)) .then(() => dispatch('closeDiffFileCommentForm', formData.diffFile.file_hash))
.catch(() => createFlash(s__('MergeRequests|Saving the comment failed'))); .catch(() => createFlash(s__('MergeRequests|Saving the comment failed')));
...@@ -565,7 +565,7 @@ export const setExpandedDiffLines = ({ commit }, { file, data }) => { ...@@ -565,7 +565,7 @@ export const setExpandedDiffLines = ({ commit }, { file, data }) => {
}); });
commit(types.TOGGLE_DIFF_FILE_RENDERING_MORE, file.file_path); commit(types.TOGGLE_DIFF_FILE_RENDERING_MORE, file.file_path);
const idleCb = t => { const idleCb = (t) => {
const startIndex = index; const startIndex = index;
while ( while (
...@@ -613,7 +613,7 @@ export const fetchFullDiff = ({ commit, dispatch }, file) => ...@@ -613,7 +613,7 @@ export const fetchFullDiff = ({ commit, dispatch }, file) =>
.catch(() => dispatch('receiveFullDiffError', file.file_path)); .catch(() => dispatch('receiveFullDiffError', file.file_path));
export const toggleFullDiff = ({ dispatch, commit, getters, state }, filePath) => { export const toggleFullDiff = ({ dispatch, commit, getters, state }, filePath) => {
const file = state.diffFiles.find(f => f.file_path === filePath); const file = state.diffFiles.find((f) => f.file_path === filePath);
commit(types.REQUEST_FULL_DIFF, filePath); commit(types.REQUEST_FULL_DIFF, filePath);
...@@ -724,7 +724,7 @@ export const setCurrentDiffFileIdFromNote = ({ commit, state, rootGetters }, not ...@@ -724,7 +724,7 @@ export const setCurrentDiffFileIdFromNote = ({ commit, state, rootGetters }, not
const fileHash = rootGetters.getDiscussion(note.discussion_id).diff_file?.file_hash; const fileHash = rootGetters.getDiscussion(note.discussion_id).diff_file?.file_hash;
if (fileHash && state.diffFiles.some(f => f.file_hash === fileHash)) { if (fileHash && state.diffFiles.some((f) => f.file_hash === fileHash)) {
commit(types.VIEW_DIFF_FILE, fileHash); commit(types.VIEW_DIFF_FILE, fileHash);
} }
}; };
......
...@@ -2,10 +2,10 @@ import { __, n__, sprintf } from '~/locale'; ...@@ -2,10 +2,10 @@ import { __, n__, sprintf } from '~/locale';
import { getParameterByName, parseBoolean } from '~/lib/utils/common_utils'; import { getParameterByName, parseBoolean } from '~/lib/utils/common_utils';
import { DIFF_COMPARE_BASE_VERSION_INDEX, DIFF_COMPARE_HEAD_VERSION_INDEX } from '../constants'; import { DIFF_COMPARE_BASE_VERSION_INDEX, DIFF_COMPARE_HEAD_VERSION_INDEX } from '../constants';
export const selectedTargetIndex = state => export const selectedTargetIndex = (state) =>
state.startVersion?.version_index || DIFF_COMPARE_BASE_VERSION_INDEX; state.startVersion?.version_index || DIFF_COMPARE_BASE_VERSION_INDEX;
export const selectedSourceIndex = state => state.mergeRequestDiff.version_index; export const selectedSourceIndex = (state) => state.mergeRequestDiff.version_index;
export const diffCompareDropdownTargetVersions = (state, getters) => { export const diffCompareDropdownTargetVersions = (state, getters) => {
// startVersion only exists if the user has selected a version other // startVersion only exists if the user has selected a version other
...@@ -40,7 +40,7 @@ export const diffCompareDropdownTargetVersions = (state, getters) => { ...@@ -40,7 +40,7 @@ export const diffCompareDropdownTargetVersions = (state, getters) => {
selected: isHeadSelected, selected: isHeadSelected,
}; };
// Appended properties here are to make the compare_dropdown_layout easier to reason about // Appended properties here are to make the compare_dropdown_layout easier to reason about
const formatVersion = v => { const formatVersion = (v) => {
return { return {
href: v.compare_path, href: v.compare_path,
versionName: sprintf(__(`version %{versionIndex}`), { versionIndex: v.version_index }), versionName: sprintf(__(`version %{versionIndex}`), { versionIndex: v.version_index }),
...@@ -53,7 +53,7 @@ export const diffCompareDropdownTargetVersions = (state, getters) => { ...@@ -53,7 +53,7 @@ export const diffCompareDropdownTargetVersions = (state, getters) => {
...state.mergeRequestDiffs.slice(1).map(formatVersion), ...state.mergeRequestDiffs.slice(1).map(formatVersion),
baseVersion, baseVersion,
state.mergeRequestDiff.head_version_path && headVersion, state.mergeRequestDiff.head_version_path && headVersion,
].filter(a => a); ].filter((a) => a);
}; };
export const diffCompareDropdownSourceVersions = (state, getters) => { export const diffCompareDropdownSourceVersions = (state, getters) => {
......
...@@ -105,11 +105,11 @@ export default { ...@@ -105,11 +105,11 @@ export default {
}, },
[types.TOGGLE_LINE_HAS_FORM](state, { lineCode, fileHash, hasForm }) { [types.TOGGLE_LINE_HAS_FORM](state, { lineCode, fileHash, hasForm }) {
const diffFile = state.diffFiles.find(f => f.file_hash === fileHash); const diffFile = state.diffFiles.find((f) => f.file_hash === fileHash);
if (!diffFile) return; if (!diffFile) return;
diffFile[INLINE_DIFF_LINES_KEY].find(l => l.line_code === lineCode).hasForm = hasForm; diffFile[INLINE_DIFF_LINES_KEY].find((l) => l.line_code === lineCode).hasForm = hasForm;
}, },
[types.ADD_CONTEXT_LINES](state, options) { [types.ADD_CONTEXT_LINES](state, options) {
...@@ -125,7 +125,7 @@ export default { ...@@ -125,7 +125,7 @@ export default {
bottom, bottom,
isExpandDown, isExpandDown,
nextLineNumbers, nextLineNumbers,
).map(line => { ).map((line) => {
const lineCode = const lineCode =
line.type === 'match' line.type === 'match'
? `${fileHash}_${line.meta_data.old_pos}_${line.meta_data.new_pos}_match` ? `${fileHash}_${line.meta_data.old_pos}_${line.meta_data.new_pos}_match`
...@@ -149,8 +149,8 @@ export default { ...@@ -149,8 +149,8 @@ export default {
[types.ADD_COLLAPSED_DIFFS](state, { file, data }) { [types.ADD_COLLAPSED_DIFFS](state, { file, data }) {
const files = prepareDiffData({ diff: data }); const files = prepareDiffData({ diff: data });
const [newFileData] = files.filter(f => f.file_hash === file.file_hash); const [newFileData] = files.filter((f) => f.file_hash === file.file_hash);
const selectedFile = state.diffFiles.find(f => f.file_hash === file.file_hash); const selectedFile = state.diffFiles.find((f) => f.file_hash === file.file_hash);
Object.assign(selectedFile, { ...newFileData }); Object.assign(selectedFile, { ...newFileData });
}, },
...@@ -159,9 +159,9 @@ export default { ...@@ -159,9 +159,9 @@ export default {
const discussionLineCodes = [discussion.line_code, ...(discussion.line_codes || [])]; const discussionLineCodes = [discussion.line_code, ...(discussion.line_codes || [])];
const fileHash = discussion.diff_file.file_hash; const fileHash = discussion.diff_file.file_hash;
const lineCheck = line => const lineCheck = (line) =>
discussionLineCodes.some( discussionLineCodes.some(
discussionLineCode => (discussionLineCode) =>
line.line_code === discussionLineCode && line.line_code === discussionLineCode &&
isDiscussionApplicableToLine({ isDiscussionApplicableToLine({
discussion, discussion,
...@@ -179,26 +179,26 @@ export default { ...@@ -179,26 +179,26 @@ export default {
: [], : [],
}); });
const setDiscussionsExpanded = line => { const setDiscussionsExpanded = (line) => {
const isLineNoteTargeted = const isLineNoteTargeted =
line.discussions && line.discussions &&
line.discussions.some( line.discussions.some(
disc => disc.notes && disc.notes.find(note => hash === `note_${note.id}`), (disc) => disc.notes && disc.notes.find((note) => hash === `note_${note.id}`),
); );
return { return {
...line, ...line,
discussionsExpanded: discussionsExpanded:
line.discussions && line.discussions.length line.discussions && line.discussions.length
? line.discussions.some(disc => !disc.resolved) || isLineNoteTargeted ? line.discussions.some((disc) => !disc.resolved) || isLineNoteTargeted
: false, : false,
}; };
}; };
state.diffFiles.forEach(file => { state.diffFiles.forEach((file) => {
if (file.file_hash === fileHash) { if (file.file_hash === fileHash) {
if (file[INLINE_DIFF_LINES_KEY].length) { if (file[INLINE_DIFF_LINES_KEY].length) {
file[INLINE_DIFF_LINES_KEY].forEach(line => { file[INLINE_DIFF_LINES_KEY].forEach((line) => {
Object.assign( Object.assign(
line, line,
setDiscussionsExpanded(lineCheck(line) ? mapDiscussions(line) : line), setDiscussionsExpanded(lineCheck(line) ? mapDiscussions(line) : line),
...@@ -208,7 +208,7 @@ export default { ...@@ -208,7 +208,7 @@ export default {
if (!file[INLINE_DIFF_LINES_KEY].length) { if (!file[INLINE_DIFF_LINES_KEY].length) {
const newDiscussions = (file.discussions || []) const newDiscussions = (file.discussions || [])
.filter(d => d.id !== discussion.id) .filter((d) => d.id !== discussion.id)
.concat(discussion); .concat(discussion);
Object.assign(file, { Object.assign(file, {
...@@ -220,26 +220,26 @@ export default { ...@@ -220,26 +220,26 @@ export default {
}, },
[types.REMOVE_LINE_DISCUSSIONS_FOR_FILE](state, { fileHash, lineCode }) { [types.REMOVE_LINE_DISCUSSIONS_FOR_FILE](state, { fileHash, lineCode }) {
const selectedFile = state.diffFiles.find(f => f.file_hash === fileHash); const selectedFile = state.diffFiles.find((f) => f.file_hash === fileHash);
if (selectedFile) { if (selectedFile) {
updateLineInFile(selectedFile, lineCode, line => updateLineInFile(selectedFile, lineCode, (line) =>
Object.assign(line, { Object.assign(line, {
discussions: line.discussions.filter(discussion => discussion.notes.length), discussions: line.discussions.filter((discussion) => discussion.notes.length),
}), }),
); );
if (selectedFile.discussions && selectedFile.discussions.length) { if (selectedFile.discussions && selectedFile.discussions.length) {
selectedFile.discussions = selectedFile.discussions.filter( selectedFile.discussions = selectedFile.discussions.filter(
discussion => discussion.notes.length, (discussion) => discussion.notes.length,
); );
} }
} }
}, },
[types.TOGGLE_LINE_DISCUSSIONS](state, { fileHash, lineCode, expanded }) { [types.TOGGLE_LINE_DISCUSSIONS](state, { fileHash, lineCode, expanded }) {
const selectedFile = state.diffFiles.find(f => f.file_hash === fileHash); const selectedFile = state.diffFiles.find((f) => f.file_hash === fileHash);
updateLineInFile(selectedFile, lineCode, line => { updateLineInFile(selectedFile, lineCode, (line) => {
Object.assign(line, { discussionsExpanded: expanded }); Object.assign(line, { discussionsExpanded: expanded });
}); });
}, },
...@@ -262,7 +262,7 @@ export default { ...@@ -262,7 +262,7 @@ export default {
[types.UPDATE_DIFF_FILE_COMMENT_FORM](state, formData) { [types.UPDATE_DIFF_FILE_COMMENT_FORM](state, formData) {
const { fileHash } = formData; const { fileHash } = formData;
state.commentForms = state.commentForms.map(form => { state.commentForms = state.commentForms.map((form) => {
if (form.fileHash === fileHash) { if (form.fileHash === fileHash) {
return { return {
...formData, ...formData,
...@@ -273,7 +273,7 @@ export default { ...@@ -273,7 +273,7 @@ export default {
}); });
}, },
[types.CLOSE_DIFF_FILE_COMMENT_FORM](state, fileHash) { [types.CLOSE_DIFF_FILE_COMMENT_FORM](state, fileHash) {
state.commentForms = state.commentForms.filter(form => form.fileHash !== fileHash); state.commentForms = state.commentForms.filter((form) => form.fileHash !== fileHash);
}, },
[types.SET_HIGHLIGHTED_ROW](state, lineCode) { [types.SET_HIGHLIGHTED_ROW](state, lineCode) {
state.highlightedRow = lineCode; state.highlightedRow = lineCode;
...@@ -313,7 +313,7 @@ export default { ...@@ -313,7 +313,7 @@ export default {
state, state,
{ filePath, collapsed, trigger = DIFF_FILE_AUTOMATIC_COLLAPSE }, { filePath, collapsed, trigger = DIFF_FILE_AUTOMATIC_COLLAPSE },
) { ) {
const file = state.diffFiles.find(f => f.file_path === filePath); const file = state.diffFiles.find((f) => f.file_path === filePath);
if (file && file.viewer) { if (file && file.viewer) {
if (trigger === DIFF_FILE_MANUAL_COLLAPSE) { if (trigger === DIFF_FILE_MANUAL_COLLAPSE) {
...@@ -330,17 +330,17 @@ export default { ...@@ -330,17 +330,17 @@ export default {
} }
}, },
[types.SET_CURRENT_VIEW_DIFF_FILE_LINES](state, { filePath, lines }) { [types.SET_CURRENT_VIEW_DIFF_FILE_LINES](state, { filePath, lines }) {
const file = state.diffFiles.find(f => f.file_path === filePath); const file = state.diffFiles.find((f) => f.file_path === filePath);
file[INLINE_DIFF_LINES_KEY] = lines; file[INLINE_DIFF_LINES_KEY] = lines;
}, },
[types.ADD_CURRENT_VIEW_DIFF_FILE_LINES](state, { filePath, line }) { [types.ADD_CURRENT_VIEW_DIFF_FILE_LINES](state, { filePath, line }) {
const file = state.diffFiles.find(f => f.file_path === filePath); const file = state.diffFiles.find((f) => f.file_path === filePath);
file[INLINE_DIFF_LINES_KEY].push(line); file[INLINE_DIFF_LINES_KEY].push(line);
}, },
[types.TOGGLE_DIFF_FILE_RENDERING_MORE](state, filePath) { [types.TOGGLE_DIFF_FILE_RENDERING_MORE](state, filePath) {
const file = state.diffFiles.find(f => f.file_path === filePath); const file = state.diffFiles.find((f) => f.file_path === filePath);
file.renderingLines = !file.renderingLines; file.renderingLines = !file.renderingLines;
}, },
......
...@@ -23,15 +23,15 @@ import { ...@@ -23,15 +23,15 @@ import {
} from '../constants'; } from '../constants';
import { prepareRawDiffFile } from '../utils/diff_file'; import { prepareRawDiffFile } from '../utils/diff_file';
export const isAdded = line => ['new', 'new-nonewline'].includes(line.type); export const isAdded = (line) => ['new', 'new-nonewline'].includes(line.type);
export const isRemoved = line => ['old', 'old-nonewline'].includes(line.type); export const isRemoved = (line) => ['old', 'old-nonewline'].includes(line.type);
export const isUnchanged = line => !line.type; export const isUnchanged = (line) => !line.type;
export const isMeta = line => ['match', 'new-nonewline', 'old-nonewline'].includes(line.type); export const isMeta = (line) => ['match', 'new-nonewline', 'old-nonewline'].includes(line.type);
export const isConflictMarker = line => export const isConflictMarker = (line) =>
[CONFLICT_MARKER_OUR, CONFLICT_MARKER_THEIR].includes(line.type); [CONFLICT_MARKER_OUR, CONFLICT_MARKER_THEIR].includes(line.type);
export const isConflictSeperator = line => line.type === CONFLICT_MARKER; export const isConflictSeperator = (line) => line.type === CONFLICT_MARKER;
export const isConflictOur = line => line.type === CONFLICT_OUR; export const isConflictOur = (line) => line.type === CONFLICT_OUR;
export const isConflictTheir = line => line.type === CONFLICT_THEIR; export const isConflictTheir = (line) => line.type === CONFLICT_THEIR;
/** /**
* Pass in the inline diff lines array which gets converted * Pass in the inline diff lines array which gets converted
...@@ -117,10 +117,10 @@ export const parallelizeDiffLines = (diffLines, inline) => { ...@@ -117,10 +117,10 @@ export const parallelizeDiffLines = (diffLines, inline) => {
}; };
export function findDiffFile(files, match, matchKey = 'file_hash') { export function findDiffFile(files, match, matchKey = 'file_hash') {
return files.find(file => file[matchKey] === match); return files.find((file) => file[matchKey] === match);
} }
export const getReversePosition = linePosition => { export const getReversePosition = (linePosition) => {
if (linePosition === LINE_POSITION_RIGHT) { if (linePosition === LINE_POSITION_RIGHT) {
return LINE_POSITION_LEFT; return LINE_POSITION_LEFT;
} }
...@@ -197,7 +197,7 @@ export const findIndexInInlineLines = (lines, lineNumbers) => { ...@@ -197,7 +197,7 @@ export const findIndexInInlineLines = (lines, lineNumbers) => {
const { oldLineNumber, newLineNumber } = lineNumbers; const { oldLineNumber, newLineNumber } = lineNumbers;
return lines.findIndex( return lines.findIndex(
line => line.old_line === oldLineNumber && line.new_line === newLineNumber, (line) => line.old_line === oldLineNumber && line.new_line === newLineNumber,
); );
}; };
...@@ -370,7 +370,7 @@ export function prepareLineForRenamedFile({ line, diffFile, index = 0 }) { ...@@ -370,7 +370,7 @@ export function prepareLineForRenamedFile({ line, diffFile, index = 0 }) {
function prepareDiffFileLines(file) { function prepareDiffFileLines(file) {
const inlineLines = file[INLINE_DIFF_LINES_KEY]; const inlineLines = file[INLINE_DIFF_LINES_KEY];
inlineLines.forEach(line => prepareLine(line, file)); // WARNING: In-Place Mutations! inlineLines.forEach((line) => prepareLine(line, file)); // WARNING: In-Place Mutations!
Object.assign(file, { Object.assign(file, {
inlineLinesCount: inlineLines.length, inlineLinesCount: inlineLines.length,
...@@ -424,7 +424,7 @@ export function getDiffPositionByLineCode(diffFiles) { ...@@ -424,7 +424,7 @@ export function getDiffPositionByLineCode(diffFiles) {
let lines = []; let lines = [];
lines = diffFiles.reduce((acc, diffFile) => { lines = diffFiles.reduce((acc, diffFile) => {
diffFile[INLINE_DIFF_LINES_KEY].forEach(line => { diffFile[INLINE_DIFF_LINES_KEY].forEach((line) => {
acc.push({ file: diffFile, line }); acc.push({ file: diffFile, line });
}); });
...@@ -471,21 +471,21 @@ export function isDiscussionApplicableToLine({ discussion, diffPosition, latestD ...@@ -471,21 +471,21 @@ export function isDiscussionApplicableToLine({ discussion, diffPosition, latestD
...(discussion.positions || []), ...(discussion.positions || []),
]; ];
const removeLineRange = position => { const removeLineRange = (position) => {
const { line_range: pNotUsed, ...positionNoLineRange } = position; const { line_range: pNotUsed, ...positionNoLineRange } = position;
return positionNoLineRange; return positionNoLineRange;
}; };
return discussionPositions return discussionPositions
.map(removeLineRange) .map(removeLineRange)
.some(position => isEqual(position, diffPositionCopy)); .some((position) => isEqual(position, diffPositionCopy));
} }
// eslint-disable-next-line // eslint-disable-next-line
return latestDiff && discussion.active && line_code === discussion.line_code; return latestDiff && discussion.active && line_code === discussion.line_code;
} }
export const getLowestSingleFolder = folder => { export const getLowestSingleFolder = (folder) => {
const getFolder = (blob, start = []) => const getFolder = (blob, start = []) =>
blob.tree.reduce( blob.tree.reduce(
(acc, file) => { (acc, file) => {
...@@ -517,8 +517,8 @@ export const getLowestSingleFolder = folder => { ...@@ -517,8 +517,8 @@ export const getLowestSingleFolder = folder => {
}; };
}; };
export const flattenTree = tree => { export const flattenTree = (tree) => {
const flatten = blobTree => const flatten = (blobTree) =>
blobTree.reduce((acc, file) => { blobTree.reduce((acc, file) => {
const blob = file; const blob = file;
let treeToFlatten = blob.tree; let treeToFlatten = blob.tree;
...@@ -540,7 +540,7 @@ export const flattenTree = tree => { ...@@ -540,7 +540,7 @@ export const flattenTree = tree => {
return flatten(tree); return flatten(tree);
}; };
export const generateTreeList = files => { export const generateTreeList = (files) => {
const { treeEntries, tree } = files.reduce( const { treeEntries, tree } = files.reduce(
(acc, file) => { (acc, file) => {
const split = file.new_path.split('/'); const split = file.new_path.split('/');
...@@ -590,8 +590,8 @@ export const generateTreeList = files => { ...@@ -590,8 +590,8 @@ export const generateTreeList = files => {
return { treeEntries, tree: flattenTree(tree) }; return { treeEntries, tree: flattenTree(tree) };
}; };
export const getDiffMode = diffFile => { export const getDiffMode = (diffFile) => {
const diffModeKey = Object.keys(diffModes).find(key => diffFile[`${key}_file`]); const diffModeKey = Object.keys(diffModes).find((key) => diffFile[`${key}_file`]);
return ( return (
diffModes[diffModeKey] || diffModes[diffModeKey] ||
(diffFile.viewer && (diffFile.viewer &&
...@@ -639,11 +639,11 @@ export const convertExpandLines = ({ ...@@ -639,11 +639,11 @@ export const convertExpandLines = ({
return lines; return lines;
}; };
export const idleCallback = cb => requestIdleCallback(cb); export const idleCallback = (cb) => requestIdleCallback(cb);
function getLinesFromFileByLineCode(file, lineCode) { function getLinesFromFileByLineCode(file, lineCode) {
const inlineLines = file[INLINE_DIFF_LINES_KEY]; const inlineLines = file[INLINE_DIFF_LINES_KEY];
const matchesCode = line => line.line_code === lineCode; const matchesCode = (line) => line.line_code === lineCode;
return inlineLines.filter(matchesCode); return inlineLines.filter(matchesCode);
} }
...@@ -652,15 +652,15 @@ export const updateLineInFile = (selectedFile, lineCode, updateFn) => { ...@@ -652,15 +652,15 @@ export const updateLineInFile = (selectedFile, lineCode, updateFn) => {
getLinesFromFileByLineCode(selectedFile, lineCode).forEach(updateFn); getLinesFromFileByLineCode(selectedFile, lineCode).forEach(updateFn);
}; };
export const allDiscussionWrappersExpanded = diff => { export const allDiscussionWrappersExpanded = (diff) => {
let discussionsExpanded = true; let discussionsExpanded = true;
const changeExpandedResult = line => { const changeExpandedResult = (line) => {
if (line && line.discussions.length) { if (line && line.discussions.length) {
discussionsExpanded = discussionsExpanded && line.discussionsExpanded; discussionsExpanded = discussionsExpanded && line.discussionsExpanded;
} }
}; };
diff[INLINE_DIFF_LINES_KEY].forEach(line => { diff[INLINE_DIFF_LINES_KEY].forEach((line) => {
changeExpandedResult(line); changeExpandedResult(line);
}); });
......
...@@ -8,8 +8,8 @@ import { getDerivedMergeRequestInformation } from './merge_request'; ...@@ -8,8 +8,8 @@ import { getDerivedMergeRequestInformation } from './merge_request';
import { uuids } from './uuids'; import { uuids } from './uuids';
function fileSymlinkInformation(file, fileList) { function fileSymlinkInformation(file, fileList) {
const duplicates = fileList.filter(iteratedFile => iteratedFile.file_hash === file.file_hash); const duplicates = fileList.filter((iteratedFile) => iteratedFile.file_hash === file.file_hash);
const includesSymlink = duplicates.some(iteratedFile => { const includesSymlink = duplicates.some((iteratedFile) => {
return [iteratedFile.a_mode, iteratedFile.b_mode].includes(DIFF_FILE_SYMLINK_MODE); return [iteratedFile.a_mode, iteratedFile.b_mode].includes(DIFF_FILE_SYMLINK_MODE);
}); });
const brokenSymlinkScenario = duplicates.length > 1 && includesSymlink; const brokenSymlinkScenario = duplicates.length > 1 && includesSymlink;
......
...@@ -2,7 +2,7 @@ import { sortTree } from '~/ide/stores/utils'; ...@@ -2,7 +2,7 @@ import { sortTree } from '~/ide/stores/utils';
import { generateTreeList } from '../store/utils'; import { generateTreeList } from '../store/utils';
// eslint-disable-next-line no-restricted-globals // eslint-disable-next-line no-restricted-globals
self.addEventListener('message', e => { self.addEventListener('message', (e) => {
const { data } = e; const { data } = e;
if (data === undefined) { if (data === undefined) {
......
...@@ -6,7 +6,7 @@ class DirtySubmitCollection { ...@@ -6,7 +6,7 @@ class DirtySubmitCollection {
this.dirtySubmits = []; this.dirtySubmits = [];
this.forms.forEach(form => this.dirtySubmits.push(new DirtySubmitForm(form))); this.forms.forEach((form) => this.dirtySubmits.push(new DirtySubmitForm(form)));
} }
} }
......
...@@ -22,10 +22,10 @@ class DirtySubmitForm { ...@@ -22,10 +22,10 @@ class DirtySubmitForm {
registerListeners() { registerListeners() {
const getThrottledHandlerForInput = memoize(() => const getThrottledHandlerForInput = memoize(() =>
throttle(event => this.updateDirtyInput(event), DirtySubmitForm.THROTTLE_DURATION), throttle((event) => this.updateDirtyInput(event), DirtySubmitForm.THROTTLE_DURATION),
); );
const throttledUpdateDirtyInput = event => { const throttledUpdateDirtyInput = (event) => {
const throttledHandler = getThrottledHandlerForInput(event.target.name); const throttledHandler = getThrottledHandlerForInput(event.target.name);
throttledHandler(event); throttledHandler(event);
}; };
...@@ -33,7 +33,7 @@ class DirtySubmitForm { ...@@ -33,7 +33,7 @@ class DirtySubmitForm {
this.form.addEventListener('input', throttledUpdateDirtyInput); this.form.addEventListener('input', throttledUpdateDirtyInput);
this.form.addEventListener('change', throttledUpdateDirtyInput); this.form.addEventListener('change', throttledUpdateDirtyInput);
$(this.form).on('change.select2', throttledUpdateDirtyInput); $(this.form).on('change.select2', throttledUpdateDirtyInput);
this.form.addEventListener('submit', event => this.formSubmit(event)); this.form.addEventListener('submit', (event) => this.formSubmit(event));
} }
updateDirtyInput(event) { updateDirtyInput(event) {
...@@ -58,7 +58,7 @@ class DirtySubmitForm { ...@@ -58,7 +58,7 @@ class DirtySubmitForm {
toggleSubmission() { toggleSubmission() {
this.isDisabled = this.dirtyInputs.length === 0; this.isDisabled = this.dirtyInputs.length === 0;
this.submits.forEach(element => { this.submits.forEach((element) => {
element.disabled = this.isDisabled; element.disabled = this.isDisabled;
}); });
} }
......
...@@ -68,7 +68,7 @@ class DropDown { ...@@ -68,7 +68,7 @@ class DropDown {
removeSelectedClasses() { removeSelectedClasses() {
const items = this.items || this.getItems(); const items = this.items || this.getItems();
items.forEach(item => item.classList.remove(SELECTED_CLASS)); items.forEach((item) => item.classList.remove(SELECTED_CLASS));
} }
addEvents() { addEvents() {
...@@ -162,7 +162,7 @@ class DropDown { ...@@ -162,7 +162,7 @@ class DropDown {
static setImagesSrc(template) { static setImagesSrc(template) {
const images = [...template.querySelectorAll('img[data-src]')]; const images = [...template.querySelectorAll('img[data-src]')];
images.forEach(image => { images.forEach((image) => {
const img = image; const img = image;
img.src = img.getAttribute('data-src'); img.src = img.getAttribute('data-src');
......
...@@ -28,7 +28,7 @@ class DropLab { ...@@ -28,7 +28,7 @@ class DropLab {
} }
destroy() { destroy() {
this.hooks.forEach(hook => hook.destroy()); this.hooks.forEach((hook) => hook.destroy());
this.hooks = []; this.hooks = [];
this.removeEvents(); this.removeEvents();
} }
...@@ -51,7 +51,7 @@ class DropLab { ...@@ -51,7 +51,7 @@ class DropLab {
} }
processData(trigger, data, methodName) { processData(trigger, data, methodName) {
this.hooks.forEach(hook => { this.hooks.forEach((hook) => {
if (Array.isArray(trigger)) hook.list[methodName](trigger); if (Array.isArray(trigger)) hook.list[methodName](trigger);
if (hook.trigger.id === trigger) hook.list[methodName](data); if (hook.trigger.id === trigger) hook.list[methodName](data);
...@@ -70,7 +70,7 @@ class DropLab { ...@@ -70,7 +70,7 @@ class DropLab {
if (utils.isDropDownParts(thisTag, this.hooks)) return; if (utils.isDropDownParts(thisTag, this.hooks)) return;
if (utils.isDropDownParts(e.target, this.hooks)) return; if (utils.isDropDownParts(e.target, this.hooks)) return;
this.hooks.forEach(hook => hook.list.hide()); this.hooks.forEach((hook) => hook.list.hide());
} }
removeEvents() { removeEvents() {
...@@ -115,7 +115,7 @@ class DropLab { ...@@ -115,7 +115,7 @@ class DropLab {
} }
addHooks(hooks, plugins, config) { addHooks(hooks, plugins, config) {
hooks.forEach(hook => this.addHook(hook, null, plugins, config)); hooks.forEach((hook) => this.addHook(hook, null, plugins, config));
return this; return this;
} }
...@@ -147,7 +147,7 @@ class DropLab { ...@@ -147,7 +147,7 @@ class DropLab {
this.fireReady(); this.fireReady();
this.queuedData.forEach(data => this.addData(data)); this.queuedData.forEach((data) => this.addData(data));
this.queuedData = []; this.queuedData = [];
return this; return this;
......
...@@ -14,7 +14,7 @@ class HookButton extends Hook { ...@@ -14,7 +14,7 @@ class HookButton extends Hook {
} }
addPlugins() { addPlugins() {
this.plugins.forEach(plugin => plugin.init(this)); this.plugins.forEach((plugin) => plugin.init(this));
} }
clicked(e) { clicked(e) {
...@@ -44,7 +44,7 @@ class HookButton extends Hook { ...@@ -44,7 +44,7 @@ class HookButton extends Hook {
} }
removePlugins() { removePlugins() {
this.plugins.forEach(plugin => plugin.destroy()); this.plugins.forEach((plugin) => plugin.destroy());
} }
destroy() { destroy() {
......
...@@ -14,7 +14,7 @@ class HookInput extends Hook { ...@@ -14,7 +14,7 @@ class HookInput extends Hook {
} }
addPlugins() { addPlugins() {
this.plugins.forEach(plugin => plugin.init(this)); this.plugins.forEach((plugin) => plugin.init(this));
} }
addEvents() { addEvents() {
...@@ -101,7 +101,7 @@ class HookInput extends Hook { ...@@ -101,7 +101,7 @@ class HookInput extends Hook {
} }
removePlugins() { removePlugins() {
this.plugins.forEach(plugin => plugin.destroy()); this.plugins.forEach((plugin) => plugin.destroy());
} }
destroy() { destroy() {
......
...@@ -43,7 +43,7 @@ const Ajax = { ...@@ -43,7 +43,7 @@ const Ajax = {
return AjaxCache.retrieve(config.endpoint) return AjaxCache.retrieve(config.endpoint)
.then(self.preprocessing.bind(null, config)) .then(self.preprocessing.bind(null, config))
.then(data => self._loadData(data, config, self)) .then((data) => self._loadData(data, config, self))
.catch(config.onError); .catch(config.onError);
}, },
destroy: function () { destroy: function () {
......
...@@ -63,7 +63,7 @@ const AjaxFilter = { ...@@ -63,7 +63,7 @@ const AjaxFilter = {
params[config.searchKey] = searchValue; params[config.searchKey] = searchValue;
var url = config.endpoint + this.buildParams(params); var url = config.endpoint + this.buildParams(params);
return AjaxCache.retrieve(url) return AjaxCache.retrieve(url)
.then(data => { .then((data) => {
this._loadData(data, config); this._loadData(data, config);
if (config.onLoadingFinished) { if (config.onLoadingFinished) {
config.onLoadingFinished(data); config.onLoadingFinished(data);
......
...@@ -27,7 +27,7 @@ const InputSetter = { ...@@ -27,7 +27,7 @@ const InputSetter = {
if (!Array.isArray(this.config)) this.config = [this.config]; if (!Array.isArray(this.config)) this.config = [this.config];
this.config.forEach(config => this.setInput(config, selectedItem)); this.config.forEach((config) => this.setInput(config, selectedItem));
}, },
setInput(config, selectedItem) { setInput(config, selectedItem) {
......
...@@ -55,9 +55,9 @@ class DueDateSelect { ...@@ -55,9 +55,9 @@ class DueDateSelect {
field: $dueDateInput.get(0), field: $dueDateInput.get(0),
theme: 'gitlab-theme', theme: 'gitlab-theme',
format: 'yyyy-mm-dd', format: 'yyyy-mm-dd',
parse: dateString => parsePikadayDate(dateString), parse: (dateString) => parsePikadayDate(dateString),
toString: date => pikadayToString(date), toString: (date) => pikadayToString(date),
onSelect: dateText => { onSelect: (dateText) => {
$dueDateInput.val(calendar.toString(dateText)); $dueDateInput.val(calendar.toString(dateText));
if (this.$dropdown.hasClass('js-issue-boards-due-date')) { if (this.$dropdown.hasClass('js-issue-boards-due-date')) {
...@@ -76,7 +76,7 @@ class DueDateSelect { ...@@ -76,7 +76,7 @@ class DueDateSelect {
} }
initRemoveDueDate() { initRemoveDueDate() {
this.$block.on('click', '.js-remove-due-date', e => { this.$block.on('click', '.js-remove-due-date', (e) => {
const calendar = this.$datePicker.data('pikaday'); const calendar = this.$datePicker.data('pikaday');
e.preventDefault(); e.preventDefault();
...@@ -103,7 +103,7 @@ class DueDateSelect { ...@@ -103,7 +103,7 @@ class DueDateSelect {
if (this.rawSelectedDate.length) { if (this.rawSelectedDate.length) {
// Construct Date object manually to avoid buggy dateString support within Date constructor // Construct Date object manually to avoid buggy dateString support within Date constructor
const dateArray = this.rawSelectedDate.split('-').map(v => parseInt(v, 10)); const dateArray = this.rawSelectedDate.split('-').map((v) => parseInt(v, 10));
const dateObj = new Date(dateArray[0], dateArray[1] - 1, dateArray[2]); const dateObj = new Date(dateArray[0], dateArray[1] - 1, dateArray[2]);
this.displayedDate = dateFormat(dateObj, 'mmm d, yyyy'); this.displayedDate = dateFormat(dateObj, 'mmm d, yyyy');
} else { } else {
...@@ -182,8 +182,8 @@ export default class DueDateSelectors { ...@@ -182,8 +182,8 @@ export default class DueDateSelectors {
theme: 'gitlab-theme animate-picker', theme: 'gitlab-theme animate-picker',
format: 'yyyy-mm-dd', format: 'yyyy-mm-dd',
container: $datePicker.parent().get(0), container: $datePicker.parent().get(0),
parse: dateString => parsePikadayDate(dateString), parse: (dateString) => parsePikadayDate(dateString),
toString: date => pikadayToString(date), toString: (date) => pikadayToString(date),
onSelect(dateText) { onSelect(dateText) {
$datePicker.val(calendar.toString(dateText)); $datePicker.val(calendar.toString(dateText));
}, },
...@@ -195,7 +195,7 @@ export default class DueDateSelectors { ...@@ -195,7 +195,7 @@ export default class DueDateSelectors {
$datePicker.data('pikaday', calendar); $datePicker.data('pikaday', calendar);
}); });
$('.js-clear-due-date,.js-clear-start-date').on('click', e => { $('.js-clear-due-date,.js-clear-start-date').on('click', (e) => {
e.preventDefault(); e.preventDefault();
const calendar = $(e.target).siblings('.datepicker').data('pikaday'); const calendar = $(e.target).siblings('.datepicker').data('pikaday');
calendar.setDate(null); calendar.setDate(null);
......
...@@ -24,7 +24,7 @@ export default class EditorLite { ...@@ -24,7 +24,7 @@ export default class EditorLite {
static setupMonacoTheme() { static setupMonacoTheme() {
const themeName = window.gon?.user_color_scheme || DEFAULT_THEME; const themeName = window.gon?.user_color_scheme || DEFAULT_THEME;
const theme = themes.find(t => t.name === themeName); const theme = themes.find((t) => t.name === themeName);
if (theme) monacoEditor.defineTheme(themeName, theme.data); if (theme) monacoEditor.defineTheme(themeName, theme.data);
monacoEditor.setTheme(theme ? themeName : DEFAULT_THEME); monacoEditor.setTheme(theme ? themeName : DEFAULT_THEME);
} }
...@@ -35,7 +35,7 @@ export default class EditorLite { ...@@ -35,7 +35,7 @@ export default class EditorLite {
const ext = `.${path.split('.').pop()}`; const ext = `.${path.split('.').pop()}`;
const language = monacoLanguages const language = monacoLanguages
.getLanguages() .getLanguages()
.find(lang => lang.extensions.indexOf(ext) !== -1); .find((lang) => lang.extensions.indexOf(ext) !== -1);
const id = language ? language.id : 'plaintext'; const id = language ? language.id : 'plaintext';
monacoEditor.setModelLanguage(model, id); monacoEditor.setModelLanguage(model, id);
} }
...@@ -51,7 +51,7 @@ export default class EditorLite { ...@@ -51,7 +51,7 @@ export default class EditorLite {
const promises = []; const promises = [];
const extensionsArray = typeof extensions === 'string' ? extensions.split(',') : extensions; const extensionsArray = typeof extensions === 'string' ? extensions.split(',') : extensions;
extensionsArray.forEach(ext => { extensionsArray.forEach((ext) => {
const prefix = ext.includes('/') ? '' : 'editor/'; const prefix = ext.includes('/') ? '' : 'editor/';
const trimmedExt = ext.replace(/^\//, '').trim(); const trimmedExt = ext.replace(/^\//, '').trim();
EditorLite.pushToImportsArray(promises, `~/${prefix}${trimmedExt}`); EditorLite.pushToImportsArray(promises, `~/${prefix}${trimmedExt}`);
...@@ -66,7 +66,7 @@ export default class EditorLite { ...@@ -66,7 +66,7 @@ export default class EditorLite {
} }
const isClassInstance = source.constructor.prototype !== Object.prototype; const isClassInstance = source.constructor.prototype !== Object.prototype;
const sanitizedSource = isClassInstance ? source.constructor.prototype : source; const sanitizedSource = isClassInstance ? source.constructor.prototype : source;
Object.getOwnPropertyNames(sanitizedSource).forEach(prop => { Object.getOwnPropertyNames(sanitizedSource).forEach((prop) => {
if (prop !== 'constructor') { if (prop !== 'constructor') {
Object.assign(inst, { [prop]: source[prop] }); Object.assign(inst, { [prop]: source[prop] });
} }
...@@ -110,17 +110,17 @@ export default class EditorLite { ...@@ -110,17 +110,17 @@ export default class EditorLite {
}); });
instance.setModel(model); instance.setModel(model);
instance.onDidDispose(() => { instance.onDidDispose(() => {
const index = this.instances.findIndex(inst => inst === instance); const index = this.instances.findIndex((inst) => inst === instance);
this.instances.splice(index, 1); this.instances.splice(index, 1);
model.dispose(); model.dispose();
}); });
instance.updateModelLanguage = path => EditorLite.updateModelLanguage(path, instance); instance.updateModelLanguage = (path) => EditorLite.updateModelLanguage(path, instance);
instance.use = args => this.use(args, instance); instance.use = (args) => this.use(args, instance);
EditorLite.loadExtensions(extensions, instance) EditorLite.loadExtensions(extensions, instance)
.then(modules => { .then((modules) => {
if (modules) { if (modules) {
modules.forEach(module => { modules.forEach((module) => {
instance.use(module.default); instance.use(module.default);
}); });
} }
...@@ -128,7 +128,7 @@ export default class EditorLite { ...@@ -128,7 +128,7 @@ export default class EditorLite {
.then(() => { .then(() => {
el.dispatchEvent(new Event('editor-ready')); el.dispatchEvent(new Event('editor-ready'));
}) })
.catch(e => { .catch((e) => {
throw e; throw e;
}); });
...@@ -137,20 +137,20 @@ export default class EditorLite { ...@@ -137,20 +137,20 @@ export default class EditorLite {
} }
dispose() { dispose() {
this.instances.forEach(instance => instance.dispose()); this.instances.forEach((instance) => instance.dispose());
} }
use(exts = [], instance = null) { use(exts = [], instance = null) {
const extensions = Array.isArray(exts) ? exts : [exts]; const extensions = Array.isArray(exts) ? exts : [exts];
const initExtensions = inst => { const initExtensions = (inst) => {
extensions.forEach(extension => { extensions.forEach((extension) => {
EditorLite.mixIntoInstance(extension, inst); EditorLite.mixIntoInstance(extension, inst);
}); });
}; };
if (instance) { if (instance) {
initExtensions(instance); initExtensions(instance);
} else { } else {
this.instances.forEach(inst => { this.instances.forEach((inst) => {
initExtensions(inst); initExtensions(inst);
}); });
} }
......
...@@ -76,7 +76,7 @@ export class EditorMarkdownExtension extends EditorLiteExtension { ...@@ -76,7 +76,7 @@ export class EditorMarkdownExtension extends EditorLiteExtension {
if (textLines.length > 1) { if (textLines.length > 1) {
// Multi-line selection // Multi-line selection
lineShift = textLines.findIndex(line => line.indexOf(toSelect) !== -1); lineShift = textLines.findIndex((line) => line.indexOf(toSelect) !== -1);
newStartLineNumber = currentSelection.startLineNumber + lineShift; newStartLineNumber = currentSelection.startLineNumber + lineShift;
newStartColumn = textLines[lineShift].indexOf(toSelect) + 1; newStartColumn = textLines[lineShift].indexOf(toSelect) + 1;
} else { } else {
......
export const clearDomElement = el => { export const clearDomElement = (el) => {
if (!el || !el.firstChild) return; if (!el || !el.firstChild) return;
while (el.firstChild) { while (el.firstChild) {
......
...@@ -35,7 +35,7 @@ async function prepareEmojiMap() { ...@@ -35,7 +35,7 @@ async function prepareEmojiMap() {
validEmojiNames = [...Object.keys(emojiMap), ...Object.keys(emojiAliases)]; validEmojiNames = [...Object.keys(emojiMap), ...Object.keys(emojiAliases)];
Object.keys(emojiMap).forEach(name => { Object.keys(emojiMap).forEach((name) => {
emojiMap[name].aliases = []; emojiMap[name].aliases = [];
emojiMap[name].name = name; emojiMap[name].name = name;
}); });
...@@ -122,23 +122,23 @@ const searchMatchers = { ...@@ -122,23 +122,23 @@ const searchMatchers = {
const searchPredicates = { const searchPredicates = {
// Search by name // Search by name
name: (matcher, query) => emoji => { name: (matcher, query) => (emoji) => {
const m = matcher(emoji.name, query); const m = matcher(emoji.name, query);
return [{ ...m, emoji, field: emoji.name }]; return [{ ...m, emoji, field: emoji.name }];
}, },
// Search by alias // Search by alias
alias: (matcher, query) => emoji => alias: (matcher, query) => (emoji) =>
emoji.aliases.map(alias => { emoji.aliases.map((alias) => {
const m = matcher(alias, query); const m = matcher(alias, query);
return { ...m, emoji, field: alias }; return { ...m, emoji, field: alias };
}), }),
// Search by description // Search by description
description: (matcher, query) => emoji => { description: (matcher, query) => (emoji) => {
const m = matcher(emoji.d, query); const m = matcher(emoji.d, query);
return [{ ...m, emoji, field: emoji.d }]; return [{ ...m, emoji, field: emoji.d }];
}, },
// Search by unicode value (always exact) // Search by unicode value (always exact)
unicode: (matcher, query) => emoji => { unicode: (matcher, query) => (emoji) => {
return [{ emoji, field: emoji.e, success: emoji.e === query }]; return [{ emoji, field: emoji.e, success: emoji.e === query }];
}, },
}; };
...@@ -196,18 +196,18 @@ export function searchEmoji(query, opts) { ...@@ -196,18 +196,18 @@ export function searchEmoji(query, opts) {
} }
const matcher = searchMatchers[match] || searchMatchers.exact; const matcher = searchMatchers[match] || searchMatchers.exact;
const predicates = fields.map(f => searchPredicates[f](matcher, query)); const predicates = fields.map((f) => searchPredicates[f](matcher, query));
const results = Object.values(emojiMap) const results = Object.values(emojiMap)
.flatMap(emoji => predicates.flatMap(predicate => predicate(emoji))) .flatMap((emoji) => predicates.flatMap((predicate) => predicate(emoji)))
.filter(r => r.success); .filter((r) => r.success);
// Fallback to question mark for unknown emojis // Fallback to question mark for unknown emojis
if (fallback && results.length === 0) { if (fallback && results.length === 0) {
return raw ? [{ emoji: fallbackEmoji }] : [fallbackEmoji]; return raw ? [{ emoji: fallbackEmoji }] : [fallbackEmoji];
} }
return raw ? results : results.map(r => r.emoji); return raw ? results : results.map((r) => r.emoji);
} }
let emojiCategoryMap; let emojiCategoryMap;
...@@ -223,7 +223,7 @@ export function getEmojiCategoryMap() { ...@@ -223,7 +223,7 @@ export function getEmojiCategoryMap() {
symbols: [], symbols: [],
flags: [], flags: [],
}; };
Object.keys(emojiMap).forEach(name => { Object.keys(emojiMap).forEach((name) => {
const emoji = emojiMap[name]; const emoji = emojiMap[name];
if (emojiCategoryMap[emoji.c]) { if (emojiCategoryMap[emoji.c]) {
emojiCategoryMap[emoji.c].push(name); emojiCategoryMap[emoji.c].push(name);
......
...@@ -9,7 +9,7 @@ export default class NoEmojiValidator extends InputValidator { ...@@ -9,7 +9,7 @@ export default class NoEmojiValidator extends InputValidator {
const container = opts.container || ''; const container = opts.container || '';
this.noEmojiEmelents = document.querySelectorAll(`${container} .js-block-emoji`); this.noEmojiEmelents = document.querySelectorAll(`${container} .js-block-emoji`);
this.noEmojiEmelents.forEach(element => this.noEmojiEmelents.forEach((element) =>
element.addEventListener('input', this.eventHandler.bind(this)), element.addEventListener('input', this.eventHandler.bind(this)),
); );
} }
......
...@@ -33,7 +33,7 @@ const tone5 = 127999; // parseInt('1F3FF', 16) ...@@ -33,7 +33,7 @@ const tone5 = 127999; // parseInt('1F3FF', 16)
function isSkinToneComboEmoji(emojiUnicode) { function isSkinToneComboEmoji(emojiUnicode) {
return ( return (
emojiUnicode.length > 2 && emojiUnicode.length > 2 &&
Array.from(emojiUnicode).some(char => { Array.from(emojiUnicode).some((char) => {
const cp = char.codePointAt(0); const cp = char.codePointAt(0);
return cp >= tone1 && cp <= tone5; return cp >= tone1 && cp <= tone5;
}) })
...@@ -60,7 +60,7 @@ const personEndCodePoint = 128105; // parseInt('1F469', 16) ...@@ -60,7 +60,7 @@ const personEndCodePoint = 128105; // parseInt('1F469', 16)
function isPersonZwjEmoji(emojiUnicode) { function isPersonZwjEmoji(emojiUnicode) {
let hasPersonEmoji = false; let hasPersonEmoji = false;
let hasZwj = false; let hasZwj = false;
Array.from(emojiUnicode).forEach(character => { Array.from(emojiUnicode).forEach((character) => {
const cp = character.codePointAt(0); const cp = character.codePointAt(0);
if (cp === zwj) { if (cp === zwj) {
hasZwj = true; hasZwj = true;
......
...@@ -89,9 +89,9 @@ function generateUnicodeSupportMap(testMap) { ...@@ -89,9 +89,9 @@ function generateUnicodeSupportMap(testMap) {
ctx.font = `${fontSize}px "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"`; ctx.font = `${fontSize}px "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"`;
// Write each emoji to the canvas vertically // Write each emoji to the canvas vertically
let writeIndex = 0; let writeIndex = 0;
testMapKeys.forEach(testKey => { testMapKeys.forEach((testKey) => {
const testEntry = testMap[testKey]; const testEntry = testMap[testKey];
[].concat(testEntry).forEach(emojiUnicode => { [].concat(testEntry).forEach((emojiUnicode) => {
ctx.fillText(emojiUnicode, 0, writeIndex * fontSize + fontSize / 2); ctx.fillText(emojiUnicode, 0, writeIndex * fontSize + fontSize / 2);
writeIndex += 1; writeIndex += 1;
}); });
...@@ -100,11 +100,11 @@ function generateUnicodeSupportMap(testMap) { ...@@ -100,11 +100,11 @@ function generateUnicodeSupportMap(testMap) {
// Read from the canvas // Read from the canvas
const resultMap = {}; const resultMap = {};
let readIndex = 0; let readIndex = 0;
testMapKeys.forEach(testKey => { testMapKeys.forEach((testKey) => {
const testEntry = testMap[testKey]; const testEntry = testMap[testKey];
// This needs to be a `reduce` instead of `every` because we need to // This needs to be a `reduce` instead of `every` because we need to
// keep the `readIndex` in sync from the writes by running all entries // keep the `readIndex` in sync from the writes by running all entries
const isTestSatisfied = [].concat(testEntry).reduce(isSatisfied => { const isTestSatisfied = [].concat(testEntry).reduce((isSatisfied) => {
// Sample along the vertical-middle for a couple of characters // Sample along the vertical-middle for a couple of characters
const imageData = ctx.getImageData(0, readIndex * fontSize + fontSize / 2, 2 * fontSize, 1) const imageData = ctx.getImageData(0, readIndex * fontSize + fontSize / 2, 2 * fontSize, 1)
.data; .data;
......
...@@ -226,7 +226,7 @@ export default { ...@@ -226,7 +226,7 @@ export default {
{ deep: true }, { deep: true },
); );
const combinedActions = (manualActions || []).concat(scheduledActions || []); const combinedActions = (manualActions || []).concat(scheduledActions || []);
return combinedActions.map(action => ({ return combinedActions.map((action) => ({
...action, ...action,
name: action.name, name: action.name,
})); }));
......
...@@ -55,7 +55,7 @@ export default { ...@@ -55,7 +55,7 @@ export default {
retryUrl: this.retryUrl, retryUrl: this.retryUrl,
isLastDeployment: this.isLastDeployment, isLastDeployment: this.isLastDeployment,
}); });
eventHub.$on('rollbackEnvironment', environment => { eventHub.$on('rollbackEnvironment', (environment) => {
if (environment.id === this.environment.id) { if (environment.id === this.environment.id) {
this.isLoading = true; this.isLoading = true;
} }
......
...@@ -116,7 +116,7 @@ export default { ...@@ -116,7 +116,7 @@ export default {
this.service this.service
.getFolderContent(folder.folder_path) .getFolderContent(folder.folder_path)
.then(response => this.store.setfolderContent(folder, response.data.environments)) .then((response) => this.store.setfolderContent(folder, response.data.environments))
.then(() => this.store.updateEnvironmentProp(folder, 'isLoadingFolderContent', false)) .then(() => this.store.updateEnvironmentProp(folder, 'isLoadingFolderContent', false))
.catch(() => { .catch(() => {
Flash(s__('Environments|An error occurred while fetching the environments.')); Flash(s__('Environments|An error occurred while fetching the environments.'));
...@@ -130,7 +130,7 @@ export default { ...@@ -130,7 +130,7 @@ export default {
// We need to verify if any folder is open to also update it // We need to verify if any folder is open to also update it
const openFolders = this.store.getOpenFolders(); const openFolders = this.store.getOpenFolders();
if (openFolders.length) { if (openFolders.length) {
openFolders.forEach(folder => this.fetchChildEnvironments(folder)); openFolders.forEach((folder) => this.fetchChildEnvironments(folder));
} }
}, },
}, },
......
...@@ -67,7 +67,7 @@ export default { ...@@ -67,7 +67,7 @@ export default {
}, },
computed: { computed: {
sortedEnvironments() { sortedEnvironments() {
return this.sortEnvironments(this.environments).map(env => return this.sortEnvironments(this.environments).map((env) =>
this.shouldRenderFolderContent(env) this.shouldRenderFolderContent(env)
? { ...env, children: this.sortEnvironments(env.children) } ? { ...env, children: this.sortEnvironments(env.children) }
: env, : env,
...@@ -144,11 +144,11 @@ export default { ...@@ -144,11 +144,11 @@ export default {
* 5. Put folders first. * 5. Put folders first.
*/ */
return flow( return flow(
sortBy(env => (env.isFolder ? env.folderName : env.name)), sortBy((env) => (env.isFolder ? env.folderName : env.name)),
reverse, reverse,
sortBy(env => (env.last_deployment ? env.last_deployment.created_at : '0000')), sortBy((env) => (env.last_deployment ? env.last_deployment.created_at : '0000')),
reverse, reverse,
sortBy(env => (env.isFolder ? -1 : 1)), sortBy((env) => (env.isFolder ? -1 : 1)),
)(environments); )(environments);
}, },
changeCanaryWeight(model, weight) { changeCanaryWeight(model, weight) {
......
...@@ -64,7 +64,7 @@ export default { ...@@ -64,7 +64,7 @@ export default {
}, },
filterNilValues(obj) { filterNilValues(obj) {
return omitBy(obj, value => value === undefined || value === null); return omitBy(obj, (value) => value === undefined || value === null);
}, },
/** /**
...@@ -80,7 +80,7 @@ export default { ...@@ -80,7 +80,7 @@ export default {
// fetch new data // fetch new data
return this.service return this.service
.fetchEnvironments(this.requestData) .fetchEnvironments(this.requestData)
.then(response => { .then((response) => {
this.successCallback(response); this.successCallback(response);
this.poll.enable({ data: this.requestData, response }); this.poll.enable({ data: this.requestData, response });
}) })
...@@ -107,7 +107,7 @@ export default { ...@@ -107,7 +107,7 @@ export default {
this.service this.service
.postAction(endpoint) .postAction(endpoint)
.then(() => this.fetchEnvironments()) .then(() => this.fetchEnvironments())
.catch(err => { .catch((err) => {
this.isLoading = false; this.isLoading = false;
Flash(isFunction(errorMessage) ? errorMessage(err.response.data) : errorMessage); Flash(isFunction(errorMessage) ? errorMessage(err.response.data) : errorMessage);
}); });
...@@ -219,7 +219,7 @@ export default { ...@@ -219,7 +219,7 @@ export default {
data: this.requestData, data: this.requestData,
successCallback: this.successCallback, successCallback: this.successCallback,
errorCallback: this.errorCallback, errorCallback: this.errorCallback,
notificationCallback: isMakingRequest => { notificationCallback: (isMakingRequest) => {
this.isMakingRequest = isMakingRequest; this.isMakingRequest = isMakingRequest;
}, },
}); });
......
...@@ -46,9 +46,9 @@ export default class EnvironmentsStore { ...@@ -46,9 +46,9 @@ export default class EnvironmentsStore {
* @returns {Array} * @returns {Array}
*/ */
storeEnvironments(environments = []) { storeEnvironments(environments = []) {
const filteredEnvironments = environments.map(env => { const filteredEnvironments = environments.map((env) => {
const oldEnvironmentState = const oldEnvironmentState =
this.state.environments.find(element => { this.state.environments.find((element) => {
if (env.latest) { if (env.latest) {
return element.id === env.latest.id; return element.id === env.latest.id;
} }
...@@ -163,7 +163,7 @@ export default class EnvironmentsStore { ...@@ -163,7 +163,7 @@ export default class EnvironmentsStore {
* @return {Object} * @return {Object}
*/ */
setfolderContent(folder, environments) { setfolderContent(folder, environments) {
const updatedEnvironments = environments.map(env => { const updatedEnvironments = environments.map((env) => {
let updated = env; let updated = env;
if (env.latest) { if (env.latest) {
...@@ -192,7 +192,7 @@ export default class EnvironmentsStore { ...@@ -192,7 +192,7 @@ export default class EnvironmentsStore {
updateEnvironmentProp(environment, prop, newValue) { updateEnvironmentProp(environment, prop, newValue) {
const { environments } = this.state; const { environments } = this.state;
const updatedEnvironments = environments.map(env => { const updatedEnvironments = environments.map((env) => {
const updateEnv = { ...env }; const updateEnv = { ...env };
if (env.id === environment.id) { if (env.id === environment.id) {
updateEnv[prop] = newValue; updateEnv[prop] = newValue;
...@@ -207,6 +207,6 @@ export default class EnvironmentsStore { ...@@ -207,6 +207,6 @@ export default class EnvironmentsStore {
getOpenFolders() { getOpenFolders() {
const { environments } = this.state; const { environments } = this.state;
return environments.filter(env => env.isFolder && env.isOpen); return environments.filter((env) => env.isFolder && env.isOpen);
} }
} }
...@@ -87,7 +87,7 @@ export default { ...@@ -87,7 +87,7 @@ export default {
}; };
}, },
pollInterval: 2000, pollInterval: 2000,
update: data => data.project.sentryErrors.detailedError, update: (data) => data.project.sentryErrors.detailedError,
error: () => createFlash(__('Failed to load error details from Sentry.')), error: () => createFlash(__('Failed to load error details from Sentry.')),
result(res) { result(res) {
if (res.data.project?.sentryErrors?.detailedError) { if (res.data.project?.sentryErrors?.detailedError) {
...@@ -213,7 +213,7 @@ export default { ...@@ -213,7 +213,7 @@ export default {
this.errorStatus === errorStatus.RESOLVED ? errorStatus.UNRESOLVED : errorStatus.RESOLVED; this.errorStatus === errorStatus.RESOLVED ? errorStatus.UNRESOLVED : errorStatus.RESOLVED;
// eslint-disable-next-line promise/catch-or-return // eslint-disable-next-line promise/catch-or-return
this.updateResolveStatus({ endpoint: this.issueUpdatePath, status }).then(res => { this.updateResolveStatus({ endpoint: this.issueUpdatePath, status }).then((res) => {
this.closedIssueId = res.closed_issue_iid; this.closedIssueId = res.closed_issue_iid;
if (this.closedIssueId) { if (this.closedIssueId) {
this.isAlertVisible = true; this.isAlertVisible = true;
......
...@@ -11,7 +11,7 @@ export const setStatus = ({ commit }, status) => { ...@@ -11,7 +11,7 @@ export const setStatus = ({ commit }, status) => {
export const updateStatus = ({ commit }, { endpoint, redirectUrl, status }) => export const updateStatus = ({ commit }, { endpoint, redirectUrl, status }) =>
service service
.updateErrorStatus(endpoint, status) .updateErrorStatus(endpoint, status)
.then(resp => { .then((resp) => {
commit(types.SET_ERROR_STATUS, status); commit(types.SET_ERROR_STATUS, status);
if (redirectUrl) visitUrl(redirectUrl); if (redirectUrl) visitUrl(redirectUrl);
......
...@@ -6,7 +6,7 @@ import { __ } from '~/locale'; ...@@ -6,7 +6,7 @@ import { __ } from '~/locale';
let stackTracePoll; let stackTracePoll;
const stopPolling = poll => { const stopPolling = (poll) => {
if (poll) poll.stop(); if (poll) poll.stop();
}; };
......
export const stacktrace = state => export const stacktrace = (state) =>
state.stacktraceData.stack_trace_entries state.stacktraceData.stack_trace_entries
? state.stacktraceData.stack_trace_entries.reverse() ? state.stacktraceData.stack_trace_entries.reverse()
: []; : [];
...@@ -17,7 +17,7 @@ export default { ...@@ -17,7 +17,7 @@ export default {
return; return;
} }
// remove any existing item, then add it to the start of the list // remove any existing item, then add it to the start of the list
const recentSearches = state.recentSearches.filter(s => s !== searchTerm); const recentSearches = state.recentSearches.filter((s) => s !== searchTerm);
recentSearches.unshift(searchTerm); recentSearches.unshift(searchTerm);
// only keep the last 5 // only keep the last 5
state.recentSearches = recentSearches.slice(0, 5); state.recentSearches = recentSearches.slice(0, 5);
...@@ -60,7 +60,7 @@ export default { ...@@ -60,7 +60,7 @@ export default {
state.endpoint = endpoint; state.endpoint = endpoint;
}, },
[types.REMOVE_IGNORED_RESOLVED_ERRORS](state, error) { [types.REMOVE_IGNORED_RESOLVED_ERRORS](state, error) {
state.errors = state.errors.filter(err => err.id !== error); state.errors = state.errors.filter((err) => err.id !== error);
}, },
[types.SET_STATUS_FILTER](state, query) { [types.SET_STATUS_FILTER](state, query) {
state.statusFilter = query; state.statusFilter = query;
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* Tracks snowplow event when User clicks on error link to Sentry * Tracks snowplow event when User clicks on error link to Sentry
* @param {String} externalUrl that will be send as a property for the event * @param {String} externalUrl that will be send as a property for the event
*/ */
export const trackClickErrorLinkToSentryOptions = url => ({ export const trackClickErrorLinkToSentryOptions = (url) => ({
category: 'Error Tracking', category: 'Error Tracking',
action: 'click_error_link_to_sentry', action: 'click_error_link_to_sentry',
label: 'Error Link', label: 'Error Link',
...@@ -30,7 +30,7 @@ export const trackErrorDetailsViewsOptions = { ...@@ -30,7 +30,7 @@ export const trackErrorDetailsViewsOptions = {
/** /**
* Tracks snowplow event when error status is updated * Tracks snowplow event when error status is updated
*/ */
export const trackErrorStatusUpdateOptions = status => ({ export const trackErrorStatusUpdateOptions = (status) => ({
category: 'Error Tracking', category: 'Error Tracking',
action: `update_${status}_status`, action: `update_${status}_status`,
}); });
...@@ -63,7 +63,7 @@ export const updateSettings = ({ dispatch, state }) => { ...@@ -63,7 +63,7 @@ export const updateSettings = ({ dispatch, state }) => {
.then(() => { .then(() => {
refreshCurrentPage(); refreshCurrentPage();
}) })
.catch(err => { .catch((err) => {
dispatch('receiveSettingsError', err); dispatch('receiveSettingsError', err);
}); });
}; };
......
...@@ -2,12 +2,12 @@ import { isMatch } from 'lodash'; ...@@ -2,12 +2,12 @@ import { isMatch } from 'lodash';
import { __, s__, sprintf } from '~/locale'; import { __, s__, sprintf } from '~/locale';
import { getDisplayName } from '../utils'; import { getDisplayName } from '../utils';
export const hasProjects = state => Boolean(state.projects) && state.projects.length > 0; export const hasProjects = (state) => Boolean(state.projects) && state.projects.length > 0;
export const isProjectInvalid = (state, getters) => export const isProjectInvalid = (state, getters) =>
Boolean(state.selectedProject) && Boolean(state.selectedProject) &&
getters.hasProjects && getters.hasProjects &&
!state.projects.some(project => isMatch(state.selectedProject, project)); !state.projects.some((project) => isMatch(state.selectedProject, project));
export const dropdownLabel = (state, getters) => { export const dropdownLabel = (state, getters) => {
if (state.selectedProject !== null) { if (state.selectedProject !== null) {
...@@ -19,7 +19,7 @@ export const dropdownLabel = (state, getters) => { ...@@ -19,7 +19,7 @@ export const dropdownLabel = (state, getters) => {
return s__('ErrorTracking|Select project'); return s__('ErrorTracking|Select project');
}; };
export const invalidProjectLabel = state => { export const invalidProjectLabel = (state) => {
if (state.selectedProject) { if (state.selectedProject) {
return sprintf( return sprintf(
__('Project "%{name}" is no longer available. Select another project to continue.'), __('Project "%{name}" is no longer available. Select another project to continue.'),
...@@ -31,7 +31,7 @@ export const invalidProjectLabel = state => { ...@@ -31,7 +31,7 @@ export const invalidProjectLabel = state => {
return ''; return '';
}; };
export const projectSelectionLabel = state => { export const projectSelectionLabel = (state) => {
if (state.token) { if (state.token) {
return s__( return s__(
"ErrorTracking|Click 'Connect' to re-establish the connection to Sentry and activate the dropdown.", "ErrorTracking|Click 'Connect' to re-establish the connection to Sentry and activate the dropdown.",
......
...@@ -12,7 +12,7 @@ export default { ...@@ -12,7 +12,7 @@ export default {
.map(convertObjectPropsToCamelCase) .map(convertObjectPropsToCamelCase)
// The `pick` strips out extra properties returned from Sentry. // The `pick` strips out extra properties returned from Sentry.
// Such properties could be problematic later, e.g. when checking whether `projects` contains `selectedProject` // Such properties could be problematic later, e.g. when checking whether `projects` contains `selectedProject`
.map(project => pick(project, projectKeys)); .map((project) => pick(project, projectKeys));
}, },
[types.RESET_CONNECT](state) { [types.RESET_CONNECT](state) {
state.connectSuccessful = false; state.connectSuccessful = false;
......
...@@ -13,4 +13,4 @@ export const transformFrontendSettings = ({ apiHost, enabled, token, selectedPro ...@@ -13,4 +13,4 @@ export const transformFrontendSettings = ({ apiHost, enabled, token, selectedPro
return { api_host: apiHost || null, enabled, token: token || null, project }; return { api_host: apiHost || null, enabled, token: token || null, project };
}; };
export const getDisplayName = project => `${project.organizationName} | ${project.slug}`; export const getDisplayName = (project) => `${project.organizationName} | ${project.slug}`;
...@@ -2,7 +2,7 @@ import $ from 'jquery'; ...@@ -2,7 +2,7 @@ import $ from 'jquery';
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
export default () => { export default () => {
$('.js-experiment-feature-toggle').on('change', e => { $('.js-experiment-feature-toggle').on('change', (e) => {
const el = e.target; const el = e.target;
Cookies.set(el.name, el.value, { Cookies.set(el.name, el.value, {
......
...@@ -122,7 +122,7 @@ export default { ...@@ -122,7 +122,7 @@ export default {
:submit-text="__('Save changes')" :submit-text="__('Save changes')"
:active="active" :active="active"
:version="version" :version="version"
@handleSubmit="data => updateFeatureFlag(data)" @handleSubmit="(data) => updateFeatureFlag(data)"
/> />
</template> </template>
</div> </div>
......
...@@ -133,7 +133,7 @@ export default { ...@@ -133,7 +133,7 @@ export default {
}, },
updateFeatureFlagOptions(parameters) { updateFeatureFlagOptions(parameters) {
const queryString = Object.keys(parameters) const queryString = Object.keys(parameters)
.map(parameter => { .map((parameter) => {
const value = parameters[parameter]; const value = parameters[parameter];
return `${parameter}=${encodeURIComponent(value)}`; return `${parameter}=${encodeURIComponent(value)}`;
}) })
......
...@@ -100,7 +100,7 @@ export default { ...@@ -100,7 +100,7 @@ export default {
return featureFlag.iid ? `^${featureFlag.iid}` : ''; return featureFlag.iid ? `^${featureFlag.iid}` : '';
}, },
canDeleteFlag(flag) { canDeleteFlag(flag) {
return !this.permissions || (flag.scopes || []).every(scope => scope.can_update); return !this.permissions || (flag.scopes || []).every((scope) => scope.can_update);
}, },
setDeleteModalData(featureFlag) { setDeleteModalData(featureFlag) {
this.deleteFeatureFlagUrl = featureFlag.destroy_path; this.deleteFeatureFlagUrl = featureFlag.destroy_path;
......
...@@ -117,7 +117,7 @@ export default { ...@@ -117,7 +117,7 @@ export default {
formDescription: this.description, formDescription: this.description,
// operate on a clone to avoid mutating props // operate on a clone to avoid mutating props
formScopes: this.scopes.map(s => ({ ...s })), formScopes: this.scopes.map((s) => ({ ...s })),
formStrategies: cloneDeep(this.strategies), formStrategies: cloneDeep(this.strategies),
newScope: '', newScope: '',
...@@ -125,13 +125,13 @@ export default { ...@@ -125,13 +125,13 @@ export default {
}, },
computed: { computed: {
filteredScopes() { filteredScopes() {
return this.formScopes.filter(scope => !scope.shouldBeDestroyed); return this.formScopes.filter((scope) => !scope.shouldBeDestroyed);
}, },
filteredStrategies() { filteredStrategies() {
return this.formStrategies.filter(s => !s.shouldBeDestroyed); return this.formStrategies.filter((s) => !s.shouldBeDestroyed);
}, },
canUpdateFlag() { canUpdateFlag() {
return !this.permissionsFlag || (this.formScopes || []).every(scope => scope.canUpdate); return !this.permissionsFlag || (this.formScopes || []).every((scope) => scope.canUpdate);
}, },
permissionsFlag() { permissionsFlag() {
return this.glFeatures.featureFlagPermissions; return this.glFeatures.featureFlagPermissions;
...@@ -167,7 +167,7 @@ export default { ...@@ -167,7 +167,7 @@ export default {
if (isNumber(s.id)) { if (isNumber(s.id)) {
Vue.set(s, 'shouldBeDestroyed', true); Vue.set(s, 'shouldBeDestroyed', true);
} else { } else {
this.formStrategies = this.formStrategies.filter(strategy => strategy !== s); this.formStrategies = this.formStrategies.filter((strategy) => strategy !== s);
} }
}, },
...@@ -188,7 +188,7 @@ export default { ...@@ -188,7 +188,7 @@ export default {
*/ */
removeScope(scope) { removeScope(scope) {
if (isString(scope.id) && scope.id.startsWith(INTERNAL_ID_PREFIX)) { if (isString(scope.id) && scope.id.startsWith(INTERNAL_ID_PREFIX)) {
this.formScopes = this.formScopes.filter(s => s !== scope); this.formScopes = this.formScopes.filter((s) => s !== scope);
} else { } else {
Vue.set(scope, 'shouldBeDestroyed', true); Vue.set(scope, 'shouldBeDestroyed', true);
} }
...@@ -387,9 +387,9 @@ export default { ...@@ -387,9 +387,9 @@ export default {
class="col-12" class="col-12"
:value="scope.environmentScope" :value="scope.environmentScope"
:disabled="!canUpdateScope(scope) || scope.environmentScope !== ''" :disabled="!canUpdateScope(scope) || scope.environmentScope !== ''"
@selectEnvironment="env => (scope.environmentScope = env)" @selectEnvironment="(env) => (scope.environmentScope = env)"
@createClicked="env => (scope.environmentScope = env)" @createClicked="(env) => (scope.environmentScope = env)"
@clearInput="env => (scope.environmentScope = '')" @clearInput="(env) => (scope.environmentScope = '')"
/> />
<gl-badge v-if="permissionsFlag && scope.protected" variant="success"> <gl-badge v-if="permissionsFlag && scope.protected" variant="success">
...@@ -406,7 +406,7 @@ export default { ...@@ -406,7 +406,7 @@ export default {
<toggle-button <toggle-button
:value="scope.active" :value="scope.active"
:disabled-input="!active || !canUpdateScope(scope)" :disabled-input="!active || !canUpdateScope(scope)"
@change="status => (scope.active = status)" @change="(status) => (scope.active = status)"
/> />
</div> </div>
</div> </div>
...@@ -524,8 +524,8 @@ export default { ...@@ -524,8 +524,8 @@ export default {
<environments-dropdown <environments-dropdown
class="js-new-scope-name col-12" class="js-new-scope-name col-12"
:value="newScope" :value="newScope"
@selectEnvironment="env => createNewScope({ environmentScope: env })" @selectEnvironment="(env) => createNewScope({ environmentScope: env })"
@createClicked="env => createNewScope({ environmentScope: env })" @createClicked="(env) => createNewScope({ environmentScope: env })"
/> />
</div> </div>
</div> </div>
......
...@@ -71,7 +71,7 @@ export default { ...@@ -71,7 +71,7 @@ export default {
:scopes="scopes" :scopes="scopes"
:strategies="strategies" :strategies="strategies"
:version="version" :version="version"
@handleSubmit="data => createFeatureFlag(data)" @handleSubmit="(data) => createFeatureFlag(data)"
/> />
</div> </div>
</template> </template>
...@@ -29,7 +29,7 @@ export const updateFeatureFlag = ({ state, dispatch }, params) => { ...@@ -29,7 +29,7 @@ export const updateFeatureFlag = ({ state, dispatch }, params) => {
dispatch('receiveUpdateFeatureFlagSuccess'); dispatch('receiveUpdateFeatureFlagSuccess');
visitUrl(state.path); visitUrl(state.path);
}) })
.catch(error => dispatch('receiveUpdateFeatureFlagError', error.response.data)); .catch((error) => dispatch('receiveUpdateFeatureFlagError', error.response.data));
}; };
export const requestUpdateFeatureFlag = ({ commit }) => commit(types.REQUEST_UPDATE_FEATURE_FLAG); export const requestUpdateFeatureFlag = ({ commit }) => commit(types.REQUEST_UPDATE_FEATURE_FLAG);
......
...@@ -4,7 +4,7 @@ import state from './state'; ...@@ -4,7 +4,7 @@ import state from './state';
import * as actions from './actions'; import * as actions from './actions';
import mutations from './mutations'; import mutations from './mutations';
export default data => export default (data) =>
new Vuex.Store({ new Vuex.Store({
actions, actions,
mutations, mutations,
......
import Api from '~/api'; import Api from '~/api';
import * as types from './mutation_types'; import * as types from './mutation_types';
const getErrorMessages = error => [].concat(error?.response?.data?.message ?? error.message); const getErrorMessages = (error) => [].concat(error?.response?.data?.message ?? error.message);
export const fetchUserLists = ({ commit, state: { filter, projectId } }) => { export const fetchUserLists = ({ commit, state: { filter, projectId } }) => {
commit(types.FETCH_USER_LISTS); commit(types.FETCH_USER_LISTS);
return Api.searchFeatureFlagUserLists(projectId, filter) return Api.searchFeatureFlagUserLists(projectId, filter)
.then(({ data }) => commit(types.RECEIVE_USER_LISTS_SUCCESS, data)) .then(({ data }) => commit(types.RECEIVE_USER_LISTS_SUCCESS, data))
.catch(error => commit(types.RECEIVE_USER_LISTS_ERROR, getErrorMessages(error))); .catch((error) => commit(types.RECEIVE_USER_LISTS_ERROR, getErrorMessages(error)));
}; };
export const setFilter = ({ commit, dispatch }, filter) => { export const setFilter = ({ commit, dispatch }, filter) => {
......
...@@ -3,7 +3,7 @@ import mutations from './mutations'; ...@@ -3,7 +3,7 @@ import mutations from './mutations';
import * as actions from './actions'; import * as actions from './actions';
import * as getters from './getters'; import * as getters from './getters';
export default data => ({ export default (data) => ({
state: state(data), state: state(data),
actions, actions,
getters, getters,
......
...@@ -17,16 +17,16 @@ import { ...@@ -17,16 +17,16 @@ import {
* objects that is easier/nicer to bind to in Vue. * objects that is easier/nicer to bind to in Vue.
* @param {Array} scopesFromRails An array of scope objects fetched from the API * @param {Array} scopesFromRails An array of scope objects fetched from the API
*/ */
export const mapToScopesViewModel = scopesFromRails => export const mapToScopesViewModel = (scopesFromRails) =>
(scopesFromRails || []).map(s => { (scopesFromRails || []).map((s) => {
const percentStrategy = (s.strategies || []).find( const percentStrategy = (s.strategies || []).find(
strat => strat.name === ROLLOUT_STRATEGY_PERCENT_ROLLOUT, (strat) => strat.name === ROLLOUT_STRATEGY_PERCENT_ROLLOUT,
); );
const rolloutPercentage = fetchPercentageParams(percentStrategy) || DEFAULT_PERCENT_ROLLOUT; const rolloutPercentage = fetchPercentageParams(percentStrategy) || DEFAULT_PERCENT_ROLLOUT;
const userStrategy = (s.strategies || []).find( const userStrategy = (s.strategies || []).find(
strat => strat.name === ROLLOUT_STRATEGY_USER_ID, (strat) => strat.name === ROLLOUT_STRATEGY_USER_ID,
); );
const rolloutStrategy = const rolloutStrategy =
...@@ -36,7 +36,7 @@ export const mapToScopesViewModel = scopesFromRails => ...@@ -36,7 +36,7 @@ export const mapToScopesViewModel = scopesFromRails =>
const rolloutUserIds = (fetchUserIdParams(userStrategy) || '') const rolloutUserIds = (fetchUserIdParams(userStrategy) || '')
.split(',') .split(',')
.filter(id => id) .filter((id) => id)
.join(', '); .join(', ');
return { return {
...@@ -59,8 +59,8 @@ export const mapToScopesViewModel = scopesFromRails => ...@@ -59,8 +59,8 @@ export const mapToScopesViewModel = scopesFromRails =>
* the shape that the Rails API expects. * the shape that the Rails API expects.
* @param {Array} scopesFromVue An array of scope objects from the Vue component * @param {Array} scopesFromVue An array of scope objects from the Vue component
*/ */
export const mapFromScopesViewModel = params => { export const mapFromScopesViewModel = (params) => {
const scopes = (params.scopes || []).map(s => { const scopes = (params.scopes || []).map((s) => {
const parameters = {}; const parameters = {};
if (s.rolloutStrategy === ROLLOUT_STRATEGY_PERCENT_ROLLOUT) { if (s.rolloutStrategy === ROLLOUT_STRATEGY_PERCENT_ROLLOUT) {
parameters.groupId = PERCENT_ROLLOUT_GROUP_ID; parameters.groupId = PERCENT_ROLLOUT_GROUP_ID;
...@@ -145,32 +145,32 @@ export const createNewEnvironmentScope = (overrides = {}, featureFlagPermissions ...@@ -145,32 +145,32 @@ export const createNewEnvironmentScope = (overrides = {}, featureFlagPermissions
return newScope; return newScope;
}; };
const mapStrategyScopesToRails = scopes => const mapStrategyScopesToRails = (scopes) =>
scopes.length === 0 scopes.length === 0
? [{ environment_scope: '*' }] ? [{ environment_scope: '*' }]
: scopes.map(s => ({ : scopes.map((s) => ({
id: s.id, id: s.id,
_destroy: s.shouldBeDestroyed, _destroy: s.shouldBeDestroyed,
environment_scope: s.environmentScope, environment_scope: s.environmentScope,
})); }));
const mapStrategyScopesToView = scopes => const mapStrategyScopesToView = (scopes) =>
scopes.map(s => ({ scopes.map((s) => ({
id: s.id, id: s.id,
// eslint-disable-next-line no-underscore-dangle // eslint-disable-next-line no-underscore-dangle
shouldBeDestroyed: Boolean(s._destroy), shouldBeDestroyed: Boolean(s._destroy),
environmentScope: s.environment_scope, environmentScope: s.environment_scope,
})); }));
const mapStrategiesParametersToViewModel = params => { const mapStrategiesParametersToViewModel = (params) => {
if (params.userIds) { if (params.userIds) {
return { ...params, userIds: params.userIds.split(',').join(', ') }; return { ...params, userIds: params.userIds.split(',').join(', ') };
} }
return params; return params;
}; };
export const mapStrategiesToViewModel = strategiesFromRails => export const mapStrategiesToViewModel = (strategiesFromRails) =>
(strategiesFromRails || []).map(s => ({ (strategiesFromRails || []).map((s) => ({
id: s.id, id: s.id,
name: s.name, name: s.name,
parameters: mapStrategiesParametersToViewModel(s.parameters), parameters: mapStrategiesParametersToViewModel(s.parameters),
...@@ -180,14 +180,14 @@ export const mapStrategiesToViewModel = strategiesFromRails => ...@@ -180,14 +180,14 @@ export const mapStrategiesToViewModel = strategiesFromRails =>
scopes: mapStrategyScopesToView(s.scopes), scopes: mapStrategyScopesToView(s.scopes),
})); }));
const mapStrategiesParametersToRails = params => { const mapStrategiesParametersToRails = (params) => {
if (params.userIds) { if (params.userIds) {
return { ...params, userIds: params.userIds.replace(/\s*,\s*/g, ',') }; return { ...params, userIds: params.userIds.replace(/\s*,\s*/g, ',') };
} }
return params; return params;
}; };
const mapStrategyToRails = strategy => { const mapStrategyToRails = (strategy) => {
const mappedStrategy = { const mappedStrategy = {
id: strategy.id, id: strategy.id,
name: strategy.name, name: strategy.name,
...@@ -202,7 +202,7 @@ const mapStrategyToRails = strategy => { ...@@ -202,7 +202,7 @@ const mapStrategyToRails = strategy => {
return mappedStrategy; return mappedStrategy;
}; };
export const mapStrategiesToRails = params => ({ export const mapStrategiesToRails = (params) => ({
operations_feature_flag: { operations_feature_flag: {
name: params.name, name: params.name,
description: params.description, description: params.description,
......
...@@ -12,7 +12,7 @@ export const fetchFeatureFlags = ({ state, dispatch }) => { ...@@ -12,7 +12,7 @@ export const fetchFeatureFlags = ({ state, dispatch }) => {
.get(state.endpoint, { .get(state.endpoint, {
params: state.options, params: state.options,
}) })
.then(response => .then((response) =>
dispatch('receiveFeatureFlagsSuccess', { dispatch('receiveFeatureFlagsSuccess', {
data: response.data || {}, data: response.data || {},
headers: response.headers, headers: response.headers,
...@@ -46,7 +46,7 @@ export const toggleFeatureFlag = ({ dispatch }, flag) => { ...@@ -46,7 +46,7 @@ export const toggleFeatureFlag = ({ dispatch }, flag) => {
.put(flag.update_path, { .put(flag.update_path, {
operations_feature_flag: flag, operations_feature_flag: flag,
}) })
.then(response => dispatch('receiveUpdateFeatureFlagSuccess', response.data)) .then((response) => dispatch('receiveUpdateFeatureFlagSuccess', response.data))
.catch(() => dispatch('receiveUpdateFeatureFlagError', flag.id)); .catch(() => dispatch('receiveUpdateFeatureFlagError', flag.id));
}; };
...@@ -62,7 +62,7 @@ export const deleteUserList = ({ state, dispatch }, list) => { ...@@ -62,7 +62,7 @@ export const deleteUserList = ({ state, dispatch }, list) => {
return Api.deleteFeatureFlagUserList(state.projectId, list.iid) return Api.deleteFeatureFlagUserList(state.projectId, list.iid)
.then(() => dispatch('fetchUserLists')) .then(() => dispatch('fetchUserLists'))
.catch(error => .catch((error) =>
dispatch('receiveDeleteUserListError', { dispatch('receiveDeleteUserListError', {
list, list,
error: error?.response?.data ?? error, error: error?.response?.data ?? error,
......
...@@ -3,7 +3,7 @@ import state from './state'; ...@@ -3,7 +3,7 @@ import state from './state';
import * as actions from './actions'; import * as actions from './actions';
import mutations from './mutations'; import mutations from './mutations';
export default data => export default (data) =>
new Vuex.Store({ new Vuex.Store({
actions, actions,
mutations, mutations,
......
...@@ -4,7 +4,7 @@ import { parseIntPagination, normalizeHeaders } from '~/lib/utils/common_utils'; ...@@ -4,7 +4,7 @@ import { parseIntPagination, normalizeHeaders } from '~/lib/utils/common_utils';
import { FEATURE_FLAG_SCOPE, USER_LIST_SCOPE } from '../../constants'; import { FEATURE_FLAG_SCOPE, USER_LIST_SCOPE } from '../../constants';
import { mapToScopesViewModel } from '../helpers'; import { mapToScopesViewModel } from '../helpers';
const mapFlag = flag => ({ ...flag, scopes: mapToScopesViewModel(flag.scopes || []) }); const mapFlag = (flag) => ({ ...flag, scopes: mapToScopesViewModel(flag.scopes || []) });
const updateFlag = (state, flag) => { const updateFlag = (state, flag) => {
const index = state[FEATURE_FLAG_SCOPE].findIndex(({ id }) => id === flag.id); const index = state[FEATURE_FLAG_SCOPE].findIndex(({ id }) => id === flag.id);
...@@ -94,7 +94,7 @@ export default { ...@@ -94,7 +94,7 @@ export default {
updateFlag(state, { ...flag, active: !flag.active }); updateFlag(state, { ...flag, active: !flag.active });
}, },
[types.REQUEST_DELETE_USER_LIST](state, list) { [types.REQUEST_DELETE_USER_LIST](state, list) {
state.userLists = state.userLists.filter(l => l !== list); state.userLists = state.userLists.filter((l) => l !== list);
}, },
[types.RECEIVE_DELETE_USER_LIST_ERROR](state, { error, list }) { [types.RECEIVE_DELETE_USER_LIST_ERROR](state, { error, list }) {
state.isLoading = false; state.isLoading = false;
......
...@@ -27,7 +27,7 @@ export const createFeatureFlag = ({ state, dispatch }, params) => { ...@@ -27,7 +27,7 @@ export const createFeatureFlag = ({ state, dispatch }, params) => {
dispatch('receiveCreateFeatureFlagSuccess'); dispatch('receiveCreateFeatureFlagSuccess');
visitUrl(state.path); visitUrl(state.path);
}) })
.catch(error => dispatch('receiveCreateFeatureFlagError', error.response.data)); .catch((error) => dispatch('receiveCreateFeatureFlagError', error.response.data));
}; };
export const requestCreateFeatureFlag = ({ commit }) => commit(types.REQUEST_CREATE_FEATURE_FLAG); export const requestCreateFeatureFlag = ({ commit }) => commit(types.REQUEST_CREATE_FEATURE_FLAG);
......
...@@ -4,7 +4,7 @@ import state from './state'; ...@@ -4,7 +4,7 @@ import state from './state';
import * as actions from './actions'; import * as actions from './actions';
import mutations from './mutations'; import mutations from './mutations';
export default data => export default (data) =>
new Vuex.Store({ new Vuex.Store({
actions, actions,
mutations, mutations,
......
...@@ -48,7 +48,7 @@ const badgeTextByType = { ...@@ -48,7 +48,7 @@ const badgeTextByType = {
const scopeName = ({ environment_scope: scope }) => const scopeName = ({ environment_scope: scope }) =>
scope === ALL_ENVIRONMENTS_NAME ? s__('FeatureFlags|All Environments') : scope; scope === ALL_ENVIRONMENTS_NAME ? s__('FeatureFlags|All Environments') : scope;
export const labelForStrategy = strategy => { export const labelForStrategy = (strategy) => {
const { name, parameters } = badgeTextByType[strategy.name]; const { name, parameters } = badgeTextByType[strategy.name];
if (parameters) { if (parameters) {
......
...@@ -31,7 +31,7 @@ export function setupFeatureHighlightPopover(id, debounceTimeout = 300) { ...@@ -31,7 +31,7 @@ export function setupFeatureHighlightPopover(id, debounceTimeout = 300) {
.removeAttr('disabled'); .removeAttr('disabled');
} }
const getPriority = e => parseInt(e.dataset.highlightPriority, 10) || 0; const getPriority = (e) => parseInt(e.dataset.highlightPriority, 10) || 0;
export function findHighestPriorityFeature() { export function findHighestPriorityFeature() {
let priorityFeature; let priorityFeature;
......
...@@ -5,7 +5,7 @@ import { deprecatedCreateFlash as Flash } from '../flash'; ...@@ -5,7 +5,7 @@ import { deprecatedCreateFlash as Flash } from '../flash';
import LazyLoader from '../lazy_loader'; import LazyLoader from '../lazy_loader';
import { togglePopover } from '../shared/popover'; import { togglePopover } from '../shared/popover';
export const getSelector = highlightId => `.js-feature-highlight[data-highlight=${highlightId}]`; export const getSelector = (highlightId) => `.js-feature-highlight[data-highlight=${highlightId}]`;
export function dismiss(highlightId) { export function dismiss(highlightId) {
axios axios
......
export default function initFilePickers() { export default function initFilePickers() {
const filePickers = document.querySelectorAll('.js-filepicker'); const filePickers = document.querySelectorAll('.js-filepicker');
filePickers.forEach(filePicker => { filePickers.forEach((filePicker) => {
const button = filePicker.querySelector('.js-filepicker-button'); const button = filePicker.querySelector('.js-filepicker-button');
button.addEventListener('click', () => { button.addEventListener('click', () => {
......
...@@ -33,8 +33,8 @@ export default { ...@@ -33,8 +33,8 @@ export default {
if (this.userCanCreateNote) { if (this.userCanCreateNote) {
$diffFile $diffFile
.on('mouseover', LINE_COLUMN_CLASSES, e => this.showButton(this.isParallelView, e)) .on('mouseover', LINE_COLUMN_CLASSES, (e) => this.showButton(this.isParallelView, e))
.on('mouseleave', LINE_COLUMN_CLASSES, e => this.hideButton(this.isParallelView, e)); .on('mouseleave', LINE_COLUMN_CLASSES, (e) => this.hideButton(this.isParallelView, e));
} }
}, },
......
...@@ -72,7 +72,7 @@ export default class FilterableList { ...@@ -72,7 +72,7 @@ export default class FilterableList {
.get(this.getFilterEndpoint(), { .get(this.getFilterEndpoint(), {
params, params,
}) })
.then(res => { .then((res) => {
this.onFilterSuccess(res, params); this.onFilterSuccess(res, params);
this.onFilterComplete(); this.onFilterComplete();
}) })
......
...@@ -50,7 +50,7 @@ export default class AvailableDropdownMappings { ...@@ -50,7 +50,7 @@ export default class AvailableDropdownMappings {
}, },
}; };
supportedTokens.forEach(type => { supportedTokens.forEach((type) => {
if (availableMappings[type]) { if (availableMappings[type]) {
allowedMappings[type] = availableMappings[type]; allowedMappings[type] = availableMappings[type];
} }
...@@ -99,7 +99,7 @@ export default class AvailableDropdownMappings { ...@@ -99,7 +99,7 @@ export default class AvailableDropdownMappings {
// The DropdownNonUser class is hardcoded to look for and display a // The DropdownNonUser class is hardcoded to look for and display a
// "title" property, so we need to add this property to each release object // "title" property, so we need to add this property to each release object
preprocessing: releases => releases.map(r => ({ ...r, title: r.tag })), preprocessing: (releases) => releases.map((r) => ({ ...r, title: r.tag })),
}, },
element: this.container.querySelector('#js-dropdown-release'), element: this.container.querySelector('#js-dropdown-release'),
}, },
...@@ -162,7 +162,7 @@ export default class AvailableDropdownMappings { ...@@ -162,7 +162,7 @@ export default class AvailableDropdownMappings {
extraArguments: { extraArguments: {
endpoint: this.getEnvironmentsEndpoint(), endpoint: this.getEnvironmentsEndpoint(),
symbol: '', symbol: '',
preprocessing: data => data.map(env => ({ title: env })), preprocessing: (data) => data.map((env) => ({ title: env })),
}, },
element: this.container.querySelector('#js-dropdown-environment'), element: this.container.querySelector('#js-dropdown-environment'),
}, },
......
...@@ -28,16 +28,16 @@ export default { ...@@ -28,16 +28,16 @@ export default {
* fix by ignoring non-string recents while in Epic page. * fix by ignoring non-string recents while in Epic page.
*/ */
compatibleItems() { compatibleItems() {
return this.items.filter(item => typeof item === 'string'); return this.items.filter((item) => typeof item === 'string');
}, },
processedItems() { processedItems() {
return this.compatibleItems.map(item => { return this.compatibleItems.map((item) => {
const { tokens, searchToken } = FilteredSearchTokenizer.processTokens( const { tokens, searchToken } = FilteredSearchTokenizer.processTokens(
item, item,
this.allowedKeys, this.allowedKeys,
); );
const resultantTokens = tokens.map(token => ({ const resultantTokens = tokens.map((token) => ({
prefix: `${token.key}:`, prefix: `${token.key}:`,
operator: token.operator, operator: token.operator,
suffix: `${token.symbol}${token.value}`, suffix: `${token.symbol}${token.value}`,
......
...@@ -33,7 +33,7 @@ export default class DropdownAjaxFilter extends FilteredSearchDropdown { ...@@ -33,7 +33,7 @@ export default class DropdownAjaxFilter extends FilteredSearchDropdown {
} }
itemClicked(e) { itemClicked(e) {
super.itemClicked(e, selected => { super.itemClicked(e, (selected) => {
const title = selected.querySelector('.dropdown-light-content').innerText.trim(); const title = selected.querySelector('.dropdown-light-content').innerText.trim();
return DropdownUtils.getEscapedText(title); return DropdownUtils.getEscapedText(title);
......
...@@ -53,7 +53,7 @@ export default class DropdownEmoji extends FilteredSearchDropdown { ...@@ -53,7 +53,7 @@ export default class DropdownEmoji extends FilteredSearchDropdown {
} }
itemClicked(e) { itemClicked(e) {
super.itemClicked(e, selected => { super.itemClicked(e, (selected) => {
const name = selected.querySelector('.js-data-value').innerText.trim(); const name = selected.querySelector('.js-data-value').innerText.trim();
return DropdownUtils.getEscapedText(name); return DropdownUtils.getEscapedText(name);
}); });
...@@ -69,7 +69,7 @@ export default class DropdownEmoji extends FilteredSearchDropdown { ...@@ -69,7 +69,7 @@ export default class DropdownEmoji extends FilteredSearchDropdown {
// Replace empty gl-emoji tag to real content // Replace empty gl-emoji tag to real content
const dropdownItems = [...this.dropdown.querySelectorAll('.filter-dropdown-item')]; const dropdownItems = [...this.dropdown.querySelectorAll('.filter-dropdown-item')];
dropdownItems.forEach(dropdownItem => { dropdownItems.forEach((dropdownItem) => {
const valueElement = dropdownItem.querySelector('.js-data-value'); const valueElement = dropdownItem.querySelector('.js-data-value');
if (valueElement !== null) { if (valueElement !== null) {
const name = valueElement.innerText; const name = valueElement.innerText;
......
...@@ -83,7 +83,7 @@ export default class DropdownHint extends FilteredSearchDropdown { ...@@ -83,7 +83,7 @@ export default class DropdownHint extends FilteredSearchDropdown {
const dropdownData = this.tokenKeys const dropdownData = this.tokenKeys
.get() .get()
.map(tokenKey => ({ .map((tokenKey) => ({
icon: `${gon.sprite_icons}#${tokenKey.icon}`, icon: `${gon.sprite_icons}#${tokenKey.icon}`,
hint: tokenKey.key, hint: tokenKey.key,
tag: `:${tokenKey.tag}`, tag: `:${tokenKey.tag}`,
......
...@@ -30,7 +30,7 @@ export default class DropdownNonUser extends FilteredSearchDropdown { ...@@ -30,7 +30,7 @@ export default class DropdownNonUser extends FilteredSearchDropdown {
} }
itemClicked(e) { itemClicked(e) {
super.itemClicked(e, selected => { super.itemClicked(e, (selected) => {
const title = selected.querySelector('.js-data-value').innerText.trim(); const title = selected.querySelector('.js-data-value').innerText.trim();
return `${this.symbol}${DropdownUtils.getEscapedText(title)}`; return `${this.symbol}${DropdownUtils.getEscapedText(title)}`;
}); });
......
...@@ -61,7 +61,7 @@ export default class DropdownUtils { ...@@ -61,7 +61,7 @@ export default class DropdownUtils {
const { lastToken, tokens } = FilteredSearchTokenizer.processTokens(searchInput, allowedKeys); const { lastToken, tokens } = FilteredSearchTokenizer.processTokens(searchInput, allowedKeys);
const lastKey = lastToken.key || lastToken || ''; const lastKey = lastToken.key || lastToken || '';
const allowMultiple = item.type === 'array'; const allowMultiple = item.type === 'array';
const itemInExistingTokens = tokens.some(t => t.key === item.hint); const itemInExistingTokens = tokens.some((t) => t.key === item.hint);
const isSearchItem = updatedItem.hint === 'search'; const isSearchItem = updatedItem.hint === 'search';
if (isSearchItem) { if (isSearchItem) {
...@@ -77,7 +77,7 @@ export default class DropdownUtils { ...@@ -77,7 +77,7 @@ export default class DropdownUtils {
const tokenName = last(split[0].split(' ')); const tokenName = last(split[0].split(' '));
const match = isSearchItem const match = isSearchItem
? allowedKeys.some(key => key.startsWith(tokenName.toLowerCase())) ? allowedKeys.some((key) => key.startsWith(tokenName.toLowerCase()))
: updatedItem.hint.indexOf(tokenName.toLowerCase()) === -1; : updatedItem.hint.indexOf(tokenName.toLowerCase()) === -1;
updatedItem.droplab_hidden = tokenName ? match : false; updatedItem.droplab_hidden = tokenName ? match : false;
...@@ -129,12 +129,12 @@ export default class DropdownUtils { ...@@ -129,12 +129,12 @@ export default class DropdownUtils {
const values = []; const values = [];
if (untilInput) { if (untilInput) {
const inputIndex = tokens.findIndex(t => t.classList.contains('input-token')); const inputIndex = tokens.findIndex((t) => t.classList.contains('input-token'));
// Add one to include input-token to the tokens array // Add one to include input-token to the tokens array
tokens.splice(inputIndex + 1); tokens.splice(inputIndex + 1);
} }
tokens.forEach(token => { tokens.forEach((token) => {
if (token.classList.contains('js-visual-token')) { if (token.classList.contains('js-visual-token')) {
const name = token.querySelector('.name'); const name = token.querySelector('.name');
const operatorContainer = token.querySelector('.operator'); const operatorContainer = token.querySelector('.operator');
...@@ -176,7 +176,7 @@ export default class DropdownUtils { ...@@ -176,7 +176,7 @@ export default class DropdownUtils {
} }
}); });
return values.map(value => value.trim()).join(' '); return values.map((value) => value.trim()).join(' ');
} }
static getSearchInput(filteredSearchInput) { static getSearchInput(filteredSearchInput) {
...@@ -192,7 +192,7 @@ export default class DropdownUtils { ...@@ -192,7 +192,7 @@ export default class DropdownUtils {
// Replace all spaces inside quote marks with underscores // Replace all spaces inside quote marks with underscores
// (will continue to match entire string until an end quote is found if any) // (will continue to match entire string until an end quote is found if any)
// This helps with matching the beginning & end of a token:key // This helps with matching the beginning & end of a token:key
inputValue = inputValue.replace(/(('[^']*'{0,1})|("[^"]*"{0,1})|:\s+)/g, str => inputValue = inputValue.replace(/(('[^']*'{0,1})|("[^"]*"{0,1})|:\s+)/g, (str) =>
str.replace(/\s/g, '_'), str.replace(/\s/g, '_'),
); );
......
...@@ -28,7 +28,7 @@ export default class FilteredSearchDropdown { ...@@ -28,7 +28,7 @@ export default class FilteredSearchDropdown {
} }
getCurrentHook() { getCurrentHook() {
return this.droplab.hooks.filter(h => h.id === this.hookId)[0] || null; return this.droplab.hooks.filter((h) => h.id === this.hookId)[0] || null;
} }
itemClicked(e, getValueFunction) { itemClicked(e, getValueFunction) {
...@@ -134,7 +134,7 @@ export default class FilteredSearchDropdown { ...@@ -134,7 +134,7 @@ export default class FilteredSearchDropdown {
if (!data) return; if (!data) return;
const results = data.map(o => { const results = data.map((o) => {
const updated = o; const updated = o;
updated.droplab_hidden = false; updated.droplab_hidden = false;
return updated; return updated;
...@@ -157,7 +157,7 @@ export default class FilteredSearchDropdown { ...@@ -157,7 +157,7 @@ export default class FilteredSearchDropdown {
// Iterate over all the static dropdown values, // Iterate over all the static dropdown values,
// then hide `None` and `Any` items. // then hide `None` and `Any` items.
Array.from(dropdownEl.querySelectorAll('li[data-value]')).forEach(itemEl => { Array.from(dropdownEl.querySelectorAll('li[data-value]')).forEach((itemEl) => {
const { const {
dataset: { value }, dataset: { value },
} = itemEl; } = itemEl;
......
...@@ -23,7 +23,7 @@ export default class FilteredSearchDropdownManager { ...@@ -23,7 +23,7 @@ export default class FilteredSearchDropdownManager {
isGroupDecendent, isGroupDecendent,
filteredSearchTokenKeys, filteredSearchTokenKeys,
}) { }) {
const removeTrailingSlash = url => url.replace(/\/$/, ''); const removeTrailingSlash = (url) => url.replace(/\/$/, '');
this.container = FilteredSearchContainer.container; this.container = FilteredSearchContainer.container;
this.runnerTagsEndpoint = removeTrailingSlash(runnerTagsEndpoint); this.runnerTagsEndpoint = removeTrailingSlash(runnerTagsEndpoint);
......
...@@ -90,14 +90,14 @@ export default class FilteredSearchManager { ...@@ -90,14 +90,14 @@ export default class FilteredSearchManager {
// Fetch recent searches from localStorage // Fetch recent searches from localStorage
this.fetchingRecentSearchesPromise = this.recentSearchesService this.fetchingRecentSearchesPromise = this.recentSearchesService
.fetch() .fetch()
.catch(error => { .catch((error) => {
if (error.name === 'RecentSearchesServiceError') return undefined; if (error.name === 'RecentSearchesServiceError') return undefined;
// eslint-disable-next-line no-new // eslint-disable-next-line no-new
new Flash(__('An error occurred while parsing recent searches')); new Flash(__('An error occurred while parsing recent searches'));
// Gracefully fail to empty array // Gracefully fail to empty array
return []; return [];
}) })
.then(searches => { .then((searches) => {
if (!searches) { if (!searches) {
return; return;
} }
...@@ -169,7 +169,7 @@ export default class FilteredSearchManager { ...@@ -169,7 +169,7 @@ export default class FilteredSearchManager {
if (this.stateFilters) { if (this.stateFilters) {
this.searchStateWrapper = this.searchState.bind(this); this.searchStateWrapper = this.searchState.bind(this);
this.applyToStateFilters(filterEl => { this.applyToStateFilters((filterEl) => {
filterEl.addEventListener('click', this.searchStateWrapper); filterEl.addEventListener('click', this.searchStateWrapper);
}); });
} }
...@@ -177,14 +177,14 @@ export default class FilteredSearchManager { ...@@ -177,14 +177,14 @@ export default class FilteredSearchManager {
unbindStateEvents() { unbindStateEvents() {
if (this.stateFilters) { if (this.stateFilters) {
this.applyToStateFilters(filterEl => { this.applyToStateFilters((filterEl) => {
filterEl.removeEventListener('click', this.searchStateWrapper); filterEl.removeEventListener('click', this.searchStateWrapper);
}); });
} }
} }
applyToStateFilters(callback) { applyToStateFilters(callback) {
this.stateFilters.querySelectorAll('a[data-state]').forEach(filterEl => { this.stateFilters.querySelectorAll('a[data-state]').forEach((filterEl) => {
if (this.states.indexOf(filterEl.dataset.state) > -1) { if (this.states.indexOf(filterEl.dataset.state) > -1) {
callback(filterEl); callback(filterEl);
} }
...@@ -263,7 +263,7 @@ export default class FilteredSearchManager { ...@@ -263,7 +263,7 @@ export default class FilteredSearchManager {
let backspaceCount = 0; let backspaceCount = 0;
// closure for keeping track of the number of backspace keystrokes // closure for keeping track of the number of backspace keystrokes
return e => { return (e) => {
// 8 = Backspace Key // 8 = Backspace Key
// 46 = Delete Key // 46 = Delete Key
// Handled by respective backspace-combination check functions // Handled by respective backspace-combination check functions
...@@ -447,7 +447,7 @@ export default class FilteredSearchManager { ...@@ -447,7 +447,7 @@ export default class FilteredSearchManager {
const removeElements = []; const removeElements = [];
[].forEach.call(this.tokensContainer.children, t => { [].forEach.call(this.tokensContainer.children, (t) => {
let canClearToken = t.classList.contains('js-visual-token'); let canClearToken = t.classList.contains('js-visual-token');
if (canClearToken) { if (canClearToken) {
...@@ -460,7 +460,7 @@ export default class FilteredSearchManager { ...@@ -460,7 +460,7 @@ export default class FilteredSearchManager {
} }
}); });
removeElements.forEach(el => { removeElements.forEach((el) => {
el.parentElement.removeChild(el); el.parentElement.removeChild(el);
}); });
...@@ -488,7 +488,7 @@ export default class FilteredSearchManager { ...@@ -488,7 +488,7 @@ export default class FilteredSearchManager {
const { isLastVisualTokenValid } = FilteredSearchVisualTokens.getLastVisualTokenBeforeInput(); const { isLastVisualTokenValid } = FilteredSearchVisualTokens.getLastVisualTokenBeforeInput();
if (isLastVisualTokenValid) { if (isLastVisualTokenValid) {
tokens.forEach(t => { tokens.forEach((t) => {
input.value = input.value.replace(`${t.key}:${t.operator}${t.symbol}${t.value}`, ''); input.value = input.value.replace(`${t.key}:${t.operator}${t.symbol}${t.value}`, '');
FilteredSearchVisualTokens.addFilterVisualToken( FilteredSearchVisualTokens.addFilterVisualToken(
...@@ -585,7 +585,7 @@ export default class FilteredSearchManager { ...@@ -585,7 +585,7 @@ export default class FilteredSearchManager {
*/ */
const notKeyValueRegex = new RegExp(/not\[(\w+)\]\[?\]?=(.*)/); const notKeyValueRegex = new RegExp(/not\[(\w+)\]\[?\]?=(.*)/);
return params.map(query => { return params.map((query) => {
// Check if there are matches for `not` operator // Check if there are matches for `not` operator
const matches = query.match(notKeyValueRegex); const matches = query.match(notKeyValueRegex);
if (matches && matches.length === 3) { if (matches && matches.length === 3) {
...@@ -624,7 +624,7 @@ export default class FilteredSearchManager { ...@@ -624,7 +624,7 @@ export default class FilteredSearchManager {
const usernameParams = this.getUsernameParams(); const usernameParams = this.getUsernameParams();
let hasFilteredSearch = false; let hasFilteredSearch = false;
params.forEach(p => { params.forEach((p) => {
const split = p.split('='); const split = p.split('=');
const keyParam = decodeURIComponent(split[0]); const keyParam = decodeURIComponent(split[0]);
const value = split[1]; const value = split[1];
...@@ -746,7 +746,7 @@ export default class FilteredSearchManager { ...@@ -746,7 +746,7 @@ export default class FilteredSearchManager {
paths.push(`state=${currentState}`); paths.push(`state=${currentState}`);
} }
tokens.forEach(token => { tokens.forEach((token) => {
const condition = this.filteredSearchTokenKeys.searchByConditionKeyValue( const condition = this.filteredSearchTokenKeys.searchByConditionKeyValue(
token.key, token.key,
token.operator, token.operator,
...@@ -795,7 +795,7 @@ export default class FilteredSearchManager { ...@@ -795,7 +795,7 @@ export default class FilteredSearchManager {
if (searchToken) { if (searchToken) {
const sanitized = searchToken const sanitized = searchToken
.split(' ') .split(' ')
.map(t => encodeURIComponent(t)) .map((t) => encodeURIComponent(t))
.join('+'); .join('+');
paths.push(`search=${sanitized}`); paths.push(`search=${sanitized}`);
} }
...@@ -817,7 +817,7 @@ export default class FilteredSearchManager { ...@@ -817,7 +817,7 @@ export default class FilteredSearchManager {
const usernamesById = {}; const usernamesById = {};
try { try {
const attribute = this.filteredSearchInput.getAttribute('data-username-params'); const attribute = this.filteredSearchInput.getAttribute('data-username-params');
JSON.parse(attribute).forEach(user => { JSON.parse(attribute).forEach((user) => {
usernamesById[user.id] = user.username; usernamesById[user.id] = user.username;
}); });
} catch (e) { } catch (e) {
......
...@@ -14,7 +14,7 @@ export default class FilteredSearchTokenKeys { ...@@ -14,7 +14,7 @@ export default class FilteredSearchTokenKeys {
} }
getKeys() { getKeys() {
return this.tokenKeys.map(i => i.key); return this.tokenKeys.map((i) => i.key);
} }
getAlternatives() { getAlternatives() {
...@@ -36,16 +36,16 @@ export default class FilteredSearchTokenKeys { ...@@ -36,16 +36,16 @@ export default class FilteredSearchTokenKeys {
} }
searchByKey(key) { searchByKey(key) {
return this.tokenKeys.find(tokenKey => tokenKey.key === key) || null; return this.tokenKeys.find((tokenKey) => tokenKey.key === key) || null;
} }
searchBySymbol(symbol) { searchBySymbol(symbol) {
return this.tokenKeys.find(tokenKey => tokenKey.symbol === symbol) || null; return this.tokenKeys.find((tokenKey) => tokenKey.symbol === symbol) || null;
} }
searchByKeyParam(keyParam) { searchByKeyParam(keyParam) {
return ( return (
this.tokenKeysWithAlternative.find(tokenKey => { this.tokenKeysWithAlternative.find((tokenKey) => {
let tokenKeyParam = tokenKey.key; let tokenKeyParam = tokenKey.key;
// Replace hyphen with underscore to compare keyParam with tokenKeyParam // Replace hyphen with underscore to compare keyParam with tokenKeyParam
...@@ -62,13 +62,13 @@ export default class FilteredSearchTokenKeys { ...@@ -62,13 +62,13 @@ export default class FilteredSearchTokenKeys {
} }
searchByConditionUrl(url) { searchByConditionUrl(url) {
return this.conditions.find(condition => condition.url === url) || null; return this.conditions.find((condition) => condition.url === url) || null;
} }
searchByConditionKeyValue(key, operator, value) { searchByConditionKeyValue(key, operator, value) {
return ( return (
this.conditions.find( this.conditions.find(
condition => (condition) =>
condition.tokenKey === key && condition.tokenKey === key &&
condition.operator === operator && condition.operator === operator &&
condition.value.toLowerCase() === value.toLowerCase(), condition.value.toLowerCase() === value.toLowerCase(),
......
...@@ -8,7 +8,7 @@ export default class FilteredSearchVisualTokens { ...@@ -8,7 +8,7 @@ export default class FilteredSearchVisualTokens {
static getOperatorToken(value) { static getOperatorToken(value) {
let token = null; let token = null;
FilteredSearchVisualTokens.permissibleOperatorValues.forEach(operatorToken => { FilteredSearchVisualTokens.permissibleOperatorValues.forEach((operatorToken) => {
if (value.startsWith(operatorToken)) { if (value.startsWith(operatorToken)) {
token = operatorToken; token = operatorToken;
} }
...@@ -20,7 +20,7 @@ export default class FilteredSearchVisualTokens { ...@@ -20,7 +20,7 @@ export default class FilteredSearchVisualTokens {
static getValueToken(value) { static getValueToken(value) {
let newValue = value; let newValue = value;
FilteredSearchVisualTokens.permissibleOperatorValues.forEach(operatorToken => { FilteredSearchVisualTokens.permissibleOperatorValues.forEach((operatorToken) => {
if (value.startsWith(operatorToken)) { if (value.startsWith(operatorToken)) {
newValue = value.slice(operatorToken.length); newValue = value.slice(operatorToken.length);
} }
...@@ -48,7 +48,7 @@ export default class FilteredSearchVisualTokens { ...@@ -48,7 +48,7 @@ export default class FilteredSearchVisualTokens {
const otherTokens = FilteredSearchContainer.container.querySelectorAll( const otherTokens = FilteredSearchContainer.container.querySelectorAll(
'.js-visual-token .selectable.selected', '.js-visual-token .selectable.selected',
); );
[].forEach.call(otherTokens, t => t.classList.remove('selected')); [].forEach.call(otherTokens, (t) => t.classList.remove('selected'));
} }
static selectToken(tokenButton, forceSelection = false) { static selectToken(tokenButton, forceSelection = false) {
......
...@@ -150,7 +150,7 @@ export const conditions = flattenDeep( ...@@ -150,7 +150,7 @@ export const conditions = flattenDeep(
tokenKey: 'my-reaction', tokenKey: 'my-reaction',
value: __('Any'), value: __('Any'),
}, },
].map(condition => { ].map((condition) => {
const [keyPart, valuePart] = condition.url.split('='); const [keyPart, valuePart] = condition.url.split('=');
const hasBrackets = keyPart.includes('[]'); const hasBrackets = keyPart.includes('[]');
......
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