QueryEditorRow.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. // Libraries
  2. import React, { PureComponent } from 'react';
  3. import classNames from 'classnames';
  4. import _ from 'lodash';
  5. // Utils & Services
  6. import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
  7. import { AngularComponent, getAngularLoader } from '@grafana/runtime';
  8. import { Emitter } from 'app/core/utils/emitter';
  9. import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
  10. import { ErrorBoundaryAlert } from 'app/core/components/ErrorBoundary/ErrorBoundary';
  11. // Types
  12. import { PanelModel } from '../state/PanelModel';
  13. import { DataQuery, DataSourceApi, PanelData, DataQueryRequest } from '@grafana/ui';
  14. import { TimeRange, LoadingState } from '@grafana/data';
  15. import { DashboardModel } from '../state/DashboardModel';
  16. interface Props {
  17. panel: PanelModel;
  18. data: PanelData;
  19. query: DataQuery;
  20. dashboard: DashboardModel;
  21. onAddQuery: (query?: DataQuery) => void;
  22. onRemoveQuery: (query: DataQuery) => void;
  23. onMoveQuery: (query: DataQuery, direction: number) => void;
  24. onChange: (query: DataQuery) => void;
  25. dataSourceValue: string | null;
  26. inMixedMode: boolean;
  27. }
  28. interface State {
  29. loadedDataSourceValue: string | null | undefined;
  30. datasource: DataSourceApi | null;
  31. isCollapsed: boolean;
  32. hasTextEditMode: boolean;
  33. queryResponse?: PanelData;
  34. }
  35. export class QueryEditorRow extends PureComponent<Props, State> {
  36. element: HTMLElement | null = null;
  37. angularScope: AngularQueryComponentScope | null;
  38. angularQueryEditor: AngularComponent | null = null;
  39. state: State = {
  40. datasource: null,
  41. isCollapsed: false,
  42. loadedDataSourceValue: undefined,
  43. hasTextEditMode: false,
  44. queryResponse: null,
  45. };
  46. componentDidMount() {
  47. this.loadDatasource();
  48. }
  49. componentWillUnmount() {
  50. if (this.angularQueryEditor) {
  51. this.angularQueryEditor.destroy();
  52. }
  53. }
  54. getAngularQueryComponentScope(): AngularQueryComponentScope {
  55. const { panel, query, dashboard } = this.props;
  56. const { datasource } = this.state;
  57. return {
  58. datasource: datasource,
  59. target: query,
  60. panel: panel,
  61. dashboard: dashboard,
  62. refresh: () => panel.refresh(),
  63. render: () => panel.render(),
  64. events: panel.events,
  65. range: getTimeSrv().timeRange(),
  66. };
  67. }
  68. async loadDatasource() {
  69. const { query, panel } = this.props;
  70. const dataSourceSrv = getDatasourceSrv();
  71. const datasource = await dataSourceSrv.get(query.datasource || panel.datasource);
  72. this.setState({
  73. datasource,
  74. loadedDataSourceValue: this.props.dataSourceValue,
  75. hasTextEditMode: _.has(datasource, 'components.QueryCtrl.prototype.toggleEditorMode'),
  76. });
  77. }
  78. componentDidUpdate(prevProps: Props) {
  79. const { loadedDataSourceValue } = this.state;
  80. const { data, query } = this.props;
  81. if (data !== prevProps.data) {
  82. this.setState({ queryResponse: filterPanelDataToQuery(data, query.refId) });
  83. if (this.angularScope) {
  84. this.angularScope.range = getTimeSrv().timeRange();
  85. }
  86. if (this.angularQueryEditor) {
  87. // Some query controllers listen to data error events and need a digest
  88. // for some reason this needs to be done in next tick
  89. setTimeout(this.angularQueryEditor.digest);
  90. }
  91. }
  92. // check if we need to load another datasource
  93. if (loadedDataSourceValue !== this.props.dataSourceValue) {
  94. if (this.angularQueryEditor) {
  95. this.angularQueryEditor.destroy();
  96. this.angularQueryEditor = null;
  97. }
  98. this.loadDatasource();
  99. return;
  100. }
  101. if (!this.element || this.angularQueryEditor) {
  102. return;
  103. }
  104. const loader = getAngularLoader();
  105. const template = '<plugin-component type="query-ctrl" />';
  106. const scopeProps = { ctrl: this.getAngularQueryComponentScope() };
  107. this.angularQueryEditor = loader.load(this.element, scopeProps, template);
  108. this.angularScope = scopeProps.ctrl;
  109. }
  110. onToggleCollapse = () => {
  111. this.setState({ isCollapsed: !this.state.isCollapsed });
  112. };
  113. onRunQuery = () => {
  114. this.props.panel.refresh();
  115. };
  116. renderPluginEditor() {
  117. const { query, data, onChange } = this.props;
  118. const { datasource, queryResponse } = this.state;
  119. if (datasource.components.QueryCtrl) {
  120. return <div ref={element => (this.element = element)} />;
  121. }
  122. if (datasource.components.QueryEditor) {
  123. const QueryEditor = datasource.components.QueryEditor;
  124. return (
  125. <QueryEditor
  126. query={query}
  127. datasource={datasource}
  128. onChange={onChange}
  129. onRunQuery={this.onRunQuery}
  130. queryResponse={queryResponse}
  131. panelData={data}
  132. />
  133. );
  134. }
  135. return <div>Data source plugin does not export any Query Editor component</div>;
  136. }
  137. onToggleEditMode = () => {
  138. if (this.angularScope && this.angularScope.toggleEditorMode) {
  139. this.angularScope.toggleEditorMode();
  140. this.angularQueryEditor.digest();
  141. }
  142. if (this.state.isCollapsed) {
  143. this.setState({ isCollapsed: false });
  144. }
  145. };
  146. onRemoveQuery = () => {
  147. this.props.onRemoveQuery(this.props.query);
  148. };
  149. onCopyQuery = () => {
  150. const copy = _.cloneDeep(this.props.query);
  151. this.props.onAddQuery(copy);
  152. };
  153. onDisableQuery = () => {
  154. this.props.query.hide = !this.props.query.hide;
  155. this.onRunQuery();
  156. this.forceUpdate();
  157. };
  158. renderCollapsedText(): string | null {
  159. const { datasource } = this.state;
  160. if (datasource.getQueryDisplayText) {
  161. return datasource.getQueryDisplayText(this.props.query);
  162. }
  163. if (this.angularScope && this.angularScope.getCollapsedText) {
  164. return this.angularScope.getCollapsedText();
  165. }
  166. return null;
  167. }
  168. render() {
  169. const { query, inMixedMode } = this.props;
  170. const { datasource, isCollapsed, hasTextEditMode } = this.state;
  171. const isDisabled = query.hide;
  172. const bodyClasses = classNames('query-editor-row__body gf-form-query', {
  173. 'query-editor-row__body--collapsed': isCollapsed,
  174. });
  175. const rowClasses = classNames('query-editor-row', {
  176. 'query-editor-row--disabled': isDisabled,
  177. 'gf-form-disabled': isDisabled,
  178. });
  179. if (!datasource) {
  180. return null;
  181. }
  182. return (
  183. <div className={rowClasses}>
  184. <div className="query-editor-row__header">
  185. <div className="query-editor-row__ref-id" onClick={this.onToggleCollapse}>
  186. {isCollapsed && <i className="fa fa-caret-right" />}
  187. {!isCollapsed && <i className="fa fa-caret-down" />}
  188. <span>{query.refId}</span>
  189. {inMixedMode && <em className="query-editor-row__context-info"> ({datasource.name})</em>}
  190. {isDisabled && <em className="query-editor-row__context-info"> Disabled</em>}
  191. </div>
  192. <div className="query-editor-row__collapsed-text" onClick={this.onToggleEditMode}>
  193. {isCollapsed && <div>{this.renderCollapsedText()}</div>}
  194. </div>
  195. <div className="query-editor-row__actions">
  196. {hasTextEditMode && (
  197. <button
  198. className="query-editor-row__action"
  199. onClick={this.onToggleEditMode}
  200. title="Toggle text edit mode"
  201. >
  202. <i className="fa fa-fw fa-pencil" />
  203. </button>
  204. )}
  205. <button className="query-editor-row__action" onClick={() => this.props.onMoveQuery(query, 1)}>
  206. <i className="fa fa-fw fa-arrow-down" />
  207. </button>
  208. <button className="query-editor-row__action" onClick={() => this.props.onMoveQuery(query, -1)}>
  209. <i className="fa fa-fw fa-arrow-up" />
  210. </button>
  211. <button className="query-editor-row__action" onClick={this.onCopyQuery} title="Duplicate query">
  212. <i className="fa fa-fw fa-copy" />
  213. </button>
  214. <button className="query-editor-row__action" onClick={this.onDisableQuery} title="Disable/enable query">
  215. {isDisabled && <i className="fa fa-fw fa-eye-slash" />}
  216. {!isDisabled && <i className="fa fa-fw fa-eye" />}
  217. </button>
  218. <button className="query-editor-row__action" onClick={this.onRemoveQuery} title="Remove query">
  219. <i className="fa fa-fw fa-trash" />
  220. </button>
  221. </div>
  222. </div>
  223. <div className={bodyClasses}>
  224. <ErrorBoundaryAlert title="Data source query editor failed">{this.renderPluginEditor()}</ErrorBoundaryAlert>
  225. </div>
  226. </div>
  227. );
  228. }
  229. }
  230. export interface AngularQueryComponentScope {
  231. target: DataQuery;
  232. panel: PanelModel;
  233. dashboard: DashboardModel;
  234. events: Emitter;
  235. refresh: () => void;
  236. render: () => void;
  237. datasource: DataSourceApi;
  238. toggleEditorMode?: () => void;
  239. getCollapsedText?: () => string;
  240. range: TimeRange;
  241. }
  242. /**
  243. * Get a version of the PanelData limited to the query we are looking at
  244. */
  245. export function filterPanelDataToQuery(data: PanelData, refId: string): PanelData | undefined {
  246. const series = data.series.filter(series => series.refId === refId);
  247. // No matching series
  248. if (!series.length) {
  249. return undefined;
  250. }
  251. // Don't pass the request if all requests are the same
  252. const request: DataQueryRequest = undefined;
  253. // TODO: look in sub-requets to match the info
  254. // Only say this is an error if the error links to the query
  255. let state = LoadingState.Done;
  256. const error = data.error && data.error.refId === refId ? data.error : undefined;
  257. if (error) {
  258. state = LoadingState.Error;
  259. }
  260. return {
  261. state,
  262. series,
  263. request,
  264. error,
  265. };
  266. }