grafana/public/app/features/templating/query/QueryVariableEditor.tsx
Marcus Andersson cc813d71c6
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 08:53:41 +01:00

310 lines
12 KiB
TypeScript

import React, { ChangeEvent, PureComponent } from 'react';
import { e2e } from '@grafana/e2e';
import { FormLabel, Switch } from '@grafana/ui';
import templateSrv from '../template_srv';
import { SelectionOptionsEditor } from '../editor/SelectionOptionsEditor';
import { QueryVariableModel, VariableRefresh, VariableSort, VariableWithMultiSupport } from '../variable';
import { QueryVariableEditorState } from './reducer';
import { changeQueryVariableDataSource, changeQueryVariableQuery, initQueryVariableEditor } from './actions';
import { VariableEditorState } from '../editor/reducer';
import { OnPropChangeArguments, VariableEditorProps } from '../editor/types';
import { MapDispatchToProps, MapStateToProps } from 'react-redux';
import { StoreState } from '../../../types';
import { connectWithStore } from '../../../core/utils/connectWithReduxStore';
import { toVariableIdentifier } from '../state/types';
export interface OwnProps extends VariableEditorProps<QueryVariableModel> {}
interface ConnectedProps {
editor: VariableEditorState<QueryVariableEditorState>;
}
interface DispatchProps {
initQueryVariableEditor: typeof initQueryVariableEditor;
changeQueryVariableDataSource: typeof changeQueryVariableDataSource;
changeQueryVariableQuery: typeof changeQueryVariableQuery;
}
type Props = OwnProps & ConnectedProps & DispatchProps;
export interface State {
regex: string | null;
tagsQuery: string | null;
tagValuesQuery: string | null;
}
export class QueryVariableEditorUnConnected extends PureComponent<Props, State> {
state: State = {
regex: null,
tagsQuery: null,
tagValuesQuery: null,
};
async componentDidMount() {
await this.props.initQueryVariableEditor(toVariableIdentifier(this.props.variable));
}
componentDidUpdate(prevProps: Readonly<Props>): void {
if (prevProps.variable.datasource !== this.props.variable.datasource) {
this.props.changeQueryVariableDataSource(
toVariableIdentifier(this.props.variable),
this.props.variable.datasource
);
}
}
getSelectedDataSourceValue = (): string => {
if (!this.props.editor.extended?.dataSources.length) {
return '';
}
const foundItem = this.props.editor.extended?.dataSources.find(ds => ds.value === this.props.variable.datasource);
const value = foundItem ? foundItem.value : this.props.editor.extended?.dataSources[0].value;
return value ?? '';
};
onDataSourceChange = (event: ChangeEvent<HTMLSelectElement>) => {
this.props.onPropChange({ propName: 'query', propValue: '' });
this.props.onPropChange({ propName: 'datasource', propValue: event.target.value });
};
onQueryChange = async (query: any, definition: string) => {
this.props.changeQueryVariableQuery(toVariableIdentifier(this.props.variable), query, definition);
};
onRegExChange = (event: ChangeEvent<HTMLInputElement>) => {
this.setState({ regex: event.target.value });
};
onRegExBlur = async (event: ChangeEvent<HTMLInputElement>) => {
this.props.onPropChange({ propName: 'regex', propValue: event.target.value, updateOptions: true });
};
onTagsQueryChange = async (event: ChangeEvent<HTMLInputElement>) => {
this.setState({ tagsQuery: event.target.value });
};
onTagsQueryBlur = async (event: ChangeEvent<HTMLInputElement>) => {
this.props.onPropChange({ propName: 'tagsQuery', propValue: event.target.value, updateOptions: true });
};
onTagValuesQueryChange = async (event: ChangeEvent<HTMLInputElement>) => {
this.setState({ tagValuesQuery: event.target.value });
};
onTagValuesQueryBlur = async (event: ChangeEvent<HTMLInputElement>) => {
this.props.onPropChange({ propName: 'tagValuesQuery', propValue: event.target.value, updateOptions: true });
};
onRefreshChange = (event: ChangeEvent<HTMLSelectElement>) => {
this.props.onPropChange({ propName: 'refresh', propValue: parseInt(event.target.value, 10) });
};
onSortChange = async (event: ChangeEvent<HTMLSelectElement>) => {
this.props.onPropChange({ propName: 'sort', propValue: parseInt(event.target.value, 10), updateOptions: true });
};
onSelectionOptionsChange = async ({ propValue, propName }: OnPropChangeArguments<VariableWithMultiSupport>) => {
this.props.onPropChange({ propName, propValue, updateOptions: true });
};
onUseTagsChange = async (event: ChangeEvent<HTMLInputElement>) => {
this.props.onPropChange({ propName: 'useTags', propValue: event.target.checked, updateOptions: true });
};
render() {
const VariableQueryEditor = this.props.editor.extended?.VariableQueryEditor;
return (
<>
<div className="gf-form-group">
<h5 className="section-heading">Query Options</h5>
<div className="gf-form-inline">
<div className="gf-form max-width-21">
<span className="gf-form-label width-10">Data source</span>
<div className="gf-form-select-wrapper max-width-14">
<select
className="gf-form-input"
value={this.getSelectedDataSourceValue()}
onChange={this.onDataSourceChange}
required
aria-label={
e2e.pages.Dashboard.Settings.Variables.Edit.QueryVariable.selectors.queryOptionsDataSourceSelect
}
>
{this.props.editor.extended?.dataSources.length &&
this.props.editor.extended?.dataSources.map(ds => (
<option key={ds.value ?? ''} value={ds.value ?? ''} label={ds.name}>
{ds.name}
</option>
))}
</select>
</div>
</div>
<div className="gf-form max-width-22">
<FormLabel width={10} tooltip={'When to update the values of this variable.'}>
Refresh
</FormLabel>
<div className="gf-form-select-wrapper width-15">
<select
className="gf-form-input"
value={this.props.variable.refresh}
onChange={this.onRefreshChange}
aria-label={
e2e.pages.Dashboard.Settings.Variables.Edit.QueryVariable.selectors.queryOptionsRefreshSelect
}
>
<option label="Never" value={VariableRefresh.never}>
Never
</option>
<option label="On Dashboard Load" value={VariableRefresh.onDashboardLoad}>
On Dashboard Load
</option>
<option label="On Time Range Change" value={VariableRefresh.onTimeRangeChanged}>
On Time Range Change
</option>
</select>
</div>
</div>
</div>
{VariableQueryEditor && this.props.editor.extended?.dataSource && (
<VariableQueryEditor
datasource={this.props.editor.extended?.dataSource}
query={this.props.variable.query}
templateSrv={templateSrv}
onChange={this.onQueryChange}
/>
)}
<div className="gf-form">
<FormLabel
width={10}
tooltip={'Optional, if you want to extract part of a series name or metric node segment.'}
>
Regex
</FormLabel>
<input
type="text"
className="gf-form-input"
placeholder="/.*-(.*)-.*/"
value={this.state.regex ?? this.props.variable.regex}
onChange={this.onRegExChange}
onBlur={this.onRegExBlur}
aria-label={e2e.pages.Dashboard.Settings.Variables.Edit.QueryVariable.selectors.queryOptionsRegExInput}
/>
</div>
<div className="gf-form max-width-21">
<FormLabel width={10} tooltip={'How to sort the values of this variable.'}>
Sort
</FormLabel>
<div className="gf-form-select-wrapper max-width-14">
<select
className="gf-form-input"
value={this.props.variable.sort}
onChange={this.onSortChange}
aria-label={e2e.pages.Dashboard.Settings.Variables.Edit.QueryVariable.selectors.queryOptionsSortSelect}
>
<option label="Disabled" value={VariableSort.disabled}>
Disabled
</option>
<option label="Alphabetical (asc)" value={VariableSort.alphabeticalAsc}>
Alphabetical (asc)
</option>
<option label="Alphabetical (desc)" value={VariableSort.alphabeticalDesc}>
Alphabetical (desc)
</option>
<option label="Numerical (asc)" value={VariableSort.numericalAsc}>
Numerical (asc)
</option>
<option label="Numerical (desc)" value={VariableSort.numericalDesc}>
Numerical (desc)
</option>
<option
label="Alphabetical (case-insensitive, asc)"
value={VariableSort.alphabeticalCaseInsensitiveAsc}
>
Alphabetical (case-insensitive, asc)
</option>
<option
label="Alphabetical (case-insensitive, desc)"
value={VariableSort.alphabeticalCaseInsensitiveDesc}
>
Alphabetical (case-insensitive, desc)
</option>
</select>
</div>
</div>
</div>
<SelectionOptionsEditor variable={this.props.variable} onPropChange={this.onSelectionOptionsChange} />
<div className="gf-form-group">
<h5>Value groups/tags (Experimental feature)</h5>
<div
aria-label={
e2e.pages.Dashboard.Settings.Variables.Edit.QueryVariable.selectors.valueGroupsTagsEnabledSwitch
}
>
<Switch
label="Enabled"
label-class="width-10"
checked={this.props.variable.useTags}
onChange={this.onUseTagsChange}
/>
</div>
{this.props.variable.useTags && (
<>
<div className="gf-form last">
<span className="gf-form-label width-10">Tags query</span>
<input
type="text"
className="gf-form-input"
value={this.state.tagsQuery ?? this.props.variable.tagsQuery}
placeholder="metric name or tags query"
onChange={this.onTagsQueryChange}
onBlur={this.onTagsQueryBlur}
aria-label={
e2e.pages.Dashboard.Settings.Variables.Edit.QueryVariable.selectors.valueGroupsTagsTagsQueryInput
}
/>
</div>
<div className="gf-form">
<li className="gf-form-label width-10">Tag values query</li>
<input
type="text"
className="gf-form-input"
value={this.state.tagValuesQuery ?? this.props.variable.tagValuesQuery}
placeholder="apps.$tag.*"
onChange={this.onTagValuesQueryChange}
onBlur={this.onTagValuesQueryBlur}
aria-label={
e2e.pages.Dashboard.Settings.Variables.Edit.QueryVariable.selectors
.valueGroupsTagsTagsValuesQueryInput
}
/>
</div>
</>
)}
</div>
</>
);
}
}
const mapStateToProps: MapStateToProps<ConnectedProps, OwnProps, StoreState> = (state, ownProps) => ({
editor: state.templating.editor as VariableEditorState<QueryVariableEditorState>,
});
const mapDispatchToProps: MapDispatchToProps<DispatchProps, OwnProps> = {
initQueryVariableEditor,
changeQueryVariableDataSource,
changeQueryVariableQuery,
};
export const QueryVariableEditor = connectWithStore(
QueryVariableEditorUnConnected,
mapStateToProps,
mapDispatchToProps
);