QueryEditorRow.tsx 10 KB

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