QueryEditorRow.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. // Libraries
  2. import classNames from 'classnames';
  3. import { cloneDeep, has } from 'lodash';
  4. import React, { PureComponent, ReactNode } from 'react';
  5. // Utils & Services
  6. import {
  7. CoreApp,
  8. DataQuery,
  9. DataSourceApi,
  10. DataSourceInstanceSettings,
  11. EventBusExtended,
  12. EventBusSrv,
  13. HistoryItem,
  14. LoadingState,
  15. PanelData,
  16. PanelEvents,
  17. TimeRange,
  18. toLegacyResponseData,
  19. } from '@grafana/data';
  20. import { selectors } from '@grafana/e2e-selectors';
  21. import { AngularComponent, getAngularLoader } from '@grafana/runtime';
  22. import { ErrorBoundaryAlert, HorizontalGroup } from '@grafana/ui';
  23. import { OperationRowHelp } from 'app/core/components/QueryOperationRow/OperationRowHelp';
  24. import { QueryOperationAction } from 'app/core/components/QueryOperationRow/QueryOperationAction';
  25. import {
  26. QueryOperationRow,
  27. QueryOperationRowRenderProps,
  28. } from 'app/core/components/QueryOperationRow/QueryOperationRow';
  29. import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
  30. import { DashboardModel } from 'app/features/dashboard/state/DashboardModel';
  31. import { PanelModel } from 'app/features/dashboard/state/PanelModel';
  32. import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
  33. import { RowActionComponents } from './QueryActionComponent';
  34. import { QueryEditorRowHeader } from './QueryEditorRowHeader';
  35. import { QueryErrorAlert } from './QueryErrorAlert';
  36. interface Props<TQuery extends DataQuery> {
  37. data: PanelData;
  38. query: TQuery;
  39. queries: TQuery[];
  40. id: string;
  41. index: number;
  42. dataSource: DataSourceInstanceSettings;
  43. onChangeDataSource?: (dsSettings: DataSourceInstanceSettings) => void;
  44. renderHeaderExtras?: () => ReactNode;
  45. onAddQuery: (query: TQuery) => void;
  46. onRemoveQuery: (query: TQuery) => void;
  47. onChange: (query: TQuery) => void;
  48. onRunQuery: () => void;
  49. visualization?: ReactNode;
  50. hideDisableQuery?: boolean;
  51. app?: CoreApp;
  52. history?: Array<HistoryItem<TQuery>>;
  53. eventBus?: EventBusExtended;
  54. alerting?: boolean;
  55. }
  56. interface State<TQuery extends DataQuery> {
  57. loadedDataSourceIdentifier?: string | null;
  58. datasource: DataSourceApi<TQuery> | null;
  59. hasTextEditMode: boolean;
  60. data?: PanelData;
  61. isOpen?: boolean;
  62. showingHelp: boolean;
  63. }
  64. export class QueryEditorRow<TQuery extends DataQuery> extends PureComponent<Props<TQuery>, State<TQuery>> {
  65. element: HTMLElement | null = null;
  66. angularScope: AngularQueryComponentScope<TQuery> | null = null;
  67. angularQueryEditor: AngularComponent | null = null;
  68. state: State<TQuery> = {
  69. datasource: null,
  70. hasTextEditMode: false,
  71. data: undefined,
  72. isOpen: true,
  73. showingHelp: false,
  74. };
  75. componentDidMount() {
  76. this.loadDatasource();
  77. }
  78. componentWillUnmount() {
  79. if (this.angularQueryEditor) {
  80. this.angularQueryEditor.destroy();
  81. }
  82. }
  83. getAngularQueryComponentScope(): AngularQueryComponentScope<TQuery> {
  84. const { query, queries } = this.props;
  85. const { datasource } = this.state;
  86. const panel = new PanelModel({ targets: queries });
  87. const dashboard = {} as DashboardModel;
  88. const me = this;
  89. return {
  90. datasource: datasource,
  91. target: query,
  92. panel: panel,
  93. dashboard: dashboard,
  94. refresh: () => {
  95. // Old angular editors modify the query model and just call refresh
  96. // Important that this use this.props here so that as this function is only created on mount and it's
  97. // important not to capture old prop functions in this closure
  98. // the "hide" attribute of the queries can be changed from the "outside",
  99. // it will be applied to "this.props.query.hide", but not to "query.hide".
  100. // so we have to apply it.
  101. if (query.hide !== me.props.query.hide) {
  102. query.hide = me.props.query.hide;
  103. }
  104. this.props.onChange(query);
  105. this.props.onRunQuery();
  106. },
  107. render: () => () => console.log('legacy render function called, it does nothing'),
  108. events: this.props.eventBus || new EventBusSrv(),
  109. range: getTimeSrv().timeRange(),
  110. };
  111. }
  112. getQueryDataSourceIdentifier(): string | null | undefined {
  113. const { query, dataSource: dsSettings } = this.props;
  114. return query.datasource?.uid ?? dsSettings.uid;
  115. }
  116. async loadDatasource() {
  117. const dataSourceSrv = getDatasourceSrv();
  118. let datasource: DataSourceApi;
  119. const dataSourceIdentifier = this.getQueryDataSourceIdentifier();
  120. try {
  121. datasource = await dataSourceSrv.get(dataSourceIdentifier);
  122. } catch (error) {
  123. datasource = await dataSourceSrv.get();
  124. }
  125. this.setState({
  126. datasource: datasource as unknown as DataSourceApi<TQuery>,
  127. loadedDataSourceIdentifier: dataSourceIdentifier,
  128. hasTextEditMode: has(datasource, 'components.QueryCtrl.prototype.toggleEditorMode'),
  129. });
  130. }
  131. componentDidUpdate(prevProps: Props<TQuery>) {
  132. const { datasource, loadedDataSourceIdentifier } = this.state;
  133. const { data, query } = this.props;
  134. if (data !== prevProps.data) {
  135. const dataFilteredByRefId = filterPanelDataToQuery(data, query.refId);
  136. this.setState({ data: dataFilteredByRefId });
  137. if (this.angularScope) {
  138. this.angularScope.range = getTimeSrv().timeRange();
  139. }
  140. if (this.angularQueryEditor && dataFilteredByRefId) {
  141. notifyAngularQueryEditorsOfData(this.angularScope!, dataFilteredByRefId, this.angularQueryEditor);
  142. }
  143. }
  144. // check if we need to load another datasource
  145. if (datasource && loadedDataSourceIdentifier !== this.getQueryDataSourceIdentifier()) {
  146. if (this.angularQueryEditor) {
  147. this.angularQueryEditor.destroy();
  148. this.angularQueryEditor = null;
  149. }
  150. this.loadDatasource();
  151. return;
  152. }
  153. if (!this.element || this.angularQueryEditor) {
  154. return;
  155. }
  156. this.renderAngularQueryEditor();
  157. }
  158. renderAngularQueryEditor = () => {
  159. if (!this.element) {
  160. return;
  161. }
  162. if (this.angularQueryEditor) {
  163. this.angularQueryEditor.destroy();
  164. this.angularQueryEditor = null;
  165. }
  166. const loader = getAngularLoader();
  167. const template = '<plugin-component type="query-ctrl" />';
  168. const scopeProps = { ctrl: this.getAngularQueryComponentScope() };
  169. this.angularQueryEditor = loader.load(this.element, scopeProps, template);
  170. this.angularScope = scopeProps.ctrl;
  171. };
  172. onOpen = () => {
  173. this.renderAngularQueryEditor();
  174. };
  175. getReactQueryEditor(ds: DataSourceApi<TQuery>) {
  176. if (!ds) {
  177. return;
  178. }
  179. switch (this.props.app) {
  180. case CoreApp.Explore:
  181. return (
  182. ds.components?.ExploreMetricsQueryField ||
  183. ds.components?.ExploreLogsQueryField ||
  184. ds.components?.ExploreQueryField ||
  185. ds.components?.QueryEditor
  186. );
  187. case CoreApp.PanelEditor:
  188. case CoreApp.Dashboard:
  189. default:
  190. return ds.components?.QueryEditor;
  191. }
  192. }
  193. renderPluginEditor = () => {
  194. const { query, onChange, queries, onRunQuery, app = CoreApp.PanelEditor, history } = this.props;
  195. const { datasource, data } = this.state;
  196. if (datasource?.components?.QueryCtrl) {
  197. return <div ref={(element) => (this.element = element)} />;
  198. }
  199. if (datasource) {
  200. let QueryEditor = this.getReactQueryEditor(datasource);
  201. if (QueryEditor) {
  202. return (
  203. <QueryEditor
  204. key={datasource?.name}
  205. query={query}
  206. datasource={datasource}
  207. onChange={onChange}
  208. onRunQuery={onRunQuery}
  209. data={data}
  210. range={getTimeSrv().timeRange()}
  211. queries={queries}
  212. app={app}
  213. history={history}
  214. />
  215. );
  216. }
  217. }
  218. return <div>Data source plugin does not export any Query Editor component</div>;
  219. };
  220. onToggleEditMode = (e: React.MouseEvent, props: QueryOperationRowRenderProps) => {
  221. e.stopPropagation();
  222. if (this.angularScope && this.angularScope.toggleEditorMode) {
  223. this.angularScope.toggleEditorMode();
  224. this.angularQueryEditor?.digest();
  225. if (!props.isOpen) {
  226. props.onOpen();
  227. }
  228. }
  229. };
  230. onRemoveQuery = () => {
  231. this.props.onRemoveQuery(this.props.query);
  232. };
  233. onCopyQuery = () => {
  234. const copy = cloneDeep(this.props.query);
  235. this.props.onAddQuery(copy);
  236. };
  237. onDisableQuery = () => {
  238. const { query } = this.props;
  239. this.props.onChange({ ...query, hide: !query.hide });
  240. this.props.onRunQuery();
  241. };
  242. onToggleHelp = () => {
  243. this.setState((state) => ({
  244. showingHelp: !state.showingHelp,
  245. }));
  246. };
  247. onClickExample = (query: TQuery) => {
  248. this.props.onChange({
  249. ...query,
  250. refId: this.props.query.refId,
  251. });
  252. this.onToggleHelp();
  253. };
  254. renderCollapsedText(): string | null {
  255. const { datasource } = this.state;
  256. if (datasource?.getQueryDisplayText) {
  257. return datasource.getQueryDisplayText(this.props.query);
  258. }
  259. if (this.angularScope && this.angularScope.getCollapsedText) {
  260. return this.angularScope.getCollapsedText();
  261. }
  262. return null;
  263. }
  264. renderExtraActions = () => {
  265. const { query, queries, data, onAddQuery, dataSource } = this.props;
  266. return RowActionComponents.getAllExtraRenderAction()
  267. .map((action, index) =>
  268. action({
  269. query,
  270. queries,
  271. timeRange: data.timeRange,
  272. onAddQuery: onAddQuery as (query: DataQuery) => void,
  273. dataSource,
  274. key: index,
  275. })
  276. )
  277. .filter(Boolean);
  278. };
  279. renderActions = (props: QueryOperationRowRenderProps) => {
  280. const { query, hideDisableQuery = false } = this.props;
  281. const { hasTextEditMode, datasource, showingHelp } = this.state;
  282. const isDisabled = query.hide;
  283. const hasEditorHelp = datasource?.components?.QueryEditorHelp;
  284. return (
  285. <HorizontalGroup width="auto">
  286. {hasEditorHelp && (
  287. <QueryOperationAction
  288. title="Toggle data source help"
  289. icon="question-circle"
  290. onClick={this.onToggleHelp}
  291. active={showingHelp}
  292. />
  293. )}
  294. {hasTextEditMode && (
  295. <QueryOperationAction
  296. title="Toggle text edit mode"
  297. icon="pen"
  298. onClick={(e) => {
  299. this.onToggleEditMode(e, props);
  300. }}
  301. />
  302. )}
  303. {this.renderExtraActions()}
  304. <QueryOperationAction title="Duplicate query" icon="copy" onClick={this.onCopyQuery} />
  305. {!hideDisableQuery ? (
  306. <QueryOperationAction
  307. title="Disable/enable query"
  308. icon={isDisabled ? 'eye-slash' : 'eye'}
  309. active={isDisabled}
  310. onClick={this.onDisableQuery}
  311. />
  312. ) : null}
  313. <QueryOperationAction title="Remove query" icon="trash-alt" onClick={this.onRemoveQuery} />
  314. </HorizontalGroup>
  315. );
  316. };
  317. renderHeader = (props: QueryOperationRowRenderProps) => {
  318. const { alerting, query, dataSource, onChangeDataSource, onChange, queries, renderHeaderExtras } = this.props;
  319. return (
  320. <QueryEditorRowHeader
  321. query={query}
  322. queries={queries}
  323. onChangeDataSource={onChangeDataSource}
  324. dataSource={dataSource}
  325. disabled={query.hide}
  326. onClick={(e) => this.onToggleEditMode(e, props)}
  327. onChange={onChange}
  328. collapsedText={!props.isOpen ? this.renderCollapsedText() : null}
  329. renderExtras={renderHeaderExtras}
  330. alerting={alerting}
  331. />
  332. );
  333. };
  334. render() {
  335. const { query, id, index, visualization } = this.props;
  336. const { datasource, showingHelp, data } = this.state;
  337. const isDisabled = query.hide;
  338. const rowClasses = classNames('query-editor-row', {
  339. 'query-editor-row--disabled': isDisabled,
  340. 'gf-form-disabled': isDisabled,
  341. });
  342. if (!datasource) {
  343. return null;
  344. }
  345. const editor = this.renderPluginEditor();
  346. const DatasourceCheatsheet = datasource.components?.QueryEditorHelp;
  347. return (
  348. <div aria-label={selectors.components.QueryEditorRows.rows}>
  349. <QueryOperationRow
  350. id={id}
  351. draggable={true}
  352. index={index}
  353. headerElement={this.renderHeader}
  354. actions={this.renderActions}
  355. onOpen={this.onOpen}
  356. >
  357. <div className={rowClasses}>
  358. <ErrorBoundaryAlert>
  359. {showingHelp && DatasourceCheatsheet && (
  360. <OperationRowHelp>
  361. <DatasourceCheatsheet
  362. onClickExample={(query) => this.onClickExample(query)}
  363. query={this.props.query}
  364. datasource={datasource}
  365. />
  366. </OperationRowHelp>
  367. )}
  368. {editor}
  369. </ErrorBoundaryAlert>
  370. {data?.error && data.error.refId === query.refId && <QueryErrorAlert error={data.error} />}
  371. {visualization}
  372. </div>
  373. </QueryOperationRow>
  374. </div>
  375. );
  376. }
  377. }
  378. function notifyAngularQueryEditorsOfData<TQuery extends DataQuery>(
  379. scope: AngularQueryComponentScope<TQuery>,
  380. data: PanelData,
  381. editor: AngularComponent
  382. ) {
  383. if (data.state === LoadingState.Done) {
  384. const legacy = data.series.map((v) => toLegacyResponseData(v));
  385. scope.events.emit(PanelEvents.dataReceived, legacy);
  386. } else if (data.state === LoadingState.Error) {
  387. scope.events.emit(PanelEvents.dataError, data.error);
  388. }
  389. // Some query controllers listen to data error events and need a digest
  390. // for some reason this needs to be done in next tick
  391. setTimeout(editor.digest);
  392. }
  393. export interface AngularQueryComponentScope<TQuery extends DataQuery> {
  394. target: TQuery;
  395. panel: PanelModel;
  396. dashboard: DashboardModel;
  397. events: EventBusExtended;
  398. refresh: () => void;
  399. render: () => void;
  400. datasource: DataSourceApi<TQuery> | null;
  401. toggleEditorMode?: () => void;
  402. getCollapsedText?: () => string;
  403. range: TimeRange;
  404. }
  405. /**
  406. * Get a version of the PanelData limited to the query we are looking at
  407. */
  408. export function filterPanelDataToQuery(data: PanelData, refId: string): PanelData | undefined {
  409. const series = data.series.filter((series) => series.refId === refId);
  410. // If there was an error with no data, pass it to the QueryEditors
  411. if (data.error && !data.series.length) {
  412. return {
  413. ...data,
  414. state: LoadingState.Error,
  415. };
  416. }
  417. // Only say this is an error if the error links to the query
  418. let state = data.state;
  419. const error = data.error && data.error.refId === refId ? data.error : undefined;
  420. if (error) {
  421. state = LoadingState.Error;
  422. } else if (!error && data.state === LoadingState.Error) {
  423. state = LoadingState.Done;
  424. }
  425. const timeRange = data.timeRange;
  426. return {
  427. ...data,
  428. state,
  429. series,
  430. error,
  431. timeRange,
  432. };
  433. }