Commit a7841365 authored by Jose Vargas's avatar Jose Vargas

Add text inputs for custom variables

This creates a section with text inputs
said inputs contain the values of each of
the custom values, changing them, changes the url
and refreshes the page
parent 7d1667a3
......@@ -30,6 +30,7 @@ import GraphGroup from './graph_group.vue';
import EmptyState from './empty_state.vue';
import GroupEmptyState from './group_empty_state.vue';
import DashboardsDropdown from './dashboards_dropdown.vue';
import VariablesSection from './variables_section.vue';
import TrackEventDirective from '~/vue_shared/directives/track_event';
import {
......@@ -64,6 +65,8 @@ export default {
EmptyState,
GroupEmptyState,
DashboardsDropdown,
VariablesSection,
},
directives: {
GlModal: GlModalDirective,
......@@ -222,6 +225,7 @@ export default {
'allDashboards',
'environmentsLoading',
'expandedPanel',
'promVariables',
]),
...mapGetters('monitoringDashboard', ['getMetricStates', 'filteredEnvironments']),
firstDashboard() {
......@@ -243,6 +247,9 @@ export default {
shouldShowEnvironmentsDropdownNoMatchedMsg() {
return !this.environmentsLoading && this.filteredEnvironments.length === 0;
},
shouldShowVariablesSection() {
return Object.keys(this.promVariables).length > 0;
},
},
watch: {
dashboard(newDashboard) {
......@@ -575,7 +582,7 @@ export default {
</div>
</div>
</div>
<variables-section v-if="shouldShowVariablesSection && !showEmptyState" />
<div v-if="!showEmptyState">
<dashboard-panel
v-show="expandedPanel.panel"
......
<script>
import { GlFormGroup, GlFormInput } from '@gitlab/ui';
import { mapState, mapActions } from 'vuex';
import { mergeUrlParams, updateHistory } from '~/lib/utils/url_utility';
export default {
components: {
GlFormGroup,
GlFormInput,
},
computed: {
...mapState('monitoringDashboard', ['promVariables']),
},
methods: {
...mapActions('monitoringDashboard', ['fetchDashboardData']),
refreshDashboard() {
updateHistory({
url: mergeUrlParams(this.promVariables, window.location.href),
title: document.title,
});
this.fetchDashboardData();
},
},
};
</script>
<template>
<div ref="variablesSection" class="d-sm-flex flex-sm-wrap pt-2 pr-1 pb-0 pl-2 variables-section">
<div v-for="(val, key) in promVariables" :key="key" class="mb-1 pr-2 d-flex d-sm-block">
<gl-form-group :label="key" class="mb-0 flex-grow-1">
<gl-form-input
v-model="promVariables[key]"
:name="key"
@keyup.native.enter="refreshDashboard"
@blur="refreshDashboard"
/>
</gl-form-group>
</div>
</div>
</template>
......@@ -222,14 +222,17 @@ export const fetchDashboardData = ({ state, dispatch, getters }) => {
*
* @param {metric} metric
*/
export const fetchPrometheusMetric = ({ commit, state }, { metric, defaultQueryParams }) => {
export const fetchPrometheusMetric = (
{ commit, state, getters },
{ metric, defaultQueryParams },
) => {
const queryParams = { ...defaultQueryParams };
if (metric.step) {
queryParams.step = metric.step;
}
if (state.promVariables.length > 0) {
queryParams.variables = state.promVariables;
if (Object.keys(state.promVariables).length > 0) {
queryParams.variables = getters.getCustomVariablesArray;
}
commit(types.REQUEST_METRIC_RESULT, { metricId: metric.metricId });
......
......@@ -96,5 +96,17 @@ export const filteredEnvironments = state =>
env.name.toLowerCase().includes((state.environmentsSearchTerm || '').trim().toLowerCase()),
);
/**
* Maps an variables object to an array
* @returns {Array} The custom variables array to be send to the API
* in the format of [variable1, variable1_value]
* @param {Object} variables - Custom variables provided by the user
*/
export const getCustomVariablesArray = state =>
Object.entries(state.promVariables)
.flat()
.map(encodeURIComponent);
// prevent babel-plugin-rewire from generating an invalid default during karma tests
export default () => {};
......@@ -51,18 +51,6 @@ const emptyStateFromError = error => {
return metricStates.UNKNOWN_ERROR;
};
/**
* Maps an variables object to an array
* @returns {Array} The custom variables array to be send to the API
* in the format of [variable1, variable1_value]
* @param {Object} variables - Custom variables provided by the user
*/
const transformVariablesObjectArray = variables =>
Object.entries(variables)
.flat()
.map(encodeURIComponent);
export default {
/**
* Dashboard panels structure and global state
......@@ -182,6 +170,6 @@ export default {
state.expandedPanel.panel = panel;
},
[types.SET_PROM_QUERY_VARIABLES](state, variables) {
state.promVariables = transformVariablesObjectArray(variables);
state.promVariables = variables;
},
};
......@@ -33,7 +33,7 @@ export default () => ({
panel: null,
},
allDashboards: [],
promVariables: [],
promVariables: {},
// Other project data
annotations: [],
......
......@@ -13,6 +13,14 @@
.form-group {
margin-bottom: map-get($spacing-scale, 3);
}
.variables-section {
input {
@include media-breakpoint-up(sm) {
width: 160px;
}
}
}
}
.draggable {
......
......@@ -111,6 +111,8 @@ exports[`Dashboard template matches the default snapshot 1`] = `
</div>
</div>
<!---->
<empty-state-stub
clusterspath="/path/to/clusters"
documentationpath="/path/to/docs"
......
......@@ -18,7 +18,12 @@ import GroupEmptyState from '~/monitoring/components/group_empty_state.vue';
import DashboardPanel from '~/monitoring/components/dashboard_panel.vue';
import { createStore } from '~/monitoring/stores';
import * as types from '~/monitoring/stores/mutation_types';
import { setupStoreWithDashboard, setMetricResult, setupStoreWithData } from '../store_utils';
import {
setupStoreWithDashboard,
setMetricResult,
setupStoreWithData,
setupStoreWithVariable,
} from '../store_utils';
import { environmentData, dashboardGitResponse, propsData } from '../mock_data';
import { metricsDashboardViewModel, metricsDashboardPanelCount } from '../fixture_data';
import createFlash from '~/flash';
......@@ -297,6 +302,20 @@ describe('Dashboard', () => {
});
});
describe('variables section', () => {
beforeEach(() => {
createShallowWrapper({ hasMetrics: true });
setupStoreWithData(wrapper.vm.$store);
setupStoreWithVariable(wrapper.vm.$store);
return wrapper.vm.$nextTick();
});
it('shows the variables section', () => {
expect(wrapper.vm.shouldShowVariablesSection).toBe(true);
});
});
describe('single panel expands to "full screen" mode', () => {
const findExpandedPanel = () => wrapper.find({ ref: 'expandedPanel' });
......
import { shallowMount } from '@vue/test-utils';
import Vuex from 'vuex';
import { GlFormInput } from '@gitlab/ui';
import VariablesSection from '~/monitoring/components/variables_section.vue';
import { updateHistory, mergeUrlParams } from '~/lib/utils/url_utility';
import { createStore } from '~/monitoring/stores';
import * as types from '~/monitoring/stores/mutation_types';
jest.mock('~/lib/utils/url_utility', () => ({
updateHistory: jest.fn(),
mergeUrlParams: jest.fn(),
}));
describe('Metrics dashboard/variables section component', () => {
let store;
let wrapper;
const sampleVariables = {
label1: 'pod',
label2: 'main',
};
const createShallowWrapper = () => {
wrapper = shallowMount(VariablesSection, {
store,
});
};
const findAllFormInputs = () => wrapper.findAll(GlFormInput);
const getInputAt = i => findAllFormInputs().at(i);
beforeEach(() => {
store = createStore();
store.state.monitoringDashboard.showEmptyState = false;
});
it('does not show the variables section', () => {
createShallowWrapper();
const allInputs = findAllFormInputs();
expect(allInputs).toHaveLength(0);
});
it('shows the variables section', () => {
createShallowWrapper();
wrapper.vm.$store.commit(
`monitoringDashboard/${types.SET_PROM_QUERY_VARIABLES}`,
sampleVariables,
);
return wrapper.vm.$nextTick(() => {
const allInputs = findAllFormInputs();
expect(allInputs).toHaveLength(Object.keys(sampleVariables).length);
});
});
describe('when changing the variable inputs', () => {
const fetchDashboardData = jest.fn();
beforeEach(() => {
store = new Vuex.Store({
modules: {
monitoringDashboard: {
namespaced: true,
state: {
showEmptyState: false,
promVariables: sampleVariables,
},
actions: {
fetchDashboardData,
},
},
},
});
createShallowWrapper();
});
it('merges the url params and refreshes the dashboard when a form input is blurred', () => {
const firstInput = getInputAt(0);
firstInput.vm.$emit('input');
firstInput.vm.$emit('blur');
expect(mergeUrlParams).toHaveBeenCalledWith(sampleVariables, window.location.href);
expect(updateHistory).toHaveBeenCalled();
expect(fetchDashboardData).toHaveBeenCalled();
});
it('merges the url params and refreshes the dashboard when a form input has received an enter key press', () => {
const firstInput = getInputAt(0);
firstInput.vm.$emit('input');
firstInput.trigger('keyup.enter');
expect(mergeUrlParams).toHaveBeenCalledWith(sampleVariables, window.location.href);
expect(updateHistory).toHaveBeenCalled();
expect(fetchDashboardData).toHaveBeenCalled();
});
});
});
......@@ -323,4 +323,24 @@ describe('Monitoring store Getters', () => {
expect(metricsSavedToDb).toEqual([`${id1}_${metric1.id}`, `${id2}_${metric2.id}`]);
});
});
describe('getCustomVariablesArray', () => {
let state;
const sampleVariables = {
label1: 'pod',
};
beforeEach(() => {
state = {
promVariables: {},
};
});
it('transforms the promVariables object to an array in the [variable, variable_value] format', () => {
mutations[types.SET_PROM_QUERY_VARIABLES](state, sampleVariables);
const variablesArray = getters.getCustomVariablesArray(state);
expect(variablesArray).toEqual(['label1', 'pod']);
});
});
});
......@@ -369,13 +369,13 @@ describe('Monitoring mutations', () => {
it('stores an empty variables array when no custom variables are given', () => {
mutations[types.SET_PROM_QUERY_VARIABLES](stateCopy, {});
expect(stateCopy.promVariables).toEqual([]);
expect(stateCopy.promVariables).toEqual({});
});
it('stores variables in the key key_value format in the array', () => {
mutations[types.SET_PROM_QUERY_VARIABLES](stateCopy, { pod: 'POD', stage: 'main ops' });
expect(stateCopy.promVariables).toEqual(['pod', 'POD', 'stage', 'main%20ops']);
expect(stateCopy.promVariables).toEqual({ pod: 'POD', stage: 'main ops' });
});
});
});
......@@ -23,6 +23,12 @@ export const setupStoreWithDashboard = $store => {
);
};
export const setupStoreWithVariable = $store => {
$store.commit(`monitoringDashboard/${types.SET_PROM_QUERY_VARIABLES}`, {
label1: 'pod',
});
};
export const setupStoreWithData = $store => {
setupStoreWithDashboard($store);
......
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