ClassicConditions.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import React, { FC } from 'react';
  2. import { SelectableValue } from '@grafana/data';
  3. import { Button, Icon, InlineField, InlineFieldRow } from '@grafana/ui';
  4. import { ClassicCondition, ExpressionQuery } from '../types';
  5. import { defaultCondition } from '../utils/expressionTypes';
  6. import { Condition } from './Condition';
  7. interface Props {
  8. query: ExpressionQuery;
  9. refIds: Array<SelectableValue<string>>;
  10. onChange: (query: ExpressionQuery) => void;
  11. }
  12. export const ClassicConditions: FC<Props> = ({ onChange, query, refIds }) => {
  13. const onConditionChange = (condition: ClassicCondition, index: number) => {
  14. if (query.conditions) {
  15. onChange({
  16. ...query,
  17. conditions: [...query.conditions.slice(0, index), condition, ...query.conditions.slice(index + 1)],
  18. });
  19. }
  20. };
  21. const onAddCondition = () => {
  22. if (query.conditions) {
  23. onChange({
  24. ...query,
  25. conditions: query.conditions.length > 0 ? [...query.conditions, defaultCondition] : [defaultCondition],
  26. });
  27. }
  28. };
  29. const onRemoveCondition = (index: number) => {
  30. if (query.conditions) {
  31. const condition = query.conditions[index];
  32. const conditions = query.conditions
  33. .filter((c) => c !== condition)
  34. .map((c, index) => {
  35. if (index === 0) {
  36. return {
  37. ...c,
  38. operator: {
  39. type: 'when',
  40. },
  41. };
  42. }
  43. return c;
  44. });
  45. onChange({
  46. ...query,
  47. conditions,
  48. });
  49. }
  50. };
  51. return (
  52. <div>
  53. <InlineFieldRow>
  54. <InlineField label="Conditions" labelWidth={14}>
  55. <div>
  56. {query.conditions?.map((condition, index) => {
  57. if (!condition) {
  58. return;
  59. }
  60. return (
  61. <Condition
  62. key={index}
  63. index={index}
  64. condition={condition}
  65. onChange={(condition: ClassicCondition) => onConditionChange(condition, index)}
  66. onRemoveCondition={onRemoveCondition}
  67. refIds={refIds}
  68. />
  69. );
  70. })}
  71. </div>
  72. </InlineField>
  73. </InlineFieldRow>
  74. <Button variant="secondary" type="button" onClick={onAddCondition}>
  75. <Icon name="plus-circle" />
  76. </Button>
  77. </div>
  78. );
  79. };