CustomParams.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import React from 'react';
  2. import { omit, reject } from 'lodash';
  3. import { TopicFormCustomParams } from 'redux/interfaces';
  4. import CustomParamSelect from './CustomParamSelect';
  5. import CustomParamValue from './CustomParamValue';
  6. import CustomParamAction from './CustomParamAction';
  7. const DEFAULT_INDEX = 'default';
  8. export const INDEX_PREFIX = 'customParams';
  9. export const isFirstParam = (index: string) => (index === DEFAULT_INDEX);
  10. interface Props {
  11. isSubmitting: boolean;
  12. }
  13. const CustomParams: React.FC<Props> = ({
  14. isSubmitting,
  15. }) => {
  16. const [formCustomParams, setFormCustomParams] = React.useState<TopicFormCustomParams>({
  17. byIndex: { [DEFAULT_INDEX]: { name: '', value: '' } },
  18. allIndexes: [DEFAULT_INDEX],
  19. });
  20. const onAdd = (event: React.MouseEvent<HTMLButtonElement>) => {
  21. event.preventDefault();
  22. const newIndex = `${INDEX_PREFIX}.${new Date().getTime()}`;
  23. setFormCustomParams({
  24. ...formCustomParams,
  25. byIndex: {
  26. ...formCustomParams.byIndex,
  27. [newIndex]: { name: '', value: '' },
  28. },
  29. allIndexes: [
  30. formCustomParams.allIndexes[0],
  31. newIndex,
  32. ...formCustomParams.allIndexes.slice(1),
  33. ],
  34. });
  35. }
  36. const onRemove = (index: string) => {
  37. setFormCustomParams({
  38. ...formCustomParams,
  39. byIndex: omit(formCustomParams.byIndex, index),
  40. allIndexes: reject(formCustomParams.allIndexes, (i) => (i === index)),
  41. });
  42. }
  43. return (
  44. <>
  45. {
  46. formCustomParams.allIndexes.map((index) => (
  47. <div className="columns is-centered" key={index}>
  48. <div className="column">
  49. <CustomParamSelect
  50. index={index}
  51. isDisabled={isFirstParam(index) || isSubmitting}
  52. name={formCustomParams.byIndex[index].name}
  53. />
  54. </div>
  55. <div className="column">
  56. <CustomParamValue
  57. index={index}
  58. isDisabled={isFirstParam(index) || isSubmitting}
  59. name={formCustomParams.byIndex[index].name}
  60. defaultValue={formCustomParams.byIndex[index].value}
  61. />
  62. </div>
  63. <div className="column is-narrow">
  64. <CustomParamAction
  65. index={index}
  66. onAdd={onAdd}
  67. onRemove={onRemove}
  68. />
  69. </div>
  70. </div>
  71. ))
  72. }
  73. </>
  74. );
  75. };
  76. export default CustomParams;