OptionElement.tsx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import React, { FC } from 'react';
  2. import { FormAPI, Input, InputControl, Select, TextArea } from '@grafana/ui';
  3. import { NotificationChannelOption } from '../../../types';
  4. interface Props extends Pick<FormAPI<any>, 'register' | 'control'> {
  5. option: NotificationChannelOption;
  6. invalid?: boolean;
  7. }
  8. export const OptionElement: FC<Props> = ({ control, option, register, invalid }) => {
  9. const modelValue = option.secure ? `secureSettings.${option.propertyName}` : `settings.${option.propertyName}`;
  10. switch (option.element) {
  11. case 'input':
  12. return (
  13. <Input
  14. {...register(`${modelValue}`, {
  15. required: option.required ? 'Required' : false,
  16. validate: (v) => (option.validationRule !== '' ? validateOption(v, option.validationRule) : true),
  17. })}
  18. invalid={invalid}
  19. type={option.inputType}
  20. placeholder={option.placeholder}
  21. />
  22. );
  23. case 'select':
  24. return (
  25. <InputControl
  26. control={control}
  27. name={`${modelValue}`}
  28. render={({ field: { ref, ...field } }) => (
  29. <Select {...field} options={option.selectOptions ?? undefined} invalid={invalid} />
  30. )}
  31. />
  32. );
  33. case 'textarea':
  34. return (
  35. <TextArea
  36. invalid={invalid}
  37. {...register(`${modelValue}`, {
  38. required: option.required ? 'Required' : false,
  39. validate: (v) => (option.validationRule !== '' ? validateOption(v, option.validationRule) : true),
  40. })}
  41. />
  42. );
  43. default:
  44. console.error('Element not supported', option.element);
  45. return null;
  46. }
  47. };
  48. const validateOption = (value: string, validationRule: string) => {
  49. return RegExp(validationRule).test(value) ? true : 'Invalid format';
  50. };