grafana/public/app/features/dashboard/panel_editor/QueriesTab.tsx

382 lines
11 KiB
TypeScript
Raw Normal View History

2018-12-11 06:36:44 -06:00
// Libraries
import React, { PureComponent } from 'react';
2018-12-11 06:36:44 -06:00
// Components
2018-12-14 07:05:47 -06:00
import { DataSourcePicker } from 'app/core/components/Select/DataSourcePicker';
import { QueryOptions } from './QueryOptions';
import { Button, CustomScrollbar, HorizontalGroup, Modal, stylesFactory, Field } from '@grafana/ui';
import { getLocationSrv, getDataSourceSrv } from '@grafana/runtime';
import { QueryEditorRows } from './QueryEditorRows';
// Services
import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
Chore: Remove angular dependency from backendSrv (#20999) * Chore: Remove angular dependency from backendSrv * Refactor: Naive soultion for logging out unauthorized users * Refactor: Restructures to different streams * Refactor: Restructures datasourceRequest * Refactor: Flipped back if statement * Refactor: Extracted getFromFetchStream * Refactor: Extracts toFailureStream operation * Refactor: Fixes issue when options.params contains arrays * Refactor: Fixes broken test (but we need a lot more) * Refactor: Adds explaining comments * Refactor: Adds latest RxJs version so cancellations work * Refactor: Cleans up the takeUntil code * Refactor: Adds tests for request function * Refactor: Separates into smaller functions * Refactor: Adds last error tests * Started to changed so we require getBackendSrv from the @grafana-runtime when applicable. * Using the getBackendSrv from @grafana/runtime. * Changed so we use the getBackendSrv from the @grafana-runtime when possible. * Fixed so Server Admin -> Orgs works again. * Removed unused dependency. * Fixed digest issues on the Server Admin -> Users page. * Fix: Fixes digest problems in Playlists * Fix: Fixes digest issues in VersionHistory * Tests: Fixes broken tests * Fix: Fixes digest issues in Alerting => Notification channels * Fixed digest issues on the Intive page. * Fixed so we run digest after password reset email sent. * Fixed digest issue when trying to sign up account. * Fixed so the Server Admin -> Edit Org works with backendSrv * Fixed so Server Admin -> Users works with backend srv. * Fixed digest issues in Server Admin -> Orgs * Fix: Fixes digest issues in DashList plugin * Fixed digest issues on Server Admin -> users. * Fix: Fixes digest issues with Snapshots * Fixed digest issue when deleting a user. * Fix: Fixes digest issues with dashLink * Chore: Changes RxJs version to 6.5.4 which includes the same cancellation fix * Fix: Fixes digest issue when toggling folder in manage dashboards * Fix: Fixes bug in executeInOrder * Fix: Fixes digest issue with CreateFolderCtrl and FolderDashboardsCtrl * Fix: Fixes tslint error in test * Refactor: Changes default behaviour for emitted messages as before migration * Fix: Fixes various digest issues when saving, starring or deleting dashboards * Fix: Fixes digest issues with FolderPickerCtrl * Fixed digest issue. * Fixed digest issues. * Fixed issues with angular digest. * Removed the this.digest pattern. Co-authored-by: Hugo Häggmark <hugo.haggmark@gmail.com> Co-authored-by: Marcus Andersson <systemvetaren@gmail.com>
2020-01-21 03:08:07 -06:00
import { backendSrv } from 'app/core/services/backend_srv';
2018-12-11 06:36:44 -06:00
import config from 'app/core/config';
// Types
import { PanelModel } from '../state/PanelModel';
import { DashboardModel } from '../state/DashboardModel';
import {
DataQuery,
DataSourceSelectItem,
DefaultTimeRange,
LoadingState,
PanelData,
DataSourceApi,
} from '@grafana/data';
2018-12-19 03:53:14 -06:00
import { PluginHelp } from 'app/core/components/PluginHelp/PluginHelp';
import { addQuery } from 'app/core/utils/query';
import { Unsubscribable } from 'rxjs';
import { DashboardQueryEditor, isSharedDashboardQuery } from 'app/plugins/datasource/dashboard';
import { expressionDatasource, ExpressionDatasourceID } from 'app/features/expressions/ExpressionDatasource';
import { css } from 'emotion';
import { selectors } from '@grafana/e2e-selectors';
2018-11-20 07:17:03 -06:00
interface Props {
panel: PanelModel;
dashboard: DashboardModel;
}
interface State {
dataSource?: DataSourceApi;
dataSourceItem: DataSourceSelectItem;
dataSourceError?: string;
2018-12-12 01:33:49 -06:00
helpContent: JSX.Element;
2018-12-11 23:52:08 -06:00
isLoadingHelp: boolean;
2018-12-11 10:03:38 -06:00
isPickerOpen: boolean;
2018-12-12 01:33:49 -06:00
isAddingMixed: boolean;
scrollTop: number;
data: PanelData;
isHelpOpen: boolean;
}
export class QueriesTab extends PureComponent<Props, State> {
datasources: DataSourceSelectItem[] = getDatasourceSrv().getMetricSources();
Chore: Remove angular dependency from backendSrv (#20999) * Chore: Remove angular dependency from backendSrv * Refactor: Naive soultion for logging out unauthorized users * Refactor: Restructures to different streams * Refactor: Restructures datasourceRequest * Refactor: Flipped back if statement * Refactor: Extracted getFromFetchStream * Refactor: Extracts toFailureStream operation * Refactor: Fixes issue when options.params contains arrays * Refactor: Fixes broken test (but we need a lot more) * Refactor: Adds explaining comments * Refactor: Adds latest RxJs version so cancellations work * Refactor: Cleans up the takeUntil code * Refactor: Adds tests for request function * Refactor: Separates into smaller functions * Refactor: Adds last error tests * Started to changed so we require getBackendSrv from the @grafana-runtime when applicable. * Using the getBackendSrv from @grafana/runtime. * Changed so we use the getBackendSrv from the @grafana-runtime when possible. * Fixed so Server Admin -> Orgs works again. * Removed unused dependency. * Fixed digest issues on the Server Admin -> Users page. * Fix: Fixes digest problems in Playlists * Fix: Fixes digest issues in VersionHistory * Tests: Fixes broken tests * Fix: Fixes digest issues in Alerting => Notification channels * Fixed digest issues on the Intive page. * Fixed so we run digest after password reset email sent. * Fixed digest issue when trying to sign up account. * Fixed so the Server Admin -> Edit Org works with backendSrv * Fixed so Server Admin -> Users works with backend srv. * Fixed digest issues in Server Admin -> Orgs * Fix: Fixes digest issues in DashList plugin * Fixed digest issues on Server Admin -> users. * Fix: Fixes digest issues with Snapshots * Fixed digest issue when deleting a user. * Fix: Fixes digest issues with dashLink * Chore: Changes RxJs version to 6.5.4 which includes the same cancellation fix * Fix: Fixes digest issue when toggling folder in manage dashboards * Fix: Fixes bug in executeInOrder * Fix: Fixes digest issue with CreateFolderCtrl and FolderDashboardsCtrl * Fix: Fixes tslint error in test * Refactor: Changes default behaviour for emitted messages as before migration * Fix: Fixes various digest issues when saving, starring or deleting dashboards * Fix: Fixes digest issues with FolderPickerCtrl * Fixed digest issue. * Fixed digest issues. * Fixed issues with angular digest. * Removed the this.digest pattern. Co-authored-by: Hugo Häggmark <hugo.haggmark@gmail.com> Co-authored-by: Marcus Andersson <systemvetaren@gmail.com>
2020-01-21 03:08:07 -06:00
backendSrv = backendSrv;
querySubscription: Unsubscribable | null;
state: State = {
isLoadingHelp: false,
dataSourceItem: this.findCurrentDataSource(),
helpContent: null,
isPickerOpen: false,
isAddingMixed: false,
isHelpOpen: false,
scrollTop: 0,
data: {
state: LoadingState.NotStarted,
series: [],
timeRange: DefaultTimeRange,
},
};
async componentDidMount() {
const { panel } = this.props;
const queryRunner = panel.getQueryRunner();
this.querySubscription = queryRunner.getData({ withTransforms: false, withFieldConfig: false }).subscribe({
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 10:28:46 -05:00
next: (data: PanelData) => this.onPanelDataUpdate(data),
});
try {
const ds = await getDataSourceSrv().get(panel.datasource);
this.setState({ dataSource: ds });
} catch (error) {
const ds = await getDataSourceSrv().get();
const dataSourceItem = this.findCurrentDataSource(ds.name);
this.setState({ dataSource: ds, dataSourceError: error?.message, dataSourceItem });
}
}
componentWillUnmount() {
if (this.querySubscription) {
this.querySubscription.unsubscribe();
this.querySubscription = null;
}
}
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 10:28:46 -05:00
onPanelDataUpdate(data: PanelData) {
this.setState({ data });
}
findCurrentDataSource(dataSourceName: string = this.props.panel.datasource): DataSourceSelectItem {
return this.datasources.find(datasource => datasource.value === dataSourceName) || this.datasources[0];
2019-01-08 08:54:12 -06:00
}
onChangeDataSource = async (newDsItem: DataSourceSelectItem) => {
const { panel } = this.props;
const { dataSourceItem } = this.state;
2018-12-11 06:36:44 -06:00
// switching to mixed
if (newDsItem.meta.mixed) {
// Set the datasource on all targets
panel.targets.forEach(target => {
if (target.datasource !== ExpressionDatasourceID) {
target.datasource = panel.datasource;
if (!target.datasource) {
target.datasource = config.defaultDatasource;
}
}
});
} else if (dataSourceItem) {
2018-12-11 06:36:44 -06:00
// if switching from mixed
if (dataSourceItem.meta.mixed) {
// Remove the explicit datasource
2018-12-11 06:36:44 -06:00
for (const target of panel.targets) {
if (target.datasource !== ExpressionDatasourceID) {
delete target.datasource;
}
2018-12-11 06:36:44 -06:00
}
} else if (dataSourceItem.meta.id !== newDsItem.meta.id) {
2018-12-11 06:36:44 -06:00
// we are changing data source type, clear queries
panel.targets = [{ refId: 'A' }];
}
}
const dataSource = await getDataSourceSrv().get(newDsItem.value);
panel.datasource = newDsItem.value;
this.setState(
{
dataSourceItem: newDsItem,
dataSource: dataSource,
dataSourceError: undefined,
},
() => panel.refresh()
);
2018-11-20 07:17:03 -06:00
};
Inspector: move `Panel JSON` and query inspector to the inspector (#23354) * move Panel JSON to inspector * move Panel JSON to inspector * update test * use stats display options * move query inspector to inspector * open inspector from the queries section * subscribe to results * subscribe to results * open the right tab * apply review feedback * update menus (inspect tabs) * Dashboard: extend dashnav to add custom content (#23433) * Dashlist: Fixed dashlist broken in edit mode (#23426) * Chore: Fix bunch of strict null error to fix master CI (#23443) * Fix bunch of null error * Fix failing test * Another test fix * Docs: Add SQL region annotation examples (#23268) Add region annotation examples for SQL data sources in docs. Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com> * Docs: Update contributing doc to install node@12. (#23450) * NewPanelEdit: Minor style and description tweaks, AND PanelQueryRunner & autoMinMax (#23445) * NewPanelEdit: Minor style and description tweaks * Removed the worst snapshot of all time * ReactTable: adds color text to field options (#23427) * Feature: adds text color field config * Refactor: created an extension point * Refactor: uses HOC for extension instead * Fix: fixes background styling from affecting cells without display.color * Chore: export OptionsUIRegistryBuilder on grafana/data (#23444) * export the ui registry * add to utils index also * DataLinks: Do not full page reload data links links (#23429) * Templating: Fix global variable "__org.id" (#23362) * Fixed global variable __org.id value * correct orgId value * reverted the change as variables moved to new file * Chore: reduce null check errors to 788 (currently over 798) (#23449) * Fixed ts errors so build will succeed * Update packages/grafana-data/src/types/graph.ts Co-Authored-By: Ryan McKinley <ryantxu@gmail.com> * Feedback from code review * Leaving out trivial typing's * Fix error with color being undefined now. * fix test with timezone issue * Fixed test Co-authored-by: Ryan McKinley <ryantxu@gmail.com> Co-authored-by: Torkel Ödegaard <torkel@grafana.com> * Cloudwatch: prefer webIdentity over EC2 role (#23452) * Plugins: add a signature status flag (#23420) * Progress * fixed button * Final touches * now works from edit mode * fix layout * show raw objects * move query inspector buttons to the bottom * update snapshot * Updated design * Made full page reload work * Fixed minor style issue * Updated * More fixes * Removed unused imports * Updated * Moved to data tab out to seperate component * fixed ts issue Co-authored-by: Torkel Ödegaard <torkel@grafana.com> Co-authored-by: Agnès Toulet <35176601+AgnesToulet@users.noreply.github.com> Co-authored-by: Andrej Ocenas <mr.ocenas@gmail.com> Co-authored-by: Alexandre de Verteuil <alexandre@grafana.com> Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com> Co-authored-by: Cyril Tovena <cyril.tovena@gmail.com> Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com> Co-authored-by: Vikky Omkar <vikkyomkar@gmail.com> Co-authored-by: Stephanie Closson <srclosson@gmail.com> Co-authored-by: Dário Nascimento <dfrnascimento@gmail.com>
2020-04-15 09:51:51 -05:00
openQueryInspector = () => {
const { panel } = this.props;
Inspector: move `Panel JSON` and query inspector to the inspector (#23354) * move Panel JSON to inspector * move Panel JSON to inspector * update test * use stats display options * move query inspector to inspector * open inspector from the queries section * subscribe to results * subscribe to results * open the right tab * apply review feedback * update menus (inspect tabs) * Dashboard: extend dashnav to add custom content (#23433) * Dashlist: Fixed dashlist broken in edit mode (#23426) * Chore: Fix bunch of strict null error to fix master CI (#23443) * Fix bunch of null error * Fix failing test * Another test fix * Docs: Add SQL region annotation examples (#23268) Add region annotation examples for SQL data sources in docs. Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com> * Docs: Update contributing doc to install node@12. (#23450) * NewPanelEdit: Minor style and description tweaks, AND PanelQueryRunner & autoMinMax (#23445) * NewPanelEdit: Minor style and description tweaks * Removed the worst snapshot of all time * ReactTable: adds color text to field options (#23427) * Feature: adds text color field config * Refactor: created an extension point * Refactor: uses HOC for extension instead * Fix: fixes background styling from affecting cells without display.color * Chore: export OptionsUIRegistryBuilder on grafana/data (#23444) * export the ui registry * add to utils index also * DataLinks: Do not full page reload data links links (#23429) * Templating: Fix global variable "__org.id" (#23362) * Fixed global variable __org.id value * correct orgId value * reverted the change as variables moved to new file * Chore: reduce null check errors to 788 (currently over 798) (#23449) * Fixed ts errors so build will succeed * Update packages/grafana-data/src/types/graph.ts Co-Authored-By: Ryan McKinley <ryantxu@gmail.com> * Feedback from code review * Leaving out trivial typing's * Fix error with color being undefined now. * fix test with timezone issue * Fixed test Co-authored-by: Ryan McKinley <ryantxu@gmail.com> Co-authored-by: Torkel Ödegaard <torkel@grafana.com> * Cloudwatch: prefer webIdentity over EC2 role (#23452) * Plugins: add a signature status flag (#23420) * Progress * fixed button * Final touches * now works from edit mode * fix layout * show raw objects * move query inspector buttons to the bottom * update snapshot * Updated design * Made full page reload work * Fixed minor style issue * Updated * More fixes * Removed unused imports * Updated * Moved to data tab out to seperate component * fixed ts issue Co-authored-by: Torkel Ödegaard <torkel@grafana.com> Co-authored-by: Agnès Toulet <35176601+AgnesToulet@users.noreply.github.com> Co-authored-by: Andrej Ocenas <mr.ocenas@gmail.com> Co-authored-by: Alexandre de Verteuil <alexandre@grafana.com> Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com> Co-authored-by: Cyril Tovena <cyril.tovena@gmail.com> Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com> Co-authored-by: Vikky Omkar <vikkyomkar@gmail.com> Co-authored-by: Stephanie Closson <srclosson@gmail.com> Co-authored-by: Dário Nascimento <dfrnascimento@gmail.com>
2020-04-15 09:51:51 -05:00
getLocationSrv().update({
query: { inspect: panel.id, inspectTab: 'query' },
partial: true,
});
};
2018-12-11 23:52:08 -06:00
renderHelp = () => {
return;
2018-12-11 23:52:08 -06:00
};
/**
* Sets the queries for the panel
*/
onUpdateQueries = (queries: DataQuery[]) => {
this.props.panel.targets = queries;
this.forceUpdate();
2018-12-11 06:36:44 -06:00
};
onAddQueryClick = () => {
if (this.state.dataSourceItem.meta.mixed) {
2018-12-12 01:54:12 -06:00
this.setState({ isAddingMixed: true });
2018-12-12 01:33:49 -06:00
return;
}
this.onUpdateQueries(addQuery(this.props.panel.targets));
this.onScrollBottom();
2018-12-11 06:36:44 -06:00
};
onAddExpressionClick = () => {
this.onUpdateQueries(addQuery(this.props.panel.targets, expressionDatasource.newQuery()));
this.onScrollBottom();
};
onScrollBottom = () => {
this.setState({ scrollTop: 1000 });
2018-12-11 06:36:44 -06:00
};
renderTopSection(styles: QueriesTabStyls) {
const { panel } = this.props;
const { dataSourceItem, data, dataSource, dataSourceError } = this.state;
if (!dataSource) {
return null;
}
2018-11-09 08:49:55 -06:00
return (
<div>
<div className={styles.dataSourceRow}>
<div className={styles.dataSourceRowItem}>
<Field invalid={!!dataSourceError} error={dataSourceError}>
<DataSourcePicker
datasources={this.datasources}
onChange={this.onChangeDataSource}
current={dataSourceItem}
/>
</Field>
</div>
<div className={styles.dataSourceRowItem}>
<Button
variant="secondary"
icon="question-circle"
title="Open data source help"
onClick={this.onOpenHelp}
/>
</div>
<div className={styles.dataSourceRowItemOptions}>
<QueryOptions panel={panel} dataSource={dataSource} data={data} />
</div>
<div className={styles.dataSourceRowItem}>
<Button
variant="secondary"
onClick={this.openQueryInspector}
aria-label={selectors.components.QueryTab.queryInspectorButton}
>
Query inspector
</Button>
</div>
</div>
</div>
);
}
onOpenHelp = () => {
this.setState({ isHelpOpen: true });
};
onCloseHelp = () => {
this.setState({ isHelpOpen: false });
2018-12-11 10:03:38 -06:00
};
2018-11-09 08:49:55 -06:00
2018-12-12 01:33:49 -06:00
renderMixedPicker = () => {
// We cannot filter on mixed flag as some mixed data sources like external plugin
// meta queries data source is mixed but also supports it's own queries
const filteredDsList = this.datasources.filter(ds => ds.meta.id !== 'mixed');
2018-12-12 01:33:49 -06:00
return (
<DataSourcePicker
datasources={filteredDsList}
2018-12-14 07:05:47 -06:00
onChange={this.onAddMixedQuery}
2018-12-12 01:33:49 -06:00
current={null}
autoFocus={true}
onBlur={this.onMixedPickerBlur}
openMenuOnFocus={true}
2018-12-12 01:33:49 -06:00
/>
);
};
onAddMixedQuery = (datasource: any) => {
this.props.panel.targets = addQuery(this.props.panel.targets, { datasource: datasource.name });
this.setState({ isAddingMixed: false, scrollTop: this.state.scrollTop + 10000 });
this.forceUpdate();
2018-12-12 01:33:49 -06:00
};
onMixedPickerBlur = () => {
this.setState({ isAddingMixed: false });
};
onQueryChange = (query: DataQuery, index: number) => {
this.props.panel.changeQuery(query, index);
this.forceUpdate();
};
setScrollTop = (event: React.MouseEvent<HTMLElement>) => {
const target = event.target as HTMLElement;
this.setState({ scrollTop: target.scrollTop });
};
renderQueries() {
const { panel, dashboard } = this.props;
const { dataSourceItem, data } = this.state;
if (isSharedDashboardQuery(dataSourceItem.name)) {
return <DashboardQueryEditor panel={panel} panelData={data} onChange={query => this.onUpdateQueries([query])} />;
}
return (
<div aria-label={selectors.components.QueryTab.content}>
<QueryEditorRows
queries={panel.targets}
datasource={dataSourceItem}
onChangeQueries={this.onUpdateQueries}
onScrollBottom={this.onScrollBottom}
panel={panel}
dashboard={dashboard}
data={data}
/>
</div>
);
}
renderAddQueryRow() {
const { dataSourceItem, isAddingMixed } = this.state;
const showAddButton = !(isAddingMixed || isSharedDashboardQuery(dataSourceItem.name));
return (
<HorizontalGroup spacing="md" align="flex-start">
{showAddButton && (
<Button
icon="plus"
onClick={this.onAddQueryClick}
variant="secondary"
aria-label={selectors.components.QueryTab.addQuery}
>
Query
</Button>
)}
{isAddingMixed && this.renderMixedPicker()}
{config.featureToggles.expressions && (
<Button icon="plus" onClick={this.onAddExpressionClick} variant="secondary">
Expression
</Button>
)}
</HorizontalGroup>
);
}
render() {
const { scrollTop, isHelpOpen } = this.state;
const styles = getStyles();
2018-12-11 23:52:08 -06:00
return (
<CustomScrollbar
autoHeightMin="100%"
autoHide={true}
updateAfterMountMs={300}
scrollTop={scrollTop}
setScrollTop={this.setScrollTop}
>
<div className={styles.innerWrapper}>
{this.renderTopSection(styles)}
<div className={styles.queriesWrapper}>{this.renderQueries()}</div>
{this.renderAddQueryRow()}
{isHelpOpen && (
<Modal title="Data source help" isOpen={true} onDismiss={this.onCloseHelp}>
<PluginHelp plugin={this.state.dataSourceItem.meta} type="query_help" />
</Modal>
)}
</div>
</CustomScrollbar>
);
}
}
const getStyles = stylesFactory(() => {
const { theme } = config;
return {
innerWrapper: css`
display: flex;
flex-direction: column;
height: 100%;
padding: ${theme.spacing.md};
`,
dataSourceRow: css`
display: flex;
margin-bottom: ${theme.spacing.md};
`,
dataSourceRowItem: css`
margin-right: ${theme.spacing.inlineFormMargin};
`,
dataSourceRowItemOptions: css`
flex-grow: 1;
margin-right: ${theme.spacing.inlineFormMargin};
`,
queriesWrapper: css`
padding-bottom: 16px;
`,
};
});
type QueriesTabStyls = ReturnType<typeof getStyles>;