mirror of
https://github.com/grafana/grafana.git
synced 2025-02-13 00:55:47 -06:00
* Refactor: Adds variables in state to TemplateSrv * Refactor: Introduces some typings and structures * Refactor: Introduces picker to adapter * Refactor: Removes useState and introduces contains instead * Refactor: Introduces Variable Editor * Refactor: Adds uuid and simplifies state * Refactor: Consolidates to VariableRenderer * Refactor: Adds name change capability * Refactor: Adds variableMiddleware * Refactor: Adds ability to change Angular type to type in State * Fix: Fixes so we check for duplicate names * Refactor: Adds ability to change State type to type in Angular * Refactor: Updates name in dashboard templating list * Refactor: Adds label change to VariableEditor * Refactor: Adds hide change to VariableEditor * Refactor: Adds update ability * Refactor: Adds tooltip * Refactor: Adds SelectionOptionsEditor * Refactor: Adds query editor and validation * Refactor: Adds regex and sort to editor * Refactor: Adds Selection options * Refactor: Adds Varible Values Previewer * Refactor: Changes from array in state to Record * Refactor: Removes getVariableAtIndex from templateSrv * Tests: Fixs broken tests * Chore: Fixes duplicate merge import * Refactor: Removes strict null errors * Refactor: Adds duplicate variable * Refactor: Adds remove variable * Refactor: Adds change order of variables * Refactor: Adds add new variable * Chore: Fixes Prettier formatting * Refactor: Adds VariablePicker * Fixed so sub menu is displayed when we only have redux template variables. * removed unused variable. * tags will be visibile in the new react picker. * added some nice colors to the tags. * Added thunk for selecting a tag. * Refactor: Cleans up templating state when dashboard unloads * Refactor: Adds save capabilities for variables in state * added possibility to select tag. * Added so you can deselect a tag. * Fixed issue with coloring on top. * minor refactoring to make the code more slim. * Refactor: Fixes dispatch return and copy of variable * selecting options when tag i selected * small refactoring. * fixed so we use options. * Refactor: Adds getValueForUrl capabilities * first implementation of keyboard navigation on picker. * removed comment. * fixed so you can toggle all options. * Refactor: Simplified state handling using Redux Toolkit and flat reducer structure * Refactor: Adds sharedTemplatingReducer and queryVariableReducer * Tests: Fixs broken tests * Chore: Removes some strict null errors * Tests: Fix broken tests * Refactor: Splitted QueryVariablePicker into smaller components * Refactor: Moves linktext and selected tags to component instead * Fix: Fixes the ability to have multiple dropdowns opened at same time * Fix: Fixes onKeyDown from prev refactor * Refactor: Adds searchfilter searching * Tests: Fixes after running e2e tests * Refactor: Adds an attempt to solve dependencies at startup * Refactor: Adds feature toggle * Refactor: Resets all angular files to master * Refactor: Move stuff to query folder * Refactor: Initial commit for SubMenu component * Refactor: Updated DashboardModel with new list * Refactor: Adds feature toggle to dashboard model and friends * Refactor: Adds picker to SubMenu * Refactor: Fixes styling on SubMenu * Refactor: Fixes processvariables * Refactor: Initial EditorList skeleton * Refactor: Refactors out VariableEditorList and VariableEditorContainer * Refactor: Adds New variable functionality * Refactor: Adds registred types * Refactor: Adds edit existing variable functionality * Refactor: Changes params to thunks * Refactor: Small fix for cleaning up state when clicking update/add * Refactor: Better typings for outer containers * Refactor: Adds change order functionality * Refactor: Removed notify angular args * Change so the url is in sync with the redux template variables. * Adding support for saving proper values and checking changes. * Refactor: Adds duplicate variable functionality * Feature: Adds remove variable functionality * Refactor: Small refactor so e2e tests work as before * Refactor: Returns null if no visible variables * Refactor: Adds annotations to SubMenu * Refactor: Fixes toggling of annotations in SubMenu * added dashboard links to new submehu. * Refactor: Small refactor breaking up into smaller components * Fix: Fixes infinite recursive loop when changing varible name * Templating: Do not mutate location query state * Refactor: Fixes minor timing issue when adding new variable * Refactor: removes initialization in variable_srv constructor * Refactor: Suggestion on how to handle templating.list in DashboardExporter * Refactor: Adds getVariables typings and changes ChangeTracker and ShareSnapshotCtrl * Refactor: Adds getVariable on DashboardModel and changes DashboardMigrator * Fix: Fixes repeated panels * wip: starting to add custom variable type. * Refactor: Merging two different toVariablePayload functions * Tests: Fixes broken tests * Fix: Reduces strict null errors * Tests: Initial commit and fixes strange dependency order * Tests: Covers sharedTemplatingReducer with tests * Refactor: Rename state/index.ts => state/reducers.ts as every where else * Refactor: Renames and moves adapters.ts * Tests: Adds tests for templatingReducer * Tests: Adds intitial tests for queryVariableReducer * starting to ad custom variable. * Tests: Adds more queryVariableReducer tests * Added support for custom variable. Next up applying some DRY principles and refactoring. * fixed compile issue. * added todo. * Tests: Fixes broken test * Tests: Covers queryVariableReducer with tests and fixed a couple of bugs * Fix: Fixes broken test * Fix: Reduces strict null errors * change so custom won't be depending on anything elese. * fixed descriptions. * removed unused dependency. * Fixed issue when adding a new variable and editor is being unmount twice. * fixed issue with select option loop. * changed so we update query on typing in editor and removed it from component state. * Moved runQuery up one level in the component tree. * renamed action and moved it to custom actions. * moved applyStateChanges to shared code. * removed todo comment. * first stab on moving picker to more general. * Refactor: Changes so we always show variables type * removed duplicate code regarding picker. * Did some renamings. * Feature: Adds text box variable type * moved tests from query reducer to picker reducer. * Removed picker from VariableState. * removed reference to picker. * Some more refactorings of the picker reducer + actions. * Chore: Refactors away editor state to its own state slice (#22515) * Refactor: Inital move, tests not working * Tests: Adds editorReducer tests * Refactor: Cleaning up * Refactor: Moves logic to thunk instead * Refactor: Initial commit * Refactor: Combines reducers to one state * Refactor: Adds combine reducers * moved navigation logic flow to a thunk instead of in the component. * fixed issue with rendering picker link. * Refactor: Removes variable prop from templating.variables * refactored and removed some more code. * Feature: adds Constant variable type * fixed so tags can be selected. * Fix: fixes default hide for constant and enum order * fixed so tags works again. * Fix: fixes so we use Angular editor when newVariables is not defined * Fix: fixes wrong hide default for Constant variable * Fix: fixes bug when using duplicate button * Fix: changes action id * Tests: prepares for newVariables * Chore: reduces strict null errors * Refactor: removes uuidInEditorReducer for simplification * Chore: changes after PR comments * Chore: uses getConfig instead of config * Tests: fixes so e2e tests check for feature toggle and fixed initLock bug * Refactor: changes so sharedReducer uses createSlice instead * Refactor: changes textBoxVariableReducer to use creactSlice instead * Refactor: changes queryBoxVariableReducer to use creactSlice instead * Refactor: changes customVariableReducer to use creactSlice instead * Refactor: changes constantVariableReducer to use creactSlice instead * Refactor: moves types to specific types.ts files instead * changed so we use queryValue stored on the variable to populate options input when opening picker. * Feature: adds the ability to test templating thunks using real store and middleware * Chore: cleans up unused import * excluded queryValue from the getSaveModel * Refactor: adds whenAsyncActionIsDispatched to reduxTester * Tests: adds initial tests for processVariables * Added reducer tests for constant variable. * added tests for custom reducer. * added tets for texbox reducer. * Tests: adds more tests for ProcessVariable * Refactor: fixes processVariable flow so we do notrun updateOptions twice * Tests: finishes tests for processVariables and removed skip test * added actions tests for custom and constant. * Tests: adds tests for setOptionFromUrl * Tests: adds a naive variable mock builder * Tests: adds tests for validateVariableSelectionState * added tests for query variable actions. * added last test for query actions. * added more tests. * some more tests. * fixed typing errors. * Fixed issues with variable tags. Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com> Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
411 lines
12 KiB
TypeScript
411 lines
12 KiB
TypeScript
// Libaries
|
|
import angular, { auto, ILocationService, IPromise, IQService } from 'angular';
|
|
import _ from 'lodash';
|
|
// Utils & Services
|
|
import coreModule from 'app/core/core_module';
|
|
import { variableTypes } from './variable';
|
|
import { Graph } from 'app/core/utils/dag';
|
|
import { TemplateSrv } from 'app/features/templating/template_srv';
|
|
import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
|
|
import { DashboardModel } from 'app/features/dashboard/state/DashboardModel';
|
|
// Types
|
|
import { AppEvents, TimeRange } from '@grafana/data';
|
|
import { CoreEvents } from 'app/types';
|
|
import { UrlQueryMap } from '@grafana/runtime';
|
|
import { appEvents, contextSrv } from 'app/core/core';
|
|
|
|
export class VariableSrv {
|
|
dashboard: DashboardModel;
|
|
variables: any[] = [];
|
|
|
|
/** @ngInject */
|
|
constructor(
|
|
private $q: IQService,
|
|
private $location: ILocationService,
|
|
private $injector: auto.IInjectorService,
|
|
private templateSrv: TemplateSrv,
|
|
private timeSrv: TimeSrv
|
|
) {}
|
|
|
|
init(dashboard: DashboardModel) {
|
|
this.dashboard = dashboard;
|
|
this.dashboard.events.on(CoreEvents.timeRangeUpdated, this.onTimeRangeUpdated.bind(this));
|
|
this.dashboard.events.on(
|
|
CoreEvents.templateVariableValueUpdated,
|
|
this.updateUrlParamsWithCurrentVariables.bind(this)
|
|
);
|
|
|
|
// create working class models representing variables
|
|
this.variables = dashboard.templating.list = dashboard.templating.list.map(this.createVariableFromModel.bind(this));
|
|
this.templateSrv.init(this.variables, this.timeSrv.timeRange());
|
|
|
|
// init variables
|
|
for (const variable of this.variables) {
|
|
variable.initLock = this.$q.defer();
|
|
}
|
|
|
|
const queryParams = this.$location.search();
|
|
return this.$q
|
|
.all(
|
|
this.variables.map(variable => {
|
|
return this.processVariable(variable, queryParams);
|
|
})
|
|
)
|
|
.then(() => {
|
|
this.templateSrv.updateIndex();
|
|
this.templateSrv.setGlobalVariable('__dashboard', {
|
|
value: {
|
|
name: dashboard.title,
|
|
uid: dashboard.uid,
|
|
toString: function() {
|
|
return this.uid;
|
|
},
|
|
},
|
|
});
|
|
this.templateSrv.setGlobalVariable('__org', {
|
|
value: {
|
|
name: contextSrv.user.orgName,
|
|
id: contextSrv.user.id,
|
|
toString: function() {
|
|
return this.id;
|
|
},
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
onTimeRangeUpdated(timeRange: TimeRange) {
|
|
this.templateSrv.updateTimeRange(timeRange);
|
|
const promises = this.variables
|
|
.filter(variable => variable.refresh === 2)
|
|
.map(variable => {
|
|
const previousOptions = variable.options.slice();
|
|
|
|
return variable.updateOptions().then(() => {
|
|
if (angular.toJson(previousOptions) !== angular.toJson(variable.options)) {
|
|
this.dashboard.templateVariableValueUpdated();
|
|
}
|
|
});
|
|
});
|
|
|
|
return this.$q
|
|
.all(promises)
|
|
.then(() => {
|
|
this.dashboard.startRefresh();
|
|
})
|
|
.catch(e => {
|
|
appEvents.emit(AppEvents.alertError, ['Template variable service failed', e.message]);
|
|
});
|
|
}
|
|
|
|
processVariable(variable: any, queryParams: any) {
|
|
const dependencies = [];
|
|
|
|
for (const otherVariable of this.variables) {
|
|
if (variable.dependsOn(otherVariable)) {
|
|
dependencies.push(otherVariable.initLock.promise);
|
|
}
|
|
}
|
|
|
|
return this.$q
|
|
.all(dependencies)
|
|
.then(() => {
|
|
const urlValue = queryParams['var-' + variable.name];
|
|
if (urlValue !== void 0) {
|
|
return variable.setValueFromUrl(urlValue).then(variable.initLock.resolve);
|
|
}
|
|
|
|
if (variable.refresh === 1 || variable.refresh === 2) {
|
|
return variable.updateOptions().then(variable.initLock.resolve);
|
|
}
|
|
|
|
variable.initLock.resolve();
|
|
})
|
|
.finally(() => {
|
|
this.templateSrv.variableInitialized(variable);
|
|
delete variable.initLock;
|
|
});
|
|
}
|
|
|
|
createVariableFromModel(model: any) {
|
|
// @ts-ignore
|
|
const ctor = variableTypes[model.type].ctor;
|
|
if (!ctor) {
|
|
throw {
|
|
message: 'Unable to find variable constructor for ' + model.type,
|
|
};
|
|
}
|
|
|
|
const variable = this.$injector.instantiate(ctor, { model: model });
|
|
return variable;
|
|
}
|
|
|
|
addVariable(variable: any) {
|
|
this.variables.push(variable);
|
|
this.templateSrv.updateIndex();
|
|
this.dashboard.updateSubmenuVisibility();
|
|
}
|
|
|
|
removeVariable(variable: any) {
|
|
const index = _.indexOf(this.variables, variable);
|
|
this.variables.splice(index, 1);
|
|
this.templateSrv.updateIndex();
|
|
this.dashboard.updateSubmenuVisibility();
|
|
}
|
|
|
|
updateOptions(variable: any) {
|
|
return variable.updateOptions();
|
|
}
|
|
|
|
variableUpdated(variable: any, emitChangeEvents?: any) {
|
|
// if there is a variable lock ignore cascading update because we are in a boot up scenario
|
|
if (variable.initLock) {
|
|
return this.$q.when();
|
|
}
|
|
|
|
const g = this.createGraph();
|
|
const node = g.getNode(variable.name);
|
|
let promises = [];
|
|
if (node) {
|
|
promises = node.getOptimizedInputEdges().map(e => {
|
|
return this.updateOptions(this.variables.find(v => v.name === e.inputNode.name));
|
|
});
|
|
}
|
|
|
|
return this.$q.all(promises).then(() => {
|
|
if (emitChangeEvents) {
|
|
this.dashboard.templateVariableValueUpdated();
|
|
this.dashboard.startRefresh();
|
|
}
|
|
});
|
|
}
|
|
|
|
selectOptionsForCurrentValue(variable: any) {
|
|
let i, y, value, option;
|
|
const selected: any = [];
|
|
|
|
for (i = 0; i < variable.options.length; i++) {
|
|
option = variable.options[i];
|
|
option.selected = false;
|
|
if (_.isArray(variable.current.value)) {
|
|
for (y = 0; y < variable.current.value.length; y++) {
|
|
value = variable.current.value[y];
|
|
if (option.value === value) {
|
|
option.selected = true;
|
|
selected.push(option);
|
|
}
|
|
}
|
|
} else if (option.value === variable.current.value) {
|
|
option.selected = true;
|
|
selected.push(option);
|
|
}
|
|
}
|
|
|
|
return selected;
|
|
}
|
|
|
|
validateVariableSelectionState(variable: any, defaultValue?: string) {
|
|
if (!variable.current) {
|
|
variable.current = {};
|
|
}
|
|
|
|
if (_.isArray(variable.current.value)) {
|
|
let selected = this.selectOptionsForCurrentValue(variable);
|
|
|
|
// if none pick first
|
|
if (selected.length === 0) {
|
|
selected = variable.options[0];
|
|
} else {
|
|
selected = {
|
|
value: _.map(selected, val => {
|
|
return val.value;
|
|
}),
|
|
text: _.map(selected, val => {
|
|
return val.text;
|
|
}),
|
|
};
|
|
}
|
|
|
|
return variable.setValue(selected);
|
|
} else {
|
|
let option: any = undefined;
|
|
|
|
// 1. find the current value
|
|
option = _.find(variable.options, {
|
|
text: variable.current.text,
|
|
});
|
|
if (option) {
|
|
return variable.setValue(option);
|
|
}
|
|
|
|
// 2. find the default value
|
|
if (defaultValue) {
|
|
option = _.find(variable.options, {
|
|
text: defaultValue,
|
|
});
|
|
if (option) {
|
|
return variable.setValue(option);
|
|
}
|
|
}
|
|
|
|
// 3. use the first value
|
|
if (variable.options) {
|
|
return variable.setValue(variable.options[0]);
|
|
}
|
|
|
|
// 4... give up
|
|
return Promise.resolve();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Sets the current selected option (or options) based on the query params in the url. It is possible for values
|
|
* in the url to not match current options of the variable. In that case the variables current value will be still set
|
|
* to that value.
|
|
* @param variable Instance of Variable
|
|
* @param urlValue Value of the query parameter
|
|
*/
|
|
setOptionFromUrl(variable: any, urlValue: string | string[]): IPromise<any> {
|
|
let promise = this.$q.when();
|
|
|
|
if (variable.refresh) {
|
|
promise = variable.updateOptions();
|
|
}
|
|
|
|
return promise.then(() => {
|
|
// Simple case. Value in url matches existing options text or value.
|
|
let option: any = _.find(variable.options, op => {
|
|
return op.text === urlValue || op.value === urlValue;
|
|
});
|
|
|
|
// No luck either it is array or value does not exist in the variables options.
|
|
if (!option) {
|
|
let defaultText = urlValue;
|
|
const defaultValue = urlValue;
|
|
|
|
if (_.isArray(urlValue)) {
|
|
// Multiple values in the url. We construct text as a list of texts from all matched options.
|
|
defaultText = urlValue.reduce((acc, item) => {
|
|
const t: any = _.find(variable.options, { value: item });
|
|
if (t) {
|
|
acc.push(t.text);
|
|
} else {
|
|
acc.push(item);
|
|
}
|
|
|
|
return acc;
|
|
}, []);
|
|
}
|
|
|
|
// It is possible that we did not match the value to any existing option. In that case the url value will be
|
|
// used anyway for both text and value.
|
|
option = { text: defaultText, value: defaultValue };
|
|
}
|
|
|
|
if (variable.multi) {
|
|
// In case variable is multiple choice, we cast to array to preserve the same behaviour as when selecting
|
|
// the option directly, which will return even single value in an array.
|
|
option = { text: _.castArray(option.text), value: _.castArray(option.value) };
|
|
}
|
|
|
|
return variable.setValue(option);
|
|
});
|
|
}
|
|
|
|
setOptionAsCurrent(variable: any, option: any) {
|
|
variable.current = _.cloneDeep(option);
|
|
|
|
if (_.isArray(variable.current.text) && variable.current.text.length > 0) {
|
|
variable.current.text = variable.current.text.join(' + ');
|
|
} else if (_.isArray(variable.current.value) && variable.current.value[0] !== '$__all') {
|
|
variable.current.text = variable.current.value.join(' + ');
|
|
}
|
|
|
|
this.selectOptionsForCurrentValue(variable);
|
|
return this.variableUpdated(variable);
|
|
}
|
|
|
|
templateVarsChangedInUrl(vars: UrlQueryMap) {
|
|
const update: Array<Promise<any>> = [];
|
|
for (const v of this.variables) {
|
|
const key = `var-${v.name}`;
|
|
if (vars.hasOwnProperty(key)) {
|
|
update.push(v.setValueFromUrl(vars[key]));
|
|
}
|
|
}
|
|
if (update.length) {
|
|
Promise.all(update).then(() => {
|
|
this.dashboard.templateVariableValueUpdated();
|
|
this.dashboard.startRefresh();
|
|
});
|
|
}
|
|
}
|
|
|
|
updateUrlParamsWithCurrentVariables() {
|
|
// update url
|
|
const params = this.$location.search();
|
|
|
|
// remove variable params
|
|
_.each(params, (value, key) => {
|
|
if (key.indexOf('var-') === 0) {
|
|
delete params[key];
|
|
}
|
|
});
|
|
|
|
// add new values
|
|
this.templateSrv.fillVariableValuesForUrl(params);
|
|
// update url
|
|
this.$location.search(params);
|
|
}
|
|
|
|
setAdhocFilter(options: any) {
|
|
let variable: any = _.find(this.variables, {
|
|
type: 'adhoc',
|
|
datasource: options.datasource,
|
|
} as any);
|
|
if (!variable) {
|
|
variable = this.createVariableFromModel({
|
|
name: 'Filters',
|
|
type: 'adhoc',
|
|
datasource: options.datasource,
|
|
});
|
|
this.addVariable(variable);
|
|
}
|
|
|
|
const filters = variable.filters;
|
|
let filter: any = _.find(filters, { key: options.key, value: options.value });
|
|
|
|
if (!filter) {
|
|
filter = { key: options.key, value: options.value };
|
|
filters.push(filter);
|
|
}
|
|
|
|
filter.operator = options.operator;
|
|
this.variableUpdated(variable, true);
|
|
}
|
|
|
|
createGraph() {
|
|
const g = new Graph();
|
|
|
|
this.variables.forEach(v => {
|
|
g.createNode(v.name);
|
|
});
|
|
|
|
this.variables.forEach(v1 => {
|
|
this.variables.forEach(v2 => {
|
|
if (v1 === v2) {
|
|
return;
|
|
}
|
|
|
|
if (v1.dependsOn(v2)) {
|
|
g.link(v1.name, v2.name);
|
|
}
|
|
});
|
|
});
|
|
|
|
return g;
|
|
}
|
|
}
|
|
|
|
coreModule.service('variableSrv', VariableSrv);
|