grafana/public/app/features/templating/template_srv.ts

361 lines
10 KiB
TypeScript
Raw Normal View History

import { escape, isString } from 'lodash';
import {
deprecationWarning,
ScopedVars,
TimeRange,
AdHocVariableFilter,
AdHocVariableModel,
TypedVariableModel,
ScopedVar,
} from '@grafana/data';
import {
getDataSourceSrv,
setTemplateSrv,
TemplateSrv as BaseTemplateSrv,
VariableInterpolation,
} from '@grafana/runtime';
import { sceneGraph, VariableCustomFormatterFn } from '@grafana/scenes';
import { VariableFormatID } from '@grafana/schema';
import { variableAdapters } from '../variables/adapters';
import { ALL_VARIABLE_TEXT, ALL_VARIABLE_VALUE } from '../variables/constants';
import { isAdHoc } from '../variables/guard';
import { getFilteredVariables, getVariables, getVariableWithName } from '../variables/state/selectors';
import { variableRegex } from '../variables/utils';
import { getFieldAccessor } from './fieldAccessorCache';
import { formatVariableValue } from './formatVariableValue';
import { macroRegistry } from './macroRegistry';
/**
* Internal regex replace function
*/
type ReplaceFunction = (fullMatch: string, variableName: string, fieldPath: string, format: string) => string;
export interface TemplateSrvDependencies {
getFilteredVariables: typeof getFilteredVariables;
getVariables: typeof getVariables;
getVariableWithName: typeof getVariableWithName;
}
const runtimeDependencies: TemplateSrvDependencies = {
getFilteredVariables,
getVariables,
getVariableWithName,
};
export class TemplateSrv implements BaseTemplateSrv {
private _variables: any[];
private regex = variableRegex;
private index: any = {};
private grafanaVariables = new Map<string, any>();
Templating: Migrates some variable types from Angular to React/Redux (#22434) * 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>
2020-03-10 02:53:41 -05:00
private timeRange?: TimeRange | null = null;
constructor(private dependencies: TemplateSrvDependencies = runtimeDependencies) {
this._variables = [];
}
init(variables: any, timeRange?: TimeRange) {
this._variables = variables;
2019-01-29 08:05:28 -06:00
this.timeRange = timeRange;
this.updateIndex();
}
/**
* @deprecated: this instance variable should not be used and will be removed in future releases
*
* Use getVariables function instead
*/
get variables(): any[] {
deprecationWarning('template_srv.ts', 'variables', 'getVariables');
return this.getVariables();
}
getVariables(): TypedVariableModel[] {
return this.dependencies.getVariables();
}
updateIndex() {
const existsOrEmpty = (value: any) => value || value === '';
this.index = this._variables.reduce((acc, currentValue) => {
if (currentValue.current && (currentValue.current.isNone || existsOrEmpty(currentValue.current.value))) {
acc[currentValue.name] = currentValue;
}
return acc;
}, {});
2019-01-29 08:05:28 -06:00
if (this.timeRange) {
const from = this.timeRange.from.valueOf().toString();
const to = this.timeRange.to.valueOf().toString();
this.index = {
...this.index,
['__from']: {
current: { value: from, text: from },
},
['__to']: {
current: { value: to, text: to },
},
};
}
}
updateTimeRange(timeRange: TimeRange) {
2019-01-29 08:05:28 -06:00
this.timeRange = timeRange;
this.updateIndex();
}
variableInitialized(variable: any) {
this.index[variable.name] = variable;
}
getAdhocFilters(datasourceName: string): AdHocVariableFilter[] {
let filters: any = [];
let ds = getDataSourceSrv().getInstanceSettings(datasourceName);
if (!ds) {
return [];
}
Variables: migrates ad hoc variable type to react/redux. (#22784) * Refactor: moves all the newVariables part to features/variables directory * Feature: adds datasource type * Tests: adds reducer tests * Tests: covers data source actions with tests * Chore: reduces strict null errors * boilerplate that will be replaced by real code. * added old editor template. * added initial version of ad hoc editor. * added working (apart from add) version of the editor. * Added placeholder for picker. * Have a working UI. Need to connect it so we refresh the variables on changes. * variable should be updated now. * removed console.log * made the url work. * cleaned up the adapter. * added possiblity to create filter directly from table. * moved infotext from general reducer to extended value of adhoc. * fixed strict null errors. * fixed strict null errors. * fixed issue where remove was displayed before being added. * fixed issue with fragment key. * changed so template_src is using the redux variables. * minor refactorings. * moved adhoc picker to adhoc variable. * adding tests for reducer and fixed bug. * added tests or urlparser. * added tests for ad hoc actions. * added more tests. * added more tests. * fixed strict null error. * fixed copy n pase error. * added utilit for getting new variable index. * removed console.log * added location to reducerTester type and created a module type for it. * changed so we only have one builder pattern. * fixed tests to use static expected values. * fixed strict errors. * fixed more strict errors. Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com>
2020-03-23 03:00:36 -05:00
for (const variable of this.getAdHocVariables()) {
const variableUid = variable.datasource?.uid;
if (variableUid === ds.uid) {
Variables: migrates ad hoc variable type to react/redux. (#22784) * Refactor: moves all the newVariables part to features/variables directory * Feature: adds datasource type * Tests: adds reducer tests * Tests: covers data source actions with tests * Chore: reduces strict null errors * boilerplate that will be replaced by real code. * added old editor template. * added initial version of ad hoc editor. * added working (apart from add) version of the editor. * Added placeholder for picker. * Have a working UI. Need to connect it so we refresh the variables on changes. * variable should be updated now. * removed console.log * made the url work. * cleaned up the adapter. * added possiblity to create filter directly from table. * moved infotext from general reducer to extended value of adhoc. * fixed strict null errors. * fixed strict null errors. * fixed issue where remove was displayed before being added. * fixed issue with fragment key. * changed so template_src is using the redux variables. * minor refactorings. * moved adhoc picker to adhoc variable. * adding tests for reducer and fixed bug. * added tests or urlparser. * added tests for ad hoc actions. * added more tests. * added more tests. * fixed strict null error. * fixed copy n pase error. * added utilit for getting new variable index. * removed console.log * added location to reducerTester type and created a module type for it. * changed so we only have one builder pattern. * fixed tests to use static expected values. * fixed strict errors. * fixed more strict errors. Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com>
2020-03-23 03:00:36 -05:00
filters = filters.concat(variable.filters);
} else if (variableUid?.indexOf('$') === 0) {
if (this.replace(variableUid) === datasourceName) {
filters = filters.concat(variable.filters);
}
}
}
return filters;
}
setGrafanaVariable(name: string, value: any) {
this.grafanaVariables.set(name, value);
}
/**
* @deprecated: setGlobalVariable function should not be used and will be removed in future releases
*
* Use addVariable action to add variables to Redux instead
*/
setGlobalVariable(name: string, variable: any) {
deprecationWarning('template_srv.ts', 'setGlobalVariable', '');
this.index = {
...this.index,
[name]: {
current: variable,
},
};
}
getVariableName(expression: string) {
this.regex.lastIndex = 0;
const match = this.regex.exec(expression);
if (!match) {
return null;
}
const variableName = match.slice(1).find((match) => match !== undefined);
return variableName;
}
containsTemplate(target: string | undefined): boolean {
if (!target) {
return false;
}
const name = this.getVariableName(target);
const variable = name && this.getVariableAtIndex(name);
return variable !== null && variable !== undefined;
}
variableExists(expression: string): boolean {
deprecationWarning('template_srv.ts', 'variableExists', 'containsTemplate');
return this.containsTemplate(expression);
}
highlightVariablesAsHtml(str: string) {
if (!str || !isString(str)) {
return str;
}
str = escape(str);
return this._replaceWithVariableRegex(str, undefined, (match, variableName) => {
if (this.getVariableAtIndex(variableName)) {
2017-12-20 05:33:33 -06:00
return '<span class="template-variable">' + match + '</span>';
}
return match;
});
}
getAllValue(variable: any) {
if (variable.allValue) {
return variable.allValue;
}
const values = [];
for (let i = 1; i < variable.options.length; i++) {
values.push(variable.options[i].value);
}
return values;
}
private getVariableValue(scopedVar: ScopedVar, fieldPath: string | undefined) {
DataLinks: enable access to labels & field names (#18918) * POC: trying to see if there is a way to support objects in template interpolations * Added support for nested objects, and arrays * Added accessor cache * fixed unit tests * First take * Use links supplier in graph * Add field's index to cache items * Get field index from field cache * CHange FiledCacheItem to FieldWithIndex * Add refId to TimeSeries class * Make field link supplier work with _series, _field and _value vars * use field link supplier in graph * Fix yaxis settings * Update dashboard schema version and add migration for data links variables * Update snapshots * Update build in data link variables * FieldCache - idx -> index * Add current query results to panel editor * WIP Updated data links dropdown to display new variables * Fix build * Update variables syntac in field display, update migration * Field links supplier: review updates * Add data frame view and field name to TimeSeries for later inspection * Retrieve data frame from TimeSeries when clicking on plot graph * Use data frame's index instead of view * Retrieve data frame by index instead of view on TimeSeries * Update data links prism regex * Fix typecheck * Add value variables to suggestions list * UI update * Rename field to config in DisplayProcessorOptions * Proces single value of a field instead of entire data frame * Updated font size from 10px to 12px for auto complete * Replace fieldName with fieldIndex in TimeSeries * Don't use .entries() for iterating in field cache * Don't use FieldCache when retrieving field for datalinks in graph * Add value calculation variable to data links (#19031) * Add support for labels with dots in the name (#19033) * Docs update * Use field name instead of removed series.fieldName * Add test dashboard * Typos fix * Make visualization tab subscribe to query results * Added tags to dashboard so it shows up in lists * minor docs fix * Update singlestat-ish variables suggestions to contain series variables * Decrease suggestions update debounce * Enable whitespace characters(new line, space) in links and strip them when processing the data link * minor data links UI update * DataLinks: Add __from and __to variables suggestions to data links (#19093) * Add from and to variables suggestions to data links * Update docs * UI update and added info text * Change ESC global bind to bind (doesn't capture ESC on input) * Close datalinks suggestions on ESC * Remove unnecessary fragment
2019-09-13 09:38:21 -05:00
if (fieldPath) {
return getFieldAccessor(fieldPath)(scopedVar.value);
DataLinks: enable access to labels & field names (#18918) * POC: trying to see if there is a way to support objects in template interpolations * Added support for nested objects, and arrays * Added accessor cache * fixed unit tests * First take * Use links supplier in graph * Add field's index to cache items * Get field index from field cache * CHange FiledCacheItem to FieldWithIndex * Add refId to TimeSeries class * Make field link supplier work with _series, _field and _value vars * use field link supplier in graph * Fix yaxis settings * Update dashboard schema version and add migration for data links variables * Update snapshots * Update build in data link variables * FieldCache - idx -> index * Add current query results to panel editor * WIP Updated data links dropdown to display new variables * Fix build * Update variables syntac in field display, update migration * Field links supplier: review updates * Add data frame view and field name to TimeSeries for later inspection * Retrieve data frame from TimeSeries when clicking on plot graph * Use data frame's index instead of view * Retrieve data frame by index instead of view on TimeSeries * Update data links prism regex * Fix typecheck * Add value variables to suggestions list * UI update * Rename field to config in DisplayProcessorOptions * Proces single value of a field instead of entire data frame * Updated font size from 10px to 12px for auto complete * Replace fieldName with fieldIndex in TimeSeries * Don't use .entries() for iterating in field cache * Don't use FieldCache when retrieving field for datalinks in graph * Add value calculation variable to data links (#19031) * Add support for labels with dots in the name (#19033) * Docs update * Use field name instead of removed series.fieldName * Add test dashboard * Typos fix * Make visualization tab subscribe to query results * Added tags to dashboard so it shows up in lists * minor docs fix * Update singlestat-ish variables suggestions to contain series variables * Decrease suggestions update debounce * Enable whitespace characters(new line, space) in links and strip them when processing the data link * minor data links UI update * DataLinks: Add __from and __to variables suggestions to data links (#19093) * Add from and to variables suggestions to data links * Update docs * UI update and added info text * Change ESC global bind to bind (doesn't capture ESC on input) * Close datalinks suggestions on ESC * Remove unnecessary fragment
2019-09-13 09:38:21 -05:00
}
return scopedVar.value;
}
private getVariableText(scopedVar: ScopedVar, value: any) {
if (scopedVar.value === value || typeof value !== 'string') {
return scopedVar.text;
}
return value;
}
replace(
target?: string,
scopedVars?: ScopedVars,
format?: string | Function | undefined,
interpolations?: VariableInterpolation[]
): string {
if (scopedVars && scopedVars.__sceneObject) {
return sceneGraph.interpolate(
scopedVars.__sceneObject.value,
target,
scopedVars,
format as string | VariableCustomFormatterFn | undefined
);
}
if (!target) {
return target ?? '';
}
this.regex.lastIndex = 0;
return this._replaceWithVariableRegex(target, format, (match, variableName, fieldPath, fmt) => {
const value = this._evaluateVariableExpression(match, variableName, fieldPath, fmt, scopedVars);
DataLinks: enable access to labels & field names (#18918) * POC: trying to see if there is a way to support objects in template interpolations * Added support for nested objects, and arrays * Added accessor cache * fixed unit tests * First take * Use links supplier in graph * Add field's index to cache items * Get field index from field cache * CHange FiledCacheItem to FieldWithIndex * Add refId to TimeSeries class * Make field link supplier work with _series, _field and _value vars * use field link supplier in graph * Fix yaxis settings * Update dashboard schema version and add migration for data links variables * Update snapshots * Update build in data link variables * FieldCache - idx -> index * Add current query results to panel editor * WIP Updated data links dropdown to display new variables * Fix build * Update variables syntac in field display, update migration * Field links supplier: review updates * Add data frame view and field name to TimeSeries for later inspection * Retrieve data frame from TimeSeries when clicking on plot graph * Use data frame's index instead of view * Retrieve data frame by index instead of view on TimeSeries * Update data links prism regex * Fix typecheck * Add value variables to suggestions list * UI update * Rename field to config in DisplayProcessorOptions * Proces single value of a field instead of entire data frame * Updated font size from 10px to 12px for auto complete * Replace fieldName with fieldIndex in TimeSeries * Don't use .entries() for iterating in field cache * Don't use FieldCache when retrieving field for datalinks in graph * Add value calculation variable to data links (#19031) * Add support for labels with dots in the name (#19033) * Docs update * Use field name instead of removed series.fieldName * Add test dashboard * Typos fix * Make visualization tab subscribe to query results * Added tags to dashboard so it shows up in lists * minor docs fix * Update singlestat-ish variables suggestions to contain series variables * Decrease suggestions update debounce * Enable whitespace characters(new line, space) in links and strip them when processing the data link * minor data links UI update * DataLinks: Add __from and __to variables suggestions to data links (#19093) * Add from and to variables suggestions to data links * Update docs * UI update and added info text * Change ESC global bind to bind (doesn't capture ESC on input) * Close datalinks suggestions on ESC * Remove unnecessary fragment
2019-09-13 09:38:21 -05:00
// If we get passed this interpolations map we will also record all the expressions that were replaced
if (interpolations) {
interpolations.push({ match, variableName, fieldPath, format: fmt, value, found: value !== match });
}
return value;
});
}
private _evaluateVariableExpression(
match: string,
variableName: string,
fieldPath: string,
format: string | VariableCustomFormatterFn | undefined,
scopedVars: ScopedVars | undefined
) {
const variable = this.getVariableAtIndex(variableName);
const scopedVar = scopedVars?.[variableName];
if (scopedVar) {
const value = this.getVariableValue(scopedVar, fieldPath);
const text = this.getVariableText(scopedVar, value);
if (value !== null && value !== undefined) {
return formatVariableValue(value, format, variable, text);
}
}
if (!variable) {
const macro = macroRegistry[variableName];
if (macro) {
return macro(match, fieldPath, scopedVars, format);
}
return match;
}
if (format === VariableFormatID.QueryParam || isAdHoc(variable)) {
const value = variableAdapters.get(variable.type).getValueForUrl(variable);
const text = isAdHoc(variable) ? variable.id : variable.current.text;
return formatVariableValue(value, format, variable, text);
}
const systemValue = this.grafanaVariables.get(variable.current.value);
if (systemValue) {
return formatVariableValue(systemValue, format, variable);
}
let value = variable.current.value;
let text = variable.current.text;
if (this.isAllValue(value)) {
value = this.getAllValue(variable);
text = ALL_VARIABLE_TEXT;
// skip formatting of custom all values unless format set to text or percentencode
if (variable.allValue && format !== VariableFormatID.Text && format !== VariableFormatID.PercentEncode) {
return this.replace(value);
}
}
if (fieldPath) {
const fieldValue = this.getVariableValue({ value, text }, fieldPath);
if (fieldValue !== null && fieldValue !== undefined) {
return formatVariableValue(fieldValue, format, variable, text);
}
}
return formatVariableValue(value, format, variable, text);
}
/**
* Tries to unify the different variable format capture groups into a simpler replacer function
*/
private _replaceWithVariableRegex(text: string, format: string | Function | undefined, replace: ReplaceFunction) {
this.regex.lastIndex = 0;
return text.replace(this.regex, (match, var1, var2, fmt2, var3, fieldPath, fmt3) => {
const variableName = var1 || var2 || var3;
const fmt = fmt2 || fmt3 || format;
return replace(match, variableName, fieldPath, fmt);
});
}
isAllValue(value: any) {
return value === ALL_VARIABLE_VALUE || (Array.isArray(value) && value[0] === ALL_VARIABLE_VALUE);
}
replaceWithText(target: string, scopedVars?: ScopedVars) {
deprecationWarning('template_srv.ts', 'replaceWithText()', 'replace(), and specify the :text format');
return this.replace(target, scopedVars, 'text');
}
private getVariableAtIndex(name: string) {
Templating: Migrates some variable types from Angular to React/Redux (#22434) * 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>
2020-03-10 02:53:41 -05:00
if (!name) {
return;
}
if (!this.index[name]) {
return this.dependencies.getVariableWithName(name);
Templating: Migrates some variable types from Angular to React/Redux (#22434) * 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>
2020-03-10 02:53:41 -05:00
}
return this.index[name];
}
Variables: migrates ad hoc variable type to react/redux. (#22784) * Refactor: moves all the newVariables part to features/variables directory * Feature: adds datasource type * Tests: adds reducer tests * Tests: covers data source actions with tests * Chore: reduces strict null errors * boilerplate that will be replaced by real code. * added old editor template. * added initial version of ad hoc editor. * added working (apart from add) version of the editor. * Added placeholder for picker. * Have a working UI. Need to connect it so we refresh the variables on changes. * variable should be updated now. * removed console.log * made the url work. * cleaned up the adapter. * added possiblity to create filter directly from table. * moved infotext from general reducer to extended value of adhoc. * fixed strict null errors. * fixed strict null errors. * fixed issue where remove was displayed before being added. * fixed issue with fragment key. * changed so template_src is using the redux variables. * minor refactorings. * moved adhoc picker to adhoc variable. * adding tests for reducer and fixed bug. * added tests or urlparser. * added tests for ad hoc actions. * added more tests. * added more tests. * fixed strict null error. * fixed copy n pase error. * added utilit for getting new variable index. * removed console.log * added location to reducerTester type and created a module type for it. * changed so we only have one builder pattern. * fixed tests to use static expected values. * fixed strict errors. * fixed more strict errors. Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com>
2020-03-23 03:00:36 -05:00
private getAdHocVariables(): AdHocVariableModel[] {
return this.dependencies.getFilteredVariables(isAdHoc) as AdHocVariableModel[];
}
}
// Expose the template srv
const srv = new TemplateSrv();
setTemplateSrv(srv);
export const getTemplateSrv = () => srv;