SubscriptionField.tsx 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import React, { useCallback, useMemo } from 'react';
  2. import { SelectableValue } from '@grafana/data';
  3. import { Select, MultiSelect } from '@grafana/ui';
  4. import { AzureMonitorQuery, AzureQueryEditorFieldProps, AzureMonitorOption, AzureQueryType } from '../types';
  5. import { findOptions } from '../utils/common';
  6. import { Field } from './Field';
  7. interface SubscriptionFieldProps extends AzureQueryEditorFieldProps {
  8. onQueryChange: (newQuery: AzureMonitorQuery) => void;
  9. subscriptions: AzureMonitorOption[];
  10. multiSelect?: boolean;
  11. }
  12. const SubscriptionField: React.FC<SubscriptionFieldProps> = ({
  13. query,
  14. subscriptions,
  15. variableOptionGroup,
  16. onQueryChange,
  17. multiSelect = false,
  18. }) => {
  19. const handleChange = useCallback(
  20. (change: SelectableValue<string>) => {
  21. if (!change.value) {
  22. return;
  23. }
  24. let newQuery: AzureMonitorQuery = {
  25. ...query,
  26. subscription: change.value,
  27. };
  28. if (query.queryType === AzureQueryType.AzureMonitor) {
  29. newQuery.azureMonitor = {
  30. ...newQuery.azureMonitor,
  31. resourceGroup: undefined,
  32. metricDefinition: undefined,
  33. metricNamespace: undefined,
  34. resourceName: undefined,
  35. metricName: undefined,
  36. aggregation: undefined,
  37. timeGrain: '',
  38. dimensionFilters: [],
  39. };
  40. }
  41. onQueryChange(newQuery);
  42. },
  43. [query, onQueryChange]
  44. );
  45. const onSubscriptionsChange = useCallback(
  46. (change: Array<SelectableValue<string>>) => {
  47. if (!change) {
  48. return;
  49. }
  50. query.subscriptions = change.map((c) => c.value ?? '');
  51. onQueryChange(query);
  52. },
  53. [query, onQueryChange]
  54. );
  55. const options = useMemo(() => [...subscriptions, variableOptionGroup], [subscriptions, variableOptionGroup]);
  56. return multiSelect ? (
  57. <Field label="Subscriptions">
  58. <MultiSelect
  59. isClearable
  60. value={findOptions([...subscriptions, ...variableOptionGroup.options], query.subscriptions)}
  61. inputId="azure-monitor-subscriptions-field"
  62. onChange={onSubscriptionsChange}
  63. options={options}
  64. width={38}
  65. />
  66. </Field>
  67. ) : (
  68. <Field label="Subscription">
  69. <Select
  70. value={query.subscription}
  71. inputId="azure-monitor-subscriptions-field"
  72. onChange={handleChange}
  73. options={options}
  74. width={38}
  75. allowCustomValue
  76. />
  77. </Field>
  78. );
  79. };
  80. export default SubscriptionField;