QueryHeader.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { pick } from 'lodash';
  2. import React from 'react';
  3. import { SelectableValue, ExploreMode } from '@grafana/data';
  4. import { EditorHeader, InlineSelect } from '@grafana/experimental';
  5. import { CloudWatchDatasource } from '../datasource';
  6. import { useRegions } from '../hooks';
  7. import { CloudWatchQuery, CloudWatchQueryMode } from '../types';
  8. import MetricsQueryHeader from './MetricsQueryEditor/MetricsQueryHeader';
  9. interface QueryHeaderProps {
  10. query: CloudWatchQuery;
  11. datasource: CloudWatchDatasource;
  12. onChange: (query: CloudWatchQuery) => void;
  13. onRunQuery: () => void;
  14. sqlCodeEditorIsDirty: boolean;
  15. onRegionChange?: (region: string) => Promise<void>;
  16. }
  17. const apiModes: Array<SelectableValue<CloudWatchQueryMode>> = [
  18. { label: 'CloudWatch Metrics', value: 'Metrics' },
  19. { label: 'CloudWatch Logs', value: 'Logs' },
  20. ];
  21. const QueryHeader: React.FC<QueryHeaderProps> = ({
  22. query,
  23. sqlCodeEditorIsDirty,
  24. datasource,
  25. onChange,
  26. onRunQuery,
  27. onRegionChange,
  28. }) => {
  29. const { queryMode, region } = query;
  30. const [regions, regionIsLoading] = useRegions(datasource);
  31. const onQueryModeChange = ({ value }: SelectableValue<CloudWatchQueryMode>) => {
  32. if (value !== queryMode) {
  33. const commonProps = pick(query, 'id', 'region', 'namespace', 'refId', 'hide', 'key', 'queryType', 'datasource');
  34. onChange({
  35. ...commonProps,
  36. queryMode: value,
  37. } as CloudWatchQuery);
  38. }
  39. };
  40. const onRegion = async ({ value }: SelectableValue<string>) => {
  41. if (onRegionChange) {
  42. await onRegionChange(value ?? 'default');
  43. }
  44. onChange({
  45. ...query,
  46. region: value,
  47. } as CloudWatchQuery);
  48. };
  49. return (
  50. <EditorHeader>
  51. <InlineSelect
  52. label="Region"
  53. value={region}
  54. placeholder="Select region"
  55. allowCustomValue
  56. onChange={({ value: region }) => region && onRegion({ value: region })}
  57. options={regions}
  58. isLoading={regionIsLoading}
  59. />
  60. <InlineSelect aria-label="Query mode" value={queryMode} options={apiModes} onChange={onQueryModeChange} />
  61. {queryMode === ExploreMode.Metrics && (
  62. <MetricsQueryHeader
  63. query={query}
  64. datasource={datasource}
  65. onChange={onChange}
  66. onRunQuery={onRunQuery}
  67. sqlCodeEditorIsDirty={sqlCodeEditorIsDirty}
  68. />
  69. )}
  70. </EditorHeader>
  71. );
  72. };
  73. export default QueryHeader;