actions.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. // Libraries
  2. import _ from 'lodash';
  3. import { ThunkAction } from 'redux-thunk';
  4. // Services & Utils
  5. import store from 'app/core/store';
  6. import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
  7. import { Emitter } from 'app/core/core';
  8. import {
  9. LAST_USED_DATASOURCE_KEY,
  10. clearQueryKeys,
  11. ensureQueries,
  12. generateEmptyQuery,
  13. hasNonEmptyQuery,
  14. makeTimeSeriesList,
  15. updateHistory,
  16. buildQueryTransaction,
  17. serializeStateToUrlParam,
  18. } from 'app/core/utils/explore';
  19. // Actions
  20. import { updateLocation } from 'app/core/actions';
  21. // Types
  22. import { StoreState } from 'app/types';
  23. import {
  24. RawTimeRange,
  25. TimeRange,
  26. DataSourceApi,
  27. DataQuery,
  28. DataSourceSelectItem,
  29. QueryHint,
  30. QueryFixAction,
  31. } from '@grafana/ui/src/types';
  32. import { ExploreId, ExploreUrlState, RangeScanner, ResultType, QueryOptions, ExploreUIState } from 'app/types/explore';
  33. import {
  34. Action,
  35. updateDatasourceInstanceAction,
  36. changeQueryAction,
  37. changeSizeAction,
  38. ChangeSizePayload,
  39. changeTimeAction,
  40. scanStopAction,
  41. clearQueriesAction,
  42. initializeExploreAction,
  43. loadDatasourceMissingAction,
  44. loadDatasourceFailureAction,
  45. loadDatasourcePendingAction,
  46. queriesImportedAction,
  47. LoadDatasourceSuccessPayload,
  48. loadDatasourceSuccessAction,
  49. modifyQueriesAction,
  50. queryTransactionFailureAction,
  51. queryTransactionStartAction,
  52. queryTransactionSuccessAction,
  53. scanRangeAction,
  54. runQueriesEmptyAction,
  55. scanStartAction,
  56. setQueriesAction,
  57. splitCloseAction,
  58. splitOpenAction,
  59. addQueryRowAction,
  60. AddQueryRowPayload,
  61. toggleGraphAction,
  62. toggleLogsAction,
  63. toggleTableAction,
  64. ToggleGraphPayload,
  65. ToggleLogsPayload,
  66. ToggleTablePayload,
  67. } from './actionTypes';
  68. import { ActionOf, ActionCreator } from 'app/core/redux/actionCreatorFactory';
  69. type ThunkResult<R> = ThunkAction<R, StoreState, undefined, Action>;
  70. // /**
  71. // * Adds a query row after the row with the given index.
  72. // */
  73. export function addQueryRow(exploreId: ExploreId, index: number): ActionOf<AddQueryRowPayload> {
  74. const query = generateEmptyQuery(index + 1);
  75. return addQueryRowAction({ exploreId, index, query });
  76. }
  77. /**
  78. * Loads a new datasource identified by the given name.
  79. */
  80. export function changeDatasource(exploreId: ExploreId, datasource: string): ThunkResult<void> {
  81. return async (dispatch, getState) => {
  82. const newDataSourceInstance = await getDatasourceSrv().get(datasource);
  83. const currentDataSourceInstance = getState().explore[exploreId].datasourceInstance;
  84. const queries = getState().explore[exploreId].queries;
  85. await dispatch(importQueries(exploreId, queries, currentDataSourceInstance, newDataSourceInstance));
  86. dispatch(updateDatasourceInstanceAction({ exploreId, datasourceInstance: newDataSourceInstance }));
  87. try {
  88. await dispatch(loadDatasource(exploreId, newDataSourceInstance));
  89. } catch (error) {
  90. console.error(error);
  91. return;
  92. }
  93. dispatch(runQueries(exploreId));
  94. };
  95. }
  96. /**
  97. * Query change handler for the query row with the given index.
  98. * If `override` is reset the query modifications and run the queries. Use this to set queries via a link.
  99. */
  100. export function changeQuery(
  101. exploreId: ExploreId,
  102. query: DataQuery,
  103. index: number,
  104. override: boolean
  105. ): ThunkResult<void> {
  106. return dispatch => {
  107. // Null query means reset
  108. if (query === null) {
  109. query = { ...generateEmptyQuery(index) };
  110. }
  111. dispatch(changeQueryAction({ exploreId, query, index, override }));
  112. if (override) {
  113. dispatch(runQueries(exploreId));
  114. }
  115. };
  116. }
  117. /**
  118. * Keep track of the Explore container size, in particular the width.
  119. * The width will be used to calculate graph intervals (number of datapoints).
  120. */
  121. export function changeSize(
  122. exploreId: ExploreId,
  123. { height, width }: { height: number; width: number }
  124. ): ActionOf<ChangeSizePayload> {
  125. return changeSizeAction({ exploreId, height, width });
  126. }
  127. /**
  128. * Change the time range of Explore. Usually called from the Timepicker or a graph interaction.
  129. */
  130. export function changeTime(exploreId: ExploreId, range: TimeRange): ThunkResult<void> {
  131. return dispatch => {
  132. dispatch(changeTimeAction({ exploreId, range }));
  133. dispatch(runQueries(exploreId));
  134. };
  135. }
  136. /**
  137. * Clear all queries and results.
  138. */
  139. export function clearQueries(exploreId: ExploreId): ThunkResult<void> {
  140. return dispatch => {
  141. dispatch(scanStopAction({ exploreId }));
  142. dispatch(clearQueriesAction({ exploreId }));
  143. dispatch(stateSave());
  144. };
  145. }
  146. /**
  147. * Initialize Explore state with state from the URL and the React component.
  148. * Call this only on components for with the Explore state has not been initialized.
  149. */
  150. export function initializeExplore(
  151. exploreId: ExploreId,
  152. datasourceName: string,
  153. queries: DataQuery[],
  154. range: RawTimeRange,
  155. containerWidth: number,
  156. eventBridge: Emitter,
  157. ui: ExploreUIState
  158. ): ThunkResult<void> {
  159. return async dispatch => {
  160. const exploreDatasources: DataSourceSelectItem[] = getDatasourceSrv()
  161. .getExternal()
  162. .map(ds => ({
  163. value: ds.name,
  164. name: ds.name,
  165. meta: ds.meta,
  166. }));
  167. dispatch(
  168. initializeExploreAction({
  169. exploreId,
  170. containerWidth,
  171. eventBridge,
  172. exploreDatasources,
  173. queries,
  174. range,
  175. ui,
  176. })
  177. );
  178. if (exploreDatasources.length >= 1) {
  179. let instance;
  180. if (datasourceName) {
  181. try {
  182. instance = await getDatasourceSrv().get(datasourceName);
  183. } catch (error) {
  184. console.error(error);
  185. }
  186. }
  187. // Checking on instance here because requested datasource could be deleted already
  188. if (!instance) {
  189. instance = await getDatasourceSrv().get();
  190. }
  191. dispatch(updateDatasourceInstanceAction({ exploreId, datasourceInstance: instance }));
  192. try {
  193. await dispatch(loadDatasource(exploreId, instance));
  194. } catch (error) {
  195. console.error(error);
  196. return;
  197. }
  198. dispatch(runQueries(exploreId, true));
  199. } else {
  200. dispatch(loadDatasourceMissingAction({ exploreId }));
  201. }
  202. };
  203. }
  204. /**
  205. * Datasource loading was successfully completed. The instance is stored in the state as well in case we need to
  206. * run datasource-specific code. Existing queries are imported to the new datasource if an importer exists,
  207. * e.g., Prometheus -> Loki queries.
  208. */
  209. export const loadDatasourceSuccess = (exploreId: ExploreId, instance: any): ActionOf<LoadDatasourceSuccessPayload> => {
  210. // Capabilities
  211. const supportsGraph = instance.meta.metrics;
  212. const supportsLogs = instance.meta.logs;
  213. const supportsTable = instance.meta.tables;
  214. // Custom components
  215. const StartPage = instance.pluginExports.ExploreStartPage;
  216. const historyKey = `grafana.explore.history.${instance.meta.id}`;
  217. const history = store.getObject(historyKey, []);
  218. // Save last-used datasource
  219. store.set(LAST_USED_DATASOURCE_KEY, instance.name);
  220. return loadDatasourceSuccessAction({
  221. exploreId,
  222. StartPage,
  223. datasourceInstance: instance,
  224. history,
  225. showingStartPage: Boolean(StartPage),
  226. supportsGraph,
  227. supportsLogs,
  228. supportsTable,
  229. });
  230. };
  231. export function importQueries(
  232. exploreId: ExploreId,
  233. queries: DataQuery[],
  234. sourceDataSource: DataSourceApi,
  235. targetDataSource: DataSourceApi
  236. ) {
  237. return async dispatch => {
  238. let importedQueries = queries;
  239. // Check if queries can be imported from previously selected datasource
  240. if (sourceDataSource.meta.id === targetDataSource.meta.id) {
  241. // Keep same queries if same type of datasource
  242. importedQueries = [...queries];
  243. } else if (targetDataSource.importQueries) {
  244. // Datasource-specific importers
  245. importedQueries = await targetDataSource.importQueries(queries, sourceDataSource.meta);
  246. } else {
  247. // Default is blank queries
  248. importedQueries = ensureQueries();
  249. }
  250. const nextQueries = importedQueries.map((q, i) => ({
  251. ...q,
  252. ...generateEmptyQuery(i),
  253. }));
  254. dispatch(queriesImportedAction({ exploreId, queries: nextQueries }));
  255. };
  256. }
  257. /**
  258. * Main action to asynchronously load a datasource. Dispatches lots of smaller actions for feedback.
  259. */
  260. export function loadDatasource(exploreId: ExploreId, instance: DataSourceApi): ThunkResult<void> {
  261. return async (dispatch, getState) => {
  262. const datasourceName = instance.name;
  263. // Keep ID to track selection
  264. dispatch(loadDatasourcePendingAction({ exploreId, requestedDatasourceName: datasourceName }));
  265. let datasourceError = null;
  266. try {
  267. const testResult = await instance.testDatasource();
  268. datasourceError = testResult.status === 'success' ? null : testResult.message;
  269. } catch (error) {
  270. datasourceError = (error && error.statusText) || 'Network error';
  271. }
  272. if (datasourceError) {
  273. dispatch(loadDatasourceFailureAction({ exploreId, error: datasourceError }));
  274. return Promise.reject(`${datasourceName} loading failed`);
  275. }
  276. if (datasourceName !== getState().explore[exploreId].requestedDatasourceName) {
  277. // User already changed datasource again, discard results
  278. return;
  279. }
  280. if (instance.init) {
  281. instance.init();
  282. }
  283. if (datasourceName !== getState().explore[exploreId].requestedDatasourceName) {
  284. // User already changed datasource again, discard results
  285. return;
  286. }
  287. dispatch(loadDatasourceSuccess(exploreId, instance));
  288. return Promise.resolve();
  289. };
  290. }
  291. /**
  292. * Action to modify a query given a datasource-specific modifier action.
  293. * @param exploreId Explore area
  294. * @param modification Action object with a type, e.g., ADD_FILTER
  295. * @param index Optional query row index. If omitted, the modification is applied to all query rows.
  296. * @param modifier Function that executes the modification, typically `datasourceInstance.modifyQueries`.
  297. */
  298. export function modifyQueries(
  299. exploreId: ExploreId,
  300. modification: QueryFixAction,
  301. index: number,
  302. modifier: any
  303. ): ThunkResult<void> {
  304. return dispatch => {
  305. dispatch(modifyQueriesAction({ exploreId, modification, index, modifier }));
  306. if (!modification.preventSubmit) {
  307. dispatch(runQueries(exploreId));
  308. }
  309. };
  310. }
  311. /**
  312. * Mark a query transaction as failed with an error extracted from the query response.
  313. * The transaction will be marked as `done`.
  314. */
  315. export function queryTransactionFailure(
  316. exploreId: ExploreId,
  317. transactionId: string,
  318. response: any,
  319. datasourceId: string
  320. ): ThunkResult<void> {
  321. return (dispatch, getState) => {
  322. const { datasourceInstance, queryTransactions } = getState().explore[exploreId];
  323. if (datasourceInstance.meta.id !== datasourceId || response.cancelled) {
  324. // Navigated away, queries did not matter
  325. return;
  326. }
  327. // Transaction might have been discarded
  328. if (!queryTransactions.find(qt => qt.id === transactionId)) {
  329. return;
  330. }
  331. console.error(response);
  332. let error: string;
  333. let errorDetails: string;
  334. if (response.data) {
  335. if (typeof response.data === 'string') {
  336. error = response.data;
  337. } else if (response.data.error) {
  338. error = response.data.error;
  339. if (response.data.response) {
  340. errorDetails = response.data.response;
  341. }
  342. } else {
  343. throw new Error('Could not handle error response');
  344. }
  345. } else if (response.message) {
  346. error = response.message;
  347. } else if (typeof response === 'string') {
  348. error = response;
  349. } else {
  350. error = 'Unknown error during query transaction. Please check JS console logs.';
  351. }
  352. // Mark transactions as complete
  353. const nextQueryTransactions = queryTransactions.map(qt => {
  354. if (qt.id === transactionId) {
  355. return {
  356. ...qt,
  357. error,
  358. errorDetails,
  359. done: true,
  360. };
  361. }
  362. return qt;
  363. });
  364. dispatch(queryTransactionFailureAction({ exploreId, queryTransactions: nextQueryTransactions }));
  365. };
  366. }
  367. /**
  368. * Complete a query transaction, mark the transaction as `done` and store query state in URL.
  369. * If the transaction was started by a scanner, it keeps on scanning for more results.
  370. * Side-effect: the query is stored in localStorage.
  371. * @param exploreId Explore area
  372. * @param transactionId ID
  373. * @param result Response from `datasourceInstance.query()`
  374. * @param latency Duration between request and response
  375. * @param queries Queries from all query rows
  376. * @param datasourceId Origin datasource instance, used to discard results if current datasource is different
  377. */
  378. export function queryTransactionSuccess(
  379. exploreId: ExploreId,
  380. transactionId: string,
  381. result: any,
  382. latency: number,
  383. queries: DataQuery[],
  384. datasourceId: string
  385. ): ThunkResult<void> {
  386. return (dispatch, getState) => {
  387. const { datasourceInstance, history, queryTransactions, scanner, scanning } = getState().explore[exploreId];
  388. // If datasource already changed, results do not matter
  389. if (datasourceInstance.meta.id !== datasourceId) {
  390. return;
  391. }
  392. // Transaction might have been discarded
  393. const transaction = queryTransactions.find(qt => qt.id === transactionId);
  394. if (!transaction) {
  395. return;
  396. }
  397. // Get query hints
  398. let hints: QueryHint[];
  399. if (datasourceInstance.getQueryHints) {
  400. hints = datasourceInstance.getQueryHints(transaction.query, result);
  401. }
  402. // Mark transactions as complete and attach result
  403. const nextQueryTransactions = queryTransactions.map(qt => {
  404. if (qt.id === transactionId) {
  405. return {
  406. ...qt,
  407. hints,
  408. latency,
  409. result,
  410. done: true,
  411. };
  412. }
  413. return qt;
  414. });
  415. // Side-effect: Saving history in localstorage
  416. const nextHistory = updateHistory(history, datasourceId, queries);
  417. dispatch(
  418. queryTransactionSuccessAction({
  419. exploreId,
  420. history: nextHistory,
  421. queryTransactions: nextQueryTransactions,
  422. })
  423. );
  424. // Keep scanning for results if this was the last scanning transaction
  425. if (scanning) {
  426. if (_.size(result) === 0) {
  427. const other = nextQueryTransactions.find(qt => qt.scanning && !qt.done);
  428. if (!other) {
  429. const range = scanner();
  430. dispatch(scanRangeAction({ exploreId, range }));
  431. }
  432. } else {
  433. // We can stop scanning if we have a result
  434. dispatch(scanStopAction({ exploreId }));
  435. }
  436. }
  437. };
  438. }
  439. /**
  440. * Main action to run queries and dispatches sub-actions based on which result viewers are active
  441. */
  442. export function runQueries(exploreId: ExploreId, ignoreUIState = false) {
  443. return (dispatch, getState) => {
  444. const {
  445. datasourceInstance,
  446. queries,
  447. showingLogs,
  448. showingGraph,
  449. showingTable,
  450. supportsGraph,
  451. supportsLogs,
  452. supportsTable,
  453. } = getState().explore[exploreId];
  454. if (!hasNonEmptyQuery(queries)) {
  455. dispatch(runQueriesEmptyAction({ exploreId }));
  456. dispatch(stateSave()); // Remember to saves to state and update location
  457. return;
  458. }
  459. // Some datasource's query builders allow per-query interval limits,
  460. // but we're using the datasource interval limit for now
  461. const interval = datasourceInstance.interval;
  462. // Keep table queries first since they need to return quickly
  463. if ((ignoreUIState || showingTable) && supportsTable) {
  464. dispatch(
  465. runQueriesForType(
  466. exploreId,
  467. 'Table',
  468. {
  469. interval,
  470. format: 'table',
  471. instant: true,
  472. valueWithRefId: true,
  473. },
  474. data => data[0]
  475. )
  476. );
  477. }
  478. if ((ignoreUIState || showingGraph) && supportsGraph) {
  479. dispatch(
  480. runQueriesForType(
  481. exploreId,
  482. 'Graph',
  483. {
  484. interval,
  485. format: 'time_series',
  486. instant: false,
  487. },
  488. makeTimeSeriesList
  489. )
  490. );
  491. }
  492. if ((ignoreUIState || showingLogs) && supportsLogs) {
  493. dispatch(runQueriesForType(exploreId, 'Logs', { interval, format: 'logs' }));
  494. }
  495. dispatch(stateSave());
  496. };
  497. }
  498. /**
  499. * Helper action to build a query transaction object and handing the query to the datasource.
  500. * @param exploreId Explore area
  501. * @param resultType Result viewer that will be associated with this query result
  502. * @param queryOptions Query options as required by the datasource's `query()` function.
  503. * @param resultGetter Optional result extractor, e.g., if the result is a list and you only need the first element.
  504. */
  505. function runQueriesForType(
  506. exploreId: ExploreId,
  507. resultType: ResultType,
  508. queryOptions: QueryOptions,
  509. resultGetter?: any
  510. ) {
  511. return async (dispatch, getState) => {
  512. const { datasourceInstance, eventBridge, queries, queryIntervals, range, scanning } = getState().explore[exploreId];
  513. const datasourceId = datasourceInstance.meta.id;
  514. // Run all queries concurrently
  515. queries.forEach(async (query, rowIndex) => {
  516. const transaction = buildQueryTransaction(
  517. query,
  518. rowIndex,
  519. resultType,
  520. queryOptions,
  521. range,
  522. queryIntervals,
  523. scanning
  524. );
  525. dispatch(queryTransactionStartAction({ exploreId, resultType, rowIndex, transaction }));
  526. try {
  527. const now = Date.now();
  528. const res = await datasourceInstance.query(transaction.options);
  529. eventBridge.emit('data-received', res.data || []);
  530. const latency = Date.now() - now;
  531. const results = resultGetter ? resultGetter(res.data) : res.data;
  532. dispatch(queryTransactionSuccess(exploreId, transaction.id, results, latency, queries, datasourceId));
  533. } catch (response) {
  534. eventBridge.emit('data-error', response);
  535. dispatch(queryTransactionFailure(exploreId, transaction.id, response, datasourceId));
  536. }
  537. });
  538. };
  539. }
  540. /**
  541. * Start a scan for more results using the given scanner.
  542. * @param exploreId Explore area
  543. * @param scanner Function that a) returns a new time range and b) triggers a query run for the new range
  544. */
  545. export function scanStart(exploreId: ExploreId, scanner: RangeScanner): ThunkResult<void> {
  546. return dispatch => {
  547. // Register the scanner
  548. dispatch(scanStartAction({ exploreId, scanner }));
  549. // Scanning must trigger query run, and return the new range
  550. const range = scanner();
  551. // Set the new range to be displayed
  552. dispatch(scanRangeAction({ exploreId, range }));
  553. };
  554. }
  555. /**
  556. * Reset queries to the given queries. Any modifications will be discarded.
  557. * Use this action for clicks on query examples. Triggers a query run.
  558. */
  559. export function setQueries(exploreId: ExploreId, rawQueries: DataQuery[]): ThunkResult<void> {
  560. return dispatch => {
  561. // Inject react keys into query objects
  562. const queries = rawQueries.map(q => ({ ...q, ...generateEmptyQuery() }));
  563. dispatch(setQueriesAction({ exploreId, queries }));
  564. dispatch(runQueries(exploreId));
  565. };
  566. }
  567. /**
  568. * Close the split view and save URL state.
  569. */
  570. export function splitClose(): ThunkResult<void> {
  571. return dispatch => {
  572. dispatch(splitCloseAction());
  573. dispatch(stateSave());
  574. };
  575. }
  576. /**
  577. * Open the split view and copy the left state to be the right state.
  578. * The right state is automatically initialized.
  579. * The copy keeps all query modifications but wipes the query results.
  580. */
  581. export function splitOpen(): ThunkResult<void> {
  582. return (dispatch, getState) => {
  583. // Clone left state to become the right state
  584. const leftState = getState().explore.left;
  585. const itemState = {
  586. ...leftState,
  587. queryTransactions: [],
  588. queries: leftState.queries.slice(),
  589. };
  590. dispatch(splitOpenAction({ itemState }));
  591. dispatch(stateSave());
  592. };
  593. }
  594. /**
  595. * Saves Explore state to URL using the `left` and `right` parameters.
  596. * If split view is not active, `right` will not be set.
  597. */
  598. export function stateSave() {
  599. return (dispatch, getState) => {
  600. const { left, right, split } = getState().explore;
  601. const urlStates: { [index: string]: string } = {};
  602. const leftUrlState: ExploreUrlState = {
  603. datasource: left.datasourceInstance.name,
  604. queries: left.queries.map(clearQueryKeys),
  605. range: left.range,
  606. ui: {
  607. showingGraph: left.showingGraph,
  608. showingLogs: left.showingLogs,
  609. showingTable: left.showingTable,
  610. },
  611. };
  612. urlStates.left = serializeStateToUrlParam(leftUrlState, true);
  613. if (split) {
  614. const rightUrlState: ExploreUrlState = {
  615. datasource: right.datasourceInstance.name,
  616. queries: right.queries.map(clearQueryKeys),
  617. range: right.range,
  618. ui: { showingGraph: right.showingGraph, showingLogs: right.showingLogs, showingTable: right.showingTable },
  619. };
  620. urlStates.right = serializeStateToUrlParam(rightUrlState, true);
  621. }
  622. dispatch(updateLocation({ query: urlStates }));
  623. };
  624. }
  625. /**
  626. * Creates action to collapse graph/logs/table panel. When panel is collapsed,
  627. * queries won't be run
  628. */
  629. const togglePanelActionCreator = (
  630. actionCreator:
  631. | ActionCreator<ToggleGraphPayload>
  632. | ActionCreator<ToggleLogsPayload>
  633. | ActionCreator<ToggleTablePayload>
  634. ) => (exploreId: ExploreId) => {
  635. return (dispatch, getState) => {
  636. let shouldRunQueries;
  637. dispatch(actionCreator({ exploreId }));
  638. dispatch(stateSave());
  639. switch (actionCreator.type) {
  640. case toggleGraphAction.type:
  641. shouldRunQueries = getState().explore[exploreId].showingGraph;
  642. break;
  643. case toggleLogsAction.type:
  644. shouldRunQueries = getState().explore[exploreId].showingLogs;
  645. break;
  646. case toggleTableAction.type:
  647. shouldRunQueries = getState().explore[exploreId].showingTable;
  648. break;
  649. }
  650. if (shouldRunQueries) {
  651. dispatch(runQueries(exploreId));
  652. }
  653. };
  654. };
  655. /**
  656. * Expand/collapse the graph result viewer. When collapsed, graph queries won't be run.
  657. */
  658. export const toggleGraph = togglePanelActionCreator(toggleGraphAction);
  659. /**
  660. * Expand/collapse the logs result viewer. When collapsed, log queries won't be run.
  661. */
  662. export const toggleLogs = togglePanelActionCreator(toggleLogsAction);
  663. /**
  664. * Expand/collapse the table result viewer. When collapsed, table queries won't be run.
  665. */
  666. export const toggleTable = togglePanelActionCreator(toggleTableAction);