CustomParamSelect.tsx 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import React from 'react';
  2. import { useFormContext } from 'react-hook-form';
  3. import { TopicConfigValue } from 'redux/interfaces';
  4. import { ErrorMessage } from '@hookform/error-message';
  5. import { TOPIC_CUSTOM_PARAMS } from 'lib/constants';
  6. import { INDEX_PREFIX } from './CustomParams';
  7. export interface CustomParamSelectProps {
  8. isDisabled: boolean;
  9. index: string;
  10. name: string;
  11. existingFields: string[];
  12. onNameChange: (inputName: string, name: string) => void;
  13. }
  14. const CustomParamSelect: React.FC<CustomParamSelectProps> = ({
  15. isDisabled,
  16. index,
  17. name,
  18. existingFields,
  19. onNameChange,
  20. }) => {
  21. const {
  22. register,
  23. getValues,
  24. trigger,
  25. formState: { errors },
  26. } = useFormContext();
  27. const optInputName = `${index}[name]`;
  28. const selectedMustBeUniq = (selected: string) => {
  29. const values = getValues();
  30. const customParamsValues: TopicConfigValue = values.customParams;
  31. const valid = !Object.entries(customParamsValues).some(
  32. ([key, customParam]) => {
  33. return (
  34. `${INDEX_PREFIX}.${key}` !== index && selected === customParam.name
  35. );
  36. }
  37. );
  38. return valid || 'Custom Parameter must be unique';
  39. };
  40. const onChange =
  41. (inputName: string) => (event: React.ChangeEvent<HTMLSelectElement>) => {
  42. trigger(inputName);
  43. onNameChange(index, event.target.value);
  44. };
  45. return (
  46. <>
  47. <label className="label">Custom Parameter</label>
  48. <div className="select is-block">
  49. <select
  50. {...register(optInputName, {
  51. required: 'Custom Parameter is required.',
  52. validate: { unique: (selected) => selectedMustBeUniq(selected) },
  53. })}
  54. onChange={onChange(optInputName)}
  55. disabled={isDisabled}
  56. defaultValue={name}
  57. >
  58. <option value="">Select</option>
  59. {Object.keys(TOPIC_CUSTOM_PARAMS).map((opt) => (
  60. <option
  61. key={opt}
  62. value={opt}
  63. disabled={existingFields.includes(opt)}
  64. >
  65. {opt}
  66. </option>
  67. ))}
  68. </select>
  69. <p className="help is-danger">
  70. <ErrorMessage errors={errors} name={optInputName} />
  71. </p>
  72. </div>
  73. </>
  74. );
  75. };
  76. export default React.memo(CustomParamSelect);